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

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