OILS / ysh / grammar.pgen2 View on Github | oilshell.org

528 lines, 179 significant
1# Grammar for YSH.
2# Adapted from the Python 3.7 expression grammar, with several changes!
3#
4# TODO:
5# - List comprehensions
6# - There's also chaining => and maybe implicit vectorization ==>
7# - But list comprehensions are more familiar, and they are concise
8# - Generator expressions?
9# - Do we need lambdas?
10
11# Note: trailing commas are allowed:
12# {k: mydict,}
13# [mylist,]
14# mytuple,
15# f(args,)
16# func f(params,)
17#
18# Kinds used:
19# VSub, Left, Right, Expr, Op, Arith, Char, Eof, Unknown
20
21# YSH patch: removed @=
22augassign: (
23 '+=' | '-=' | '*=' | '/=' |
24 '**=' | '//=' | '%=' |
25 '&=' | '|=' | '^=' | '<<=' | '>>='
26)
27
28test: or_test ['if' or_test 'else' test] | lambdef
29
30# Lambdas follow the same rules as Python:
31#
32# |x| 1, 2 == (|x| 1), 2
33# |x| x if True else 42 == |x| (x if True else 42)
34#
35# Python also had a test_nocond production like this: We don't need it because
36# we can't have multiple ifs.
37# [x for x in range(3) if lambda x: x if 1]
38#
39# The zero arg syntax like || 1 annoys me -- but this also works:
40# func() { return 1 }
41#
42# We used name_type_list rather than param_group because a default value like
43# x|y (bitwise or) conflicts with the | delimiter!
44#
45# TODO: consider this syntax:
46# fn (x) x # expression
47# fn (x) ^( echo hi ) # statement
48
49lambdef: '|' [name_type_list] '|' test
50
51or_test: and_test ('or' and_test)*
52and_test: not_test ('and' not_test)*
53not_test: 'not' not_test | comparison
54comparison: range_expr (comp_op range_expr)*
55
56# Unlike slice, beginning and end are required
57range_expr: expr ['..' expr]
58
59# YSH patch: remove legacy <>, add === and more
60comp_op: (
61 '<'|'>'|'==='|'>='|'<='|'!=='|'in'|'not' 'in'|'is'|'is' 'not'|
62 '~' | '!~' | '~~' | '!~~' | '~=='
63)
64
65# For lists and dicts. Note: In Python this was star_expr *foo
66splat_expr: '...' expr
67
68expr: xor_expr ('|' xor_expr)*
69xor_expr: and_expr ('^' and_expr)*
70and_expr: shift_expr ('&' shift_expr)*
71shift_expr: arith_expr (('<<'|'>>') arith_expr)*
72# YSH: add concatenation ++ with same precedence as +
73arith_expr: term (('+'|'-'|'++') term)*
74# YSH: removed '@' matrix mul
75term: factor (('*'|'/'|'//'|'%') factor)*
76factor: ('+'|'-'|'~') factor | power
77# YSH: removed Python 3 'await'
78power: atom trailer* ['**' factor]
79
80testlist_comp: (test|splat_expr) ( comp_for | (',' (test|splat_expr))* [','] )
81
82atom: (
83 '(' [testlist_comp] ')'
84 | '[' [testlist_comp] ']'
85 # Note: newlines are significant inside {}, unlike inside () and []
86 | '{' [Op_Newline] [dict] '}'
87 | '&' Expr_Name place_trailer*
88
89 # NOTE: These atoms are are allowed in typed array literals
90 | Expr_Name | Expr_Null | Expr_True | Expr_False
91
92 # Allow suffixes on floats and decimals
93 # e.g. 100 M is a function M which multiplies by 1_000_000
94 # e.g. 100 Mi is a function Mi which multiplies by 1024 * 1024
95 | Expr_Float [Expr_Name]
96 | Expr_DecInt [Expr_Name]
97
98 | Expr_BinInt | Expr_OctInt | Expr_HexInt
99
100 | Char_OneChar # char literal \n \\ etc.
101 | Char_UBraced # char literal \u{3bc}
102 | Char_Pound # char literal #'A' etc.
103
104 | dq_string | sq_string
105 # Expr_Symbol could be %mykey
106
107 | eggex
108 | literal_expr
109
110 # $foo is disallowed, but $? is allowed. Should be "$foo" to indicate a
111 # string, or ${foo:-}
112 | simple_var_sub
113 | sh_command_sub | braced_var_sub
114 | sh_array_literal
115 | old_sh_array_literal
116)
117
118literal_expr: '^[' expr ']'
119
120place_trailer: (
121 '[' subscriptlist ']'
122 | '.' Expr_Name
123)
124
125# var f = f(x)
126trailer: (
127 '(' [arglist] ')'
128 | '[' subscriptlist ']'
129
130 # Is a {} trailing useful for anything? It's not in Python or JS
131
132 | '.' Expr_Name
133 | '->' Expr_Name
134 | '=>' Expr_Name
135)
136
137# YSH patch: this is 'expr' instead of 'test'
138# - 1:(3<4) doesn't make any sense.
139# - And then this allows us to support a[3:] and a[:i] as special cases.
140# - First class slices have to be written 0:n.
141
142subscriptlist: subscript (',' subscript)* [',']
143
144# TODO: Add => as low precedence operator, for Func[Str, Int => Str]
145subscript: expr | [expr] ':' [expr]
146
147# TODO: => should be even lower precedence here too
148testlist: test (',' test)* [',']
149
150# Dict syntax resembles JavaScript
151# https://stackoverflow.com/questions/38948306/what-is-javascript-shorthand-property
152#
153# Examples:
154# {age: 20} is like {'age': 20}
155#
156# x = 'age'
157# d = %{[x]: 20} # Evaluate x as a variable
158# d = %{["foo$x"]: 20} # Another expression
159# d = %{[x, y]: 20} # Tuple key
160# d = %{key1, key1: 123}
161# Notes:
162# - Value is optional when the key is a name, because it can be taken from the
163# environment.
164# - We don't have:
165# - dict comprehensions. Maybe wait until LR parsing?
166# - Splatting with **
167
168dict_pair: (
169 Expr_Name [':' test]
170 | '[' testlist ']' ':' test
171 | sq_string ':' test
172 | dq_string ':' test
173)
174
175comma_newline: ',' [Op_Newline] | Op_Newline
176
177dict: dict_pair (comma_newline dict_pair)* [comma_newline]
178
179# This how Python implemented dict comprehensions. We can probably do the
180# same.
181#
182# dictorsetmaker: ( ((test ':' test | '**' expr)
183# (comp_for | (',' (test ':' test | '**' expr))* [','])) |
184# ((test | splat_expr)
185# (comp_for | (',' (test | splat_expr))* [','])) )
186
187# The reason that keywords are test nodes instead of NAME is that using NAME
188# results in an ambiguity. ast.c makes sure it's a NAME.
189# "test '=' test" is really "keyword '=' test", but we have no such token.
190# These need to be in a single rule to avoid grammar that is ambiguous
191# to our LL(1) parser. Even though 'test' includes '*expr' in splat_expr,
192# we explicitly match '*' here, too, to give it proper precedence.
193# Illegal combinations and orderings are blocked in ast.c:
194# multiple (test comp_for) arguments are blocked; keyword unpackings
195# that precede iterable unpackings are blocked; etc.
196
197argument: (
198 test [comp_for]
199 # named arg
200 | test '=' test
201 # splat. The ... goes before, not after, to be consistent with Python, JS,
202 # and the prefix @ operator.
203 | '...' test
204)
205
206# The grammar at call sites is less restrictive than at declaration sites.
207# ... can appear anywhere. Keyword args can appear anywhere too.
208arg_group: argument (',' argument)* [',']
209arglist: (
210 [arg_group]
211 [';' [arg_group]]
212)
213arglist3: (
214 [arg_group]
215 [';' [arg_group]]
216 [';' [argument]] # procs have an extra block argument
217)
218
219
220# YSH patch: test_nocond -> or_test. I believe this was trying to prevent the
221# "double if" ambiguity here:
222# #
223# [x for x in range(3) if lambda x: x if 1]
224#
225# but YSH doesn't supported "nested loops", so we don't have this problem.
226comp_for: 'for' name_type_list 'in' or_test ['if' or_test]
227
228
229#
230# Expressions that are New in YSH
231#
232
233# Notes:
234# - Most of these occur in 'atom' above
235# - You can write $mystr but not mystr. It has to be (mystr)
236array_item: (
237 Expr_Null | Expr_True | Expr_False
238 | Expr_Float | Expr_DecInt | Expr_BinInt | Expr_OctInt | Expr_HexInt
239 | dq_string | sq_string
240 | sh_command_sub | braced_var_sub | simple_var_sub
241 | '(' test ')'
242)
243sh_array_literal: ':|' Expr_CastedDummy Op_Pipe
244
245# TODO: remove old array
246old_sh_array_literal: '%(' Expr_CastedDummy Right_ShArrayLiteral
247sh_command_sub: ( '$(' | '@(' | '^(' ) Expr_CastedDummy Eof_RParen
248
249# Note: could add c"" too
250dq_string: (Left_DoubleQuote | Left_TDoubleQuote | Left_CaretDoubleQuote) Expr_CastedDummy Right_DoubleQuote
251sq_string: (
252 Left_SingleQuote | Left_TSingleQuote
253 | Left_RSingleQuote | Left_RTSingleQuote
254 | Left_DollarSingleQuote
255 | Left_USingleQuote | Left_UTSingleQuote
256 | Left_BSingleQuote | Left_BTSingleQuote
257) Expr_CastedDummy Right_SingleQuote
258
259braced_var_sub: '${' Expr_CastedDummy Right_DollarBrace
260
261simple_var_sub: (
262 # This is everything in Kind.VSub except VSub_Name, which is braced: ${foo}
263 #
264 # Note: we could allow $foo and $0, but disallow the rest in favor of ${@}
265 # and ${-}? Meh it's too inconsistent.
266 VSub_DollarName | VSub_Number
267 | VSub_Bang | VSub_At | VSub_Pound | VSub_Dollar | VSub_Star | VSub_Hyphen
268 | VSub_QMark
269 # NOTE: $? should be STATUS because it's an integer.
270)
271
272#
273# Assignment / Type Variables
274#
275# Several differences vs. Python:
276#
277# - no yield expression on RHS
278# - no star expressions on either side (Python 3) *x, y = 2, *b
279# - no multiple assignments like: var x = y = 3
280# - type annotation syntax is more restrictive # a: (1+2) = 3 is OK in python
281# - We're validating the lvalue here, instead of doing it in the "transformer".
282# We have the 'var' prefix which helps.
283
284# name_type use cases:
285# var x Int, y Int = 3, 5
286# / <capture d+ as date: int> /
287#
288# for x Int, y Int
289# [x for x Int, y Int in ...]
290#
291# func(x Int, y Int) - this is separate
292
293# Optional colon because we want both
294
295# var x: Int = 42 # colon looks nicer
296# proc p (; x Int, y Int; z Int) { echo hi } # colon gets in the way of ;
297
298name_type: Expr_Name [':'] [type_expr]
299name_type_list: name_type (',' name_type)*
300
301type_expr: Expr_Name [ '[' type_expr (',' type_expr)* ']' ]
302
303# NOTE: Eof_RParen and Eof_Backtick aren't allowed because we don't want 'var'
304# in command subs.
305end_stmt: '}' | ';' | Op_Newline | Eof_Real
306
307# TODO: allow -> to denote aliasing/mutation
308ysh_var_decl: name_type_list ['=' testlist] end_stmt
309
310# Note: this is more precise way of writing ysh_mutation, but it's ambiguous :(
311# ysh_mutation: lhs augassign testlist end_stmt
312# | lhs_list '=' testlist end_stmt
313
314# Note: for YSH (not Tea), we could accept [':'] expr for setvar :out = 'foo'
315lhs_list: expr (',' expr)*
316
317# TODO: allow -> to denote aliasing/mutation
318ysh_mutation: lhs_list (augassign | '=') testlist end_stmt
319
320# proc arg lists, like:
321# json write (x, indent=1)
322# cd /tmp ( ; ; ^(echo hi))
323#
324# What about:
325# myproc /tmp [ ; ; ^(echo hi)] - I guess this doesn't make sense?
326ysh_eager_arglist: '(' [arglist3] ')'
327ysh_lazy_arglist: '[' [arglist] ']'
328
329#
330# Other Entry Points
331#
332
333# if (x > 0) etc.
334ysh_expr: '(' testlist ')'
335
336# = 42 + a[i]
337# call f(x)
338command_expr: testlist end_stmt
339
340# $[d->key] etc.
341ysh_expr_sub: testlist ']'
342
343# Signatures for proc and func.
344
345# Note: 'proc name-with-hyphens' is allowed, so we can't parse the name in
346# expression mode.
347ysh_proc: (
348 [ '('
349 [ param_group ] # word params, with defaults
350 [ ';' [ param_group ] ] # positional typed params, with defaults
351 [ ';' [ param_group ] ] # named params, with defaults
352 [ ';' [ param_group ] ] # optional block param, with no type or default
353
354 # This causes a pgen2 error? It doesn't know which branch to take
355 # So we have the extra {block} syntax
356 #[ ';' Expr_Name ] # optional block param, with no type or default
357 ')'
358 ]
359 '{' # opening { for pgen2
360)
361
362ysh_func: (
363 Expr_Name '(' [param_group] [';' param_group] ')' ['=>' type_expr] '{'
364)
365
366param: Expr_Name [type_expr] ['=' expr]
367
368# This is an awkward way of writing that '...' has to come last.
369param_group: (
370 (param ',')*
371 [ (param | '...' Expr_Name) [','] ]
372)
373
374#
375# Regex Sublanguage
376#
377
378char_literal: Char_OneChar | Char_Hex | Char_UBraced
379
380# we allow a-z A-Z 0-9 as ranges, but otherwise they have to be quoted
381# The parser enforces that they are single strings
382range_char: Expr_Name | Expr_DecInt | sq_string | char_literal
383
384# digit or a-z
385# We have to do further validation of ranges later.
386class_literal_term: (
387 # NOTE: range_char has sq_string
388 range_char ['-' range_char ]
389 # splice a literal set of characters
390 | '@' Expr_Name
391 | '!' Expr_Name
392 # Reserved for [[.collating sequences.]] (Unicode)
393 | '.' Expr_Name
394 # Reserved for [[=character equivalents=]] (Unicode)
395 | '=' Expr_Name
396 # TODO: Do these char classes actually work in bash/awk/egrep/sed/etc.?
397
398)
399class_literal: '[' class_literal_term+ ']'
400
401# NOTE: Here is an example of where you can put ^ in the middle of a pattern in
402# Python, and it matters!
403# >>> r = re.compile('.f[a-z]*', re.DOTALL|re.MULTILINE)
404# >>> r.findall('z\nfoo\nbeef\nfood\n')
405# ['\nfoo', 'ef', '\nfood']
406# >>> r = re.compile('.^f[a-z]*', re.DOTALL|re.MULTILINE)
407# r.findall('z\nfoo\nbeef\nfood\n')
408# ['\nfoo', '\nfood']
409
410re_atom: (
411 char_literal
412 # builtin regex like 'digit' or a regex reference like 'D'
413 | Expr_Name
414 # %begin or %end
415 | Expr_Symbol
416 | class_literal
417 # !digit or ![a-f]. Note ! %boundary could be \B in Python, but ERE
418 # doesn't have anything like that
419 | '!' (Expr_Name | class_literal)
420
421 # syntactic space for Perl-style backtracking
422 # !!REF 1 !!REF name
423 # !!AHEAD(d+) !!BEHIND(d+) !!NOT_AHEAD(d+) !!NOT_BEHIND(d+)
424 #
425 # Note: !! conflicts with history
426 | '!' '!' Expr_Name (Expr_Name | Expr_DecInt | '(' regex ')')
427
428 # Splice another expression
429 | '@' Expr_Name
430 # any %start %end are preferred
431 | '.' | '^' | '$'
432 # In a language-independent spec, backslashes are disallowed within 'sq'.
433 # Write it with char literals outside strings: 'foo' \\ 'bar' \n
434 #
435 # No double-quoted strings because you can write "x = $x" with 'x = ' @x
436 | sq_string
437
438 # grouping (non-capturing in Perl; capturing in ERE although < > is preferred)
439 | '(' regex ')'
440
441 # Capturing group, with optional name and conversion function
442 # <capture d+ as date>
443 # <capture d+ as date: int>
444 # <capture d+ : int>
445 | '<' 'capture' regex ['as' Expr_Name] [':' Expr_Name] '>'
446
447 # Might want this obscure conditional construct. Can't use C-style ternary
448 # because '?' is a regex operator.
449 #| '{' regex 'if' regex 'else' regex '}'
450
451 # Others:
452 # PCRE has (?R ) for recursion? That could be !RECURSE()
453 # Note: .NET has && in character classes, making it a recursive language
454)
455
456# e.g. a{3} a{3,4} a{3,} a{,4} but not a{,}
457repeat_range: (
458 Expr_DecInt [',']
459 | ',' Expr_DecInt
460 | Expr_DecInt ',' Expr_DecInt
461)
462
463repeat_op: (
464 '+' | '*' | '?'
465 # In PCRE, ?? *? +? {}? is lazy/nongreedy and ?+ *+ ++ {}+ is "possessive"
466 # We use N and P modifiers within {}.
467 # a{L +} a{P ?} a{P 3,4} a{P ,4}
468 | '{' [Expr_Name] ('+' | '*' | '?' | repeat_range) '}'
469)
470
471re_alt: (re_atom [repeat_op])+
472
473regex: [re_alt] (('|'|'or') re_alt)*
474
475# e.g. /digit+ ; multiline !ignorecase/
476#
477# This can express translation preferences:
478#
479# / d+ ; ; ERE / is '[[:digit:]]+'
480# / d+ ; ; PCRE / is '\d+'
481# / d+ ; ignorecase ; python / is '(?i)\d+'
482
483# Python has the syntax
484# (?i:myre) to set a flag
485# (?-i:myre) to remove a flag
486#
487# They can apply to portions of the expression, which we don't have here.
488re_flag: ['!'] Expr_Name
489eggex: '/' regex [';' re_flag* [';' Expr_Name] ] '/'
490
491# Patterns are the start of a case arm. Ie,
492#
493# case (foo) {
494# (40 + 2) | (0) { echo number }
495# ^^^^^^^^^^^^^^-- This is pattern
496# }
497#
498# Due to limitations created from pgen2/cmd_parser interactions, we also parse
499# the leading '{' token of the case arm body in pgen2. We do this to help pgen2
500# figure out when to transfer control back to the cmd_parser. For more details
501# see #oil-dev > Dev Friction / Smells.
502#
503# case (foo) {
504# (40 + 2) | (0) { echo number }
505# ^-- End of pattern/beginning of case arm body
506# }
507
508ysh_case_pat: (
509 '(' (pat_else | pat_exprs)
510 | eggex
511) [Op_Newline] '{'
512
513pat_else: 'else' ')'
514pat_exprs: expr ')' [Op_Newline] ('|' [Op_Newline] '(' expr ')' [Op_Newline])*
515
516
517# Syntax reserved for PCRE/Python, but that's not in ERE:
518#
519# non-greedy a{N *}
520# non-capturing ( digit+ )
521# backtracking !!REF 1 !!AHEAD(d+)
522#
523# Legacy syntax:
524#
525# ^ and $ instead of %start and %end
526# < and > instead of %start_word and %end_word
527# . instead of dot
528# | instead of 'or'