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

536 lines, 183 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# " $" """ $""" ^"
250dq_string: (
251 Left_DoubleQuote | Left_DollarDoubleQuote |
252 Left_TDoubleQuote | Left_DollarTDoubleQuote |
253 Left_CaretDoubleQuote
254 ) Expr_CastedDummy Right_DoubleQuote
255
256# ' ''' r' r'''
257# $' for "refactoring" property
258# u' u''' b' b'''
259sq_string: (
260 Left_SingleQuote | Left_TSingleQuote
261 | Left_RSingleQuote | Left_RTSingleQuote
262 | Left_DollarSingleQuote
263 | Left_USingleQuote | Left_UTSingleQuote
264 | Left_BSingleQuote | Left_BTSingleQuote
265) Expr_CastedDummy Right_SingleQuote
266
267braced_var_sub: '${' Expr_CastedDummy Right_DollarBrace
268
269simple_var_sub: (
270 # This is everything in Kind.VSub except VSub_Name, which is braced: ${foo}
271 #
272 # Note: we could allow $foo and $0, but disallow the rest in favor of ${@}
273 # and ${-}? Meh it's too inconsistent.
274 VSub_DollarName | VSub_Number
275 | VSub_Bang | VSub_At | VSub_Pound | VSub_Dollar | VSub_Star | VSub_Hyphen
276 | VSub_QMark
277 # NOTE: $? should be STATUS because it's an integer.
278)
279
280#
281# Assignment / Type Variables
282#
283# Several differences vs. Python:
284#
285# - no yield expression on RHS
286# - no star expressions on either side (Python 3) *x, y = 2, *b
287# - no multiple assignments like: var x = y = 3
288# - type annotation syntax is more restrictive # a: (1+2) = 3 is OK in python
289# - We're validating the lvalue here, instead of doing it in the "transformer".
290# We have the 'var' prefix which helps.
291
292# name_type use cases:
293# var x Int, y Int = 3, 5
294# / <capture d+ as date: int> /
295#
296# for x Int, y Int
297# [x for x Int, y Int in ...]
298#
299# func(x Int, y Int) - this is separate
300
301# Optional colon because we want both
302
303# var x: Int = 42 # colon looks nicer
304# proc p (; x Int, y Int; z Int) { echo hi } # colon gets in the way of ;
305
306name_type: Expr_Name [':'] [type_expr]
307name_type_list: name_type (',' name_type)*
308
309type_expr: Expr_Name [ '[' type_expr (',' type_expr)* ']' ]
310
311# NOTE: Eof_RParen and Eof_Backtick aren't allowed because we don't want 'var'
312# in command subs.
313end_stmt: '}' | ';' | Op_Newline | Eof_Real
314
315# TODO: allow -> to denote aliasing/mutation
316ysh_var_decl: name_type_list ['=' testlist] end_stmt
317
318# Note: this is more precise way of writing ysh_mutation, but it's ambiguous :(
319# ysh_mutation: lhs augassign testlist end_stmt
320# | lhs_list '=' testlist end_stmt
321
322# Note: for YSH (not Tea), we could accept [':'] expr for setvar :out = 'foo'
323lhs_list: expr (',' expr)*
324
325# TODO: allow -> to denote aliasing/mutation
326ysh_mutation: lhs_list (augassign | '=') testlist end_stmt
327
328# proc arg lists, like:
329# json write (x, indent=1)
330# cd /tmp ( ; ; ^(echo hi))
331#
332# What about:
333# myproc /tmp [ ; ; ^(echo hi)] - I guess this doesn't make sense?
334ysh_eager_arglist: '(' [arglist3] ')'
335ysh_lazy_arglist: '[' [arglist] ']'
336
337#
338# Other Entry Points
339#
340
341# if (x > 0) etc.
342ysh_expr: '(' testlist ')'
343
344# = 42 + a[i]
345# call f(x)
346command_expr: testlist end_stmt
347
348# $[d->key] etc.
349ysh_expr_sub: testlist ']'
350
351# Signatures for proc and func.
352
353# Note: 'proc name-with-hyphens' is allowed, so we can't parse the name in
354# expression mode.
355ysh_proc: (
356 [ '('
357 [ param_group ] # word params, with defaults
358 [ ';' [ param_group ] ] # positional typed params, with defaults
359 [ ';' [ param_group ] ] # named params, with defaults
360 [ ';' [ param_group ] ] # optional block param, with no type or default
361
362 # This causes a pgen2 error? It doesn't know which branch to take
363 # So we have the extra {block} syntax
364 #[ ';' Expr_Name ] # optional block param, with no type or default
365 ')'
366 ]
367 '{' # opening { for pgen2
368)
369
370ysh_func: (
371 Expr_Name '(' [param_group] [';' param_group] ')' ['=>' type_expr] '{'
372)
373
374param: Expr_Name [type_expr] ['=' expr]
375
376# This is an awkward way of writing that '...' has to come last.
377param_group: (
378 (param ',')*
379 [ (param | '...' Expr_Name) [','] ]
380)
381
382#
383# Regex Sublanguage
384#
385
386char_literal: Char_OneChar | Char_Hex | Char_UBraced
387
388# we allow a-z A-Z 0-9 as ranges, but otherwise they have to be quoted
389# The parser enforces that they are single strings
390range_char: Expr_Name | Expr_DecInt | sq_string | char_literal
391
392# digit or a-z
393# We have to do further validation of ranges later.
394class_literal_term: (
395 # NOTE: range_char has sq_string
396 range_char ['-' range_char ]
397 # splice a literal set of characters
398 | '@' Expr_Name
399 | '!' Expr_Name
400 # Reserved for [[.collating sequences.]] (Unicode)
401 | '.' Expr_Name
402 # Reserved for [[=character equivalents=]] (Unicode)
403 | '=' Expr_Name
404 # TODO: Do these char classes actually work in bash/awk/egrep/sed/etc.?
405
406)
407class_literal: '[' class_literal_term+ ']'
408
409# NOTE: Here is an example of where you can put ^ in the middle of a pattern in
410# Python, and it matters!
411# >>> r = re.compile('.f[a-z]*', re.DOTALL|re.MULTILINE)
412# >>> r.findall('z\nfoo\nbeef\nfood\n')
413# ['\nfoo', 'ef', '\nfood']
414# >>> r = re.compile('.^f[a-z]*', re.DOTALL|re.MULTILINE)
415# r.findall('z\nfoo\nbeef\nfood\n')
416# ['\nfoo', '\nfood']
417
418re_atom: (
419 char_literal
420 # builtin regex like 'digit' or a regex reference like 'D'
421 | Expr_Name
422 # %begin or %end
423 | Expr_Symbol
424 | class_literal
425 # !digit or ![a-f]. Note ! %boundary could be \B in Python, but ERE
426 # doesn't have anything like that
427 | '!' (Expr_Name | class_literal)
428
429 # syntactic space for Perl-style backtracking
430 # !!REF 1 !!REF name
431 # !!AHEAD(d+) !!BEHIND(d+) !!NOT_AHEAD(d+) !!NOT_BEHIND(d+)
432 #
433 # Note: !! conflicts with history
434 | '!' '!' Expr_Name (Expr_Name | Expr_DecInt | '(' regex ')')
435
436 # Splice another expression
437 | '@' Expr_Name
438 # any %start %end are preferred
439 | '.' | '^' | '$'
440 # In a language-independent spec, backslashes are disallowed within 'sq'.
441 # Write it with char literals outside strings: 'foo' \\ 'bar' \n
442 #
443 # No double-quoted strings because you can write "x = $x" with 'x = ' @x
444 | sq_string
445
446 # grouping (non-capturing in Perl; capturing in ERE although < > is preferred)
447 | '(' regex ')'
448
449 # Capturing group, with optional name and conversion function
450 # <capture d+ as date>
451 # <capture d+ as date: int>
452 # <capture d+ : int>
453 | '<' 'capture' regex ['as' Expr_Name] [':' Expr_Name] '>'
454
455 # Might want this obscure conditional construct. Can't use C-style ternary
456 # because '?' is a regex operator.
457 #| '{' regex 'if' regex 'else' regex '}'
458
459 # Others:
460 # PCRE has (?R ) for recursion? That could be !RECURSE()
461 # Note: .NET has && in character classes, making it a recursive language
462)
463
464# e.g. a{3} a{3,4} a{3,} a{,4} but not a{,}
465repeat_range: (
466 Expr_DecInt [',']
467 | ',' Expr_DecInt
468 | Expr_DecInt ',' Expr_DecInt
469)
470
471repeat_op: (
472 '+' | '*' | '?'
473 # In PCRE, ?? *? +? {}? is lazy/nongreedy and ?+ *+ ++ {}+ is "possessive"
474 # We use N and P modifiers within {}.
475 # a{L +} a{P ?} a{P 3,4} a{P ,4}
476 | '{' [Expr_Name] ('+' | '*' | '?' | repeat_range) '}'
477)
478
479re_alt: (re_atom [repeat_op])+
480
481regex: [re_alt] (('|'|'or') re_alt)*
482
483# e.g. /digit+ ; multiline !ignorecase/
484#
485# This can express translation preferences:
486#
487# / d+ ; ; ERE / is '[[:digit:]]+'
488# / d+ ; ; PCRE / is '\d+'
489# / d+ ; ignorecase ; python / is '(?i)\d+'
490
491# Python has the syntax
492# (?i:myre) to set a flag
493# (?-i:myre) to remove a flag
494#
495# They can apply to portions of the expression, which we don't have here.
496re_flag: ['!'] Expr_Name
497eggex: '/' regex [';' re_flag* [';' Expr_Name] ] '/'
498
499# Patterns are the start of a case arm. Ie,
500#
501# case (foo) {
502# (40 + 2) | (0) { echo number }
503# ^^^^^^^^^^^^^^-- This is pattern
504# }
505#
506# Due to limitations created from pgen2/cmd_parser interactions, we also parse
507# the leading '{' token of the case arm body in pgen2. We do this to help pgen2
508# figure out when to transfer control back to the cmd_parser. For more details
509# see #oil-dev > Dev Friction / Smells.
510#
511# case (foo) {
512# (40 + 2) | (0) { echo number }
513# ^-- End of pattern/beginning of case arm body
514# }
515
516ysh_case_pat: (
517 '(' (pat_else | pat_exprs)
518 | eggex
519) [Op_Newline] '{'
520
521pat_else: 'else' ')'
522pat_exprs: expr ')' [Op_Newline] ('|' [Op_Newline] '(' expr ')' [Op_Newline])*
523
524
525# Syntax reserved for PCRE/Python, but that's not in ERE:
526#
527# non-greedy a{N *}
528# non-capturing ( digit+ )
529# backtracking !!REF 1 !!AHEAD(d+)
530#
531# Legacy syntax:
532#
533# ^ and $ instead of %start and %end
534# < and > instead of %start_word and %end_word
535# . instead of dot
536# | instead of 'or'