-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathParser.y
706 lines (587 loc) · 21 KB
/
Parser.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
{
module Language.Python.Parser (parse, parseRepl) where
import Control.Monad.Error
import Data.Either
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Language.Python
import qualified Language.Python.Lexer as L
}
%tokentype {L.Token}
%error { parseError }
%monad { Either String } { (>>=) } { return }
%name parseTokens file_input
%name parseLine single_input
%token
identifier {L.Identifier $$}
literal {L.Literal $$}
string {L.StringLiteral $$}
NEWLINE {L.Newline}
'+' {L.Operator "+"}
'-' {L.Operator "-"}
'*' {L.Operator "*"}
'/' {L.Operator "/"}
'|' {L.Operator "|"}
'==' {L.Operator "=="}
'!=' {L.Operator "!="}
'<' {L.Operator "<"}
'<=' {L.Operator "<="}
'>' {L.Operator ">"}
'>=' {L.Operator ">="}
'+=' {L.Delimiter "+="}
'-=' {L.Delimiter "-="}
'*=' {L.Delimiter "*="}
'/=' {L.Delimiter "/="}
'%=' {L.Delimiter "%="}
'&=' {L.Delimiter "&="}
'|=' {L.Delimiter "|="}
'^=' {L.Delimiter "^="}
'<<=' {L.Delimiter "<<="}
'>>=' {L.Delimiter ">>="}
'**=' {L.Delimiter "**="}
'//=' {L.Delimiter "//="}
'@' {L.Delimiter "@"}
'%' {L.Operator "%"}
'**' {L.Operator "**"}
'//' {L.Operator "//"}
'~' {L.Operator "~"}
'^' {L.Operator "^"}
'&' {L.Operator "&"}
'<<' {L.Operator "<<"}
'>>' {L.Operator ">>"}
'.' {L.Delimiter "."}
'[' {L.Delimiter "["}
']' {L.Delimiter "]"}
'(' {L.Delimiter "("}
')' {L.Delimiter ")"}
'{' {L.Delimiter "{"}
'}' {L.Delimiter "}"}
':' {L.Delimiter ":"}
'=' {L.Delimiter "="}
';' {L.Delimiter ";"}
',' {L.Delimiter ","}
INDENT {L.Indent}
DEDENT {L.Dedent}
AND {L.Keyword "and"}
ASSERT {L.Keyword "assert"}
AS {L.Keyword "as"}
BREAK {L.Keyword "break"}
CLASS {L.Keyword "class"}
CONTINUE {L.Keyword "continue"}
DEF {L.Keyword "def"}
DEL {L.Keyword "del"}
ELIF {L.Keyword "elif"}
ELSE {L.Keyword "else"}
EXCEPT {L.Keyword "except"}
FALSE {L.Keyword "False"}
FINALLY {L.Keyword "finally"}
FOR {L.Keyword "for"}
FROM {L.Keyword "from"}
GLOBAL {L.Keyword "global"}
IF {L.Keyword "if"}
IMPORT {L.Keyword "import"}
IN {L.Keyword "in"}
IS {L.Keyword "is"}
LAMBDA {L.Keyword "lambda"}
NONE {L.Keyword "None"}
NONLOCAL {L.Keyword "nonlocal"}
NOT {L.Keyword "not"}
OR {L.Keyword "or"}
PASS {L.Keyword "pass"}
RAISE {L.Keyword "raise"}
RETURN {L.Keyword "return"}
TRUE {L.Keyword "True"}
TRY {L.Keyword "try"}
WHILE {L.Keyword "while"}
WITH {L.Keyword "with"}
YIELD {L.Keyword "yield"}
%left LAMBDA
%left IF ELSE
%left OR
%left AND
%left IN IS '<' '<=' '>' '>=' '!=' '=='
%left '|'
%left '^'
%left '&'
%left '<<' '>>'
%left '+' '-'
%left '*' '/' '//' '%'
%left POS NEG COMP
%left SPLAT
%right '**'
%%
or(p,q)
: p { $1 }
| q { $1 }
either(p,q)
: p { Left $1 }
| q { Right $1 }
opt(p)
: { Nothing }
| p { Just $1 }
rev_list1(p)
: p { [$1] }
| rev_list1(p) p { $2 : $1 }
many1(p)
: rev_list1(p) { reverse $1 }
many0(p)
: many1(p) { $1 }
| { [] }
sepOptEndBy(p,sep)
: sepByRev(p,sep) sep { reverse $1 }
| sepByRev(p,sep) { reverse $1 }
sepBy(p,sep): sepByRev(p,sep) { reverse $1 }
sepBy0(p,sep)
: { [] }
| sepBy(p,sep) { $1 }
sepByRev(p,sep)
: p { [$1] }
| sepByRev(p,sep) sep p { $3 : $1 }
exprOrTuple(p)
: p { $1 }
| p ',' { TupleDef [$1] }
| exprOrTupleTuple(p) opt(',') { TupleDef $1 }
exprOrTupleTuple(p)
: p ',' p { [$1, $3] }
| exprOrTupleTuple(p) ',' p { $1 ++ [$3] }
-- single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
single_input
: NEWLINE { [Pass] }
| simple_stmt { $1 }
| compound_stmt NEWLINE { [$1] }
-- file_input: (NEWLINE | stmt)* ENDMARKER
file_input
: many0(either(NEWLINE, stmt)) { foldl' (++) [] (rights $1) }
-- eval_input: testlist NEWLINE* ENDMARKER
--
-- decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorator
: '@' dotted_name NEWLINE { Decorator $2 [] }
| '@' dotted_name '(' arglist ')' NEWLINE { Decorator $2 $4 }
-- decorators: decorator+
decorators
: many1(decorator) { $1 }
-- decorated: decorators (classdef | funcdef)
decorated
: decorators or(classdef, funcdef) { $2 }
-- funcdef: 'def' NAME parameters ['->' test] ':' suite
funcdef
: DEF identifier parameters ':' suite { FuncDef (T.pack $2) $3 $5 }
-- parameters: '(' [typedargslist] ')'
parameters
: '(' sepBy0(parameter, ',') ')' { $2 }
parameter
: identifier { FormalParam (T.pack $1) }
| identifier '=' test { DefaultParam (T.pack $1) $3 }
| '*' identifier { SplatParam (T.pack $2) }
| '**' identifier { DoubleSplatParam (T.pack $2) }
-- typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
-- ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]
-- | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
-- tfpdef: NAME [':' test]
-- varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','
-- ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]
-- | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
varargslist
: sepBy0(parameter, ',') { $1 }
-- vfpdef: NAME
vfpdef
: identifier { $1 }
-- stmt: simple_stmt | compound_stmt
stmt
: simple_stmt { $1 }
| compound_stmt { [$1] }
-- simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
simple_stmt
: small_stmts opt(';') NEWLINE { $1 }
small_stmts
: small_stmt { [$1] }
| small_stmts ';' small_stmt { $1 ++ [$3] }
-- small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
-- import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
small_stmt
: expr_stmt { $1 }
| del_stmt { $1 }
| pass_stmt { $1 }
| flow_stmt { $1 }
| import_stmt { $1 }
| global_stmt { $1 }
| nonlocal_stmt { $1 }
| assert_stmt { $1 }
-- expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) |
-- ('=' (yield_expr|testlist_star_expr))*)
expr_stmt
: testlist_star_expr { Expression $1 }
| testlist_star_expr augassign or(yield_expr, testlist) { handleAugAssignment $1 $2 $3 }
| testlist_star_expr '=' or(yield_expr, testlist_star_expr) { Assignment $1 $3 }
-- testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
testlist_star_expr
: exprOrTuple(or(test, star_expr)) { $1 }
-- augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
-- '<<=' | '>>=' | '**=' | '//=')
-- # For normal assignments, additional restrictions enforced by the interpreter
augassign
: '+=' { ArithOp Add }
| '-=' { ArithOp Sub }
| '*=' { ArithOp Mul }
| '/=' { ArithOp Div }
| '%=' { ArithOp Mod }
| '&=' { BitOp BitAnd }
| '|=' { BitOp BitOr }
| '^=' { BitOp BitXor }
| '<<=' { BitOp LShift }
| '>>=' { BitOp RShift }
| '**=' { ArithOp Pow }
| '//=' { ArithOp FDiv }
-- del_stmt: 'del' exprlist
del_stmt
: DEL exprlist { Del $2 }
-- pass_stmt: 'pass'
pass_stmt
: PASS { Pass }
-- flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
flow_stmt
: break_stmt { $1 }
| continue_stmt { $1 }
| return_stmt { $1 }
| raise_stmt { $1 }
| yield_stmt { $1 }
-- break_stmt: 'break'
break_stmt
: BREAK { Break }
-- continue_stmt: 'continue'
continue_stmt
: CONTINUE { Continue }
-- return_stmt: 'return' [testlist]
return_stmt
: RETURN opt(testlist) { Return $ maybe (Constant ConstantNone) id $2 }
-- yield_stmt: yield_expr
yield_stmt
: yield_expr { Expression $1 }
-- raise_stmt: 'raise' [test ['from' test]]
raise_stmt
: RAISE { Reraise }
| RAISE test { Raise $2 (Constant ConstantNone) }
| RAISE test FROM test { Raise $2 $4 }
-- import_stmt: import_name | import_from
import_stmt
: import_name { $1 }
| import_from { $1 }
-- import_name: 'import' dotted_as_names
import_name
: IMPORT dotted_as_names { Import $2 }
-- # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
-- import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
-- 'import' ('*' | '(' import_as_names ')' | import_as_names))
import_from
: FROM from_import IMPORT from_import_items { ImportFrom $2 $4 }
from_import
: many0('.') dotted_name { RelativeImport (length $1) $2 }
| many1('.') { RelativeImport (length $1) Glob }
from_import_items
: '*' { [Glob] }
| '(' import_as_names ')' { $2 }
| import_as_names { $1 }
-- import_as_name: NAME ['as' NAME]
import_as_name
: identifier { mkName $1 }
| identifier AS identifier { As (mkName $1) (mkName $3) }
-- dotted_as_name: dotted_name ['as' NAME]
dotted_as_name
: dotted_name { $1 }
| dotted_name AS identifier { As $1 (mkName $3) }
-- import_as_names: import_as_name (',' import_as_name)* [',']
import_as_names
: sepOptEndBy(import_as_name, ',') { $1 }
-- dotted_as_names: dotted_as_name (',' dotted_as_name)*
dotted_as_names
: sepBy(dotted_as_name, ',') { $1 }
-- dotted_name: NAME ('.' NAME)*
dotted_name
: sepBy(identifier, '.') { mkName $ (intercalate "." $1) }
-- global_stmt: 'global' NAME (',' NAME)*
global_stmt
: GLOBAL sepBy(identifier, ',') { Global $ map T.pack $2 }
-- nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
nonlocal_stmt
: NONLOCAL sepBy(identifier, ',') { Nonlocal $ map T.pack $2 }
-- assert_stmt: 'assert' test [',' test]
assert_stmt
: ASSERT test { Assert $2 (Constant ConstantNone) }
| ASSERT test ',' test { Assert $2 $4 }
-- compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
compound_stmt
: if_stmt { $1 }
| while_stmt { $1 }
| for_stmt { $1 }
| try_stmt { $1 }
| with_stmt { $1 }
| funcdef { $1 }
| classdef { $1 }
| decorated { $1 }
-- if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
if_stmt
: IF test ':' suite many0(elif_clause) else_clause { If ((IfClause $2 $4):$5) $6 }
elif_clause
: ELIF test ':' suite { IfClause $2 $4 }
else_clause
: { [] }
| ELSE ':' suite { $3 }
-- while_stmt: 'while' test ':' suite ['else' ':' suite]
while_stmt
: WHILE test ':' suite { While $2 $4 [] }
| WHILE test ':' suite ELSE ':' suite { While $2 $4 $7 }
-- for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
for_stmt
: FOR exprlist IN testlist ':' suite { For $2 $4 $6 [] }
| FOR exprlist IN testlist ':' suite ELSE ':' suite { For $2 $4 $6 $9 }
-- try_stmt: ('try' ':' suite
-- ((except_clause ':' suite)+
-- ['else' ':' suite]
-- ['finally' ':' suite] |
-- 'finally' ':' suite))
try_stmt
: TRY ':' suite many1(except_clauses) else_clause finally_clause { Try $4 $3 $5 $6 }
| TRY ':' suite FINALLY ':' suite { Try [] $3 [] $6 }
except_clauses
: except_clause ':' suite { $1 $3 }
finally_clause
: { [] }
| FINALLY ':' suite { $3 }
-- with_stmt: 'with' with_item (',' with_item)* ':' suite
with_stmt
: WITH sepBy(with_item, ',') ':' suite { expandWith $2 $4 }
-- with_item: test ['as' expr]
with_item
: test { WithExpression $1 T.empty }
| test AS identifier { WithExpression $1 (T.pack $3) }
-- # NB compile.c makes sure that the default except clause is last
-- except_clause: 'except' [test ['as' NAME]]
except_clause
: EXCEPT { ExceptClause (mkName "BaseException") T.empty }
| EXCEPT test { ExceptClause $2 T.empty }
| EXCEPT test AS identifier { ExceptClause $2 (T.pack $4) }
-- suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
suite
: simple_stmt { $1 }
| NEWLINE INDENT many1(stmt) DEDENT { concat $3 }
-- test: or_test ['if' or_test 'else' test] | lambdef
test
: or_test { $1 }
| or_test IF or_test ELSE test { TernOp $3 $1 $5 }
| lambdef { $1 }
-- test_nocond: or_test | lambdef_nocond
test_nocond
: or_test { $1 }
| lambdef_nocond { $1 }
-- lambdef: 'lambda' [varargslist] ':' test
lambdef
: LAMBDA varargslist ':' test { LambdaExpr $2 $4 }
-- lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
lambdef_nocond
: LAMBDA varargslist ':' test_nocond { LambdaExpr $2 $4 }
-- or_test: and_test ('or' and_test)*
-- TODO: implement 0-n clauses
or_test
: and_test { $1 }
| or_test OR and_test { BinOp (BoolOp Or) $1 $3 }
-- and_test: not_test ('and' not_test)*
-- TODO: implement 0-n clauses
and_test
: not_test { $1 }
| and_test AND not_test { BinOp (BoolOp And) $1 $3 }
-- not_test: 'not' not_test | comparison
-- TODO: implement 0-n clauses
not_test
: NOT not_test { UnaryOp Not $2 }
| comparison { $1 }
-- comparison: expr (comp_op expr)*
-- TODO: implement 0-n clauses
comparison
: expr { $1 }
| expr comp_op expr { BinOp (CompOp $2) $1 $3 }
-- comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
comp_op
: '<' { LessThan }
| '>' { GreaterThan }
| '==' { Eq }
| '>=' { GreaterThanEq }
| '<=' { LessThanEq }
| '!=' { NotEq }
| IN { In }
| NOT IN { NotIn }
| IS { Is }
| IS NOT { IsNot }
-- star_expr: '*' expr
-- TODO: implement
star_expr
: '*' expr { undefined }
-- expr: xor_expr ('|' xor_expr)*
-- TODO: implement 0-n handling
expr
: xor_expr { $1 }
| xor_expr '|' xor_expr { BinOp (BitOp BitOr) $1 $3 }
-- xor_expr: and_expr ('^' and_expr)*
-- TODO: implement 0-n handling
xor_expr
: and_expr { $1 }
| and_expr '^' and_expr { BinOp (BitOp BitXor) $1 $3 }
-- and_expr: shift_expr ('&' shift_expr)*
-- TODO: implement 0-n handling
and_expr
: shift_expr { $1 }
| shift_expr '&' shift_expr { BinOp (BitOp BitAnd) $1 $3 }
-- shift_expr: arith_expr (('<<'|'>>') arith_expr)*
-- TODO: implement 0-n handling
shift_expr
: arith_expr { $1 }
| arith_expr '<<' arith_expr { BinOp (BitOp LShift) $1 $3 }
| arith_expr '>>' arith_expr { BinOp (BitOp RShift) $1 $3 }
-- arith_expr: term (('+'|'-') term)*
arith_expr
: term { $1 }
| arith_expr '+' term { BinOp (ArithOp Add) $1 $3 }
| arith_expr '-' term { BinOp (ArithOp Sub) $1 $3 }
-- term: factor (('*'|'/'|'%'|'//') factor)*
term
: factor { $1 }
| term '*' factor { BinOp (ArithOp Mul) $1 $3 }
| term '/' factor { BinOp (ArithOp Div) $1 $3 }
| term '%' factor { BinOp (ArithOp Mod) $1 $3 }
| term '//' factor { BinOp (ArithOp FDiv) $1 $3 }
-- factor: ('+'|'-'|'~') factor | power
factor
: '+' factor %prec POS { UnaryOp Pos $2 }
| '-' factor %prec NEG { UnaryOp Neg $2 }
| '~' factor %prec COMP { UnaryOp Complement $2 }
| power { $1 }
-- power: atom trailer* ['**' factor]
power
: atom many0(trailer) { handleTrailers $1 $2 }
| atom many0(trailer) '**' factor { BinOp (ArithOp Pow) (handleTrailers $1 $2) $4 }
-- atom: ('(' [yield_expr|testlist_comp] ')' |
-- '[' [testlist_comp] ']' |
-- '{' [dictorsetmaker] '}' |
-- NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
atom
: '(' opt(or(yield_expr, testlist_comp)) ')' { maybe (TupleDef []) id $2 }
| '[' opt(testlist_comp) ']' { maybe (ListDef []) (\e -> ListDef $ expressionsOf e) $2 }
| '{' opt(dictorsetmaker) '}' { maybe (DictDef []) (\e -> e) $2 }
| identifier { mkName $1 }
| literal { Constant $1 }
| many1(string) { Constant $ ConstantString (foldl' T.append T.empty $1) }
| NONE { Constant ConstantNone }
| TRUE { Constant $ ConstantBool True }
| FALSE { Constant $ ConstantBool False }
-- testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
testlist_comp
: exprOrTuple(or(test, star_expr)) { $1 }
| comp_for { undefined }
-- trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
trailer
: '(' arglist ')' { TrailerCall $2 }
| '[' subscriptlist ']' { TrailerSub $2 }
| '.' identifier { TrailerAttr $2 }
-- subscriptlist: subscript (',' subscript)* [',']
subscriptlist
: exprOrTuple(subscript) { $1 }
-- subscript: test | [test] ':' [test] [sliceop]
subscript
: test { $1 }
| opt(test) ':' opt(test) opt(sliceop) { handleSlice $1 $3 $4 }
-- sliceop: ':' [test]
sliceop
: ':' opt(test) { maybe (Constant ConstantNone) id $2 }
-- exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
exprlist
: exprOrTuple(or(expr, star_expr)) { $1 }
-- testlist: test (',' test)* [',']
testlist
: exprOrTuple(test) { $1 }
-- dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
-- (test (comp_for | (',' test)* [','])) )
dictorsetmaker
: sepOptEndBy(set_item, ',') { SetDef $1 }
| sepOptEndBy(dict_item, ',') { DictDef $1 }
set_item
: test opt(comp_for) { $1 }
dict_item
: test ':' test opt(comp_for) { ($1, $3)}
-- classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
classdef
: CLASS identifier base_classes ':' suite { ClassDef (T.pack $2) $3 $5 }
base_classes
: { [] }
| '(' sepBy0(identifier, ',') ')' { map T.pack $2 }
-- arglist: (argument ',')* (argument [',']
-- |'*' test (',' argument)* [',' '**' test]
-- |'**' test)
arglist
: sepBy0(argitem, ',') { $1 }
argitem
: argument { $1 }
| '*' test { StarArg $2 }
| '**' test { DoubleStarArg $2 }
-- # The reason that keywords are test nodes instead of NAME is that using NAME
-- # results in an ambiguity. ast.c makes sure it's a NAME.
-- argument: test [comp_for] | test '=' test # Really [keyword '='] test
argument
: test opt(comp_for) { Arg $1 }
| identifier '=' test { KeywordArg (T.pack $1) $3 }
-- comp_iter: comp_for | comp_if
comp_iter
: or(comp_for, comp_if) { $1 }
-- comp_for: 'for' exprlist 'in' or_test [comp_iter]
comp_for
: FOR exprlist IN or_test opt(comp_iter) { undefined }
-- comp_if: 'if' test_nocond [comp_iter]
comp_if
: IF test_nocond opt(comp_iter) { undefined }
--
-- # not used in grammar, but may appear in "node" passed from Parser to Compiler
-- encoding_decl: NAME
--
-- yield_expr: 'yield' [yield_arg]
yield_expr
: YIELD yield_arg { Yield $2 }
-- yield_arg: 'from' test | testlist
yield_arg
: FROM test { From $2 }
| testlist { $1 }
{
data Trailer
= TrailerCall [Arg]
| TrailerAttr String
| TrailerSub Expression
| TrailerSlice
deriving (Eq, Show)
expandWith [] block = error "with should have at least one condition!"
expandWith [expr] block = With expr block
expandWith (e:es) block = With e [expandWith es block]
expressionsOf (TupleDef exprs) = exprs
expressionsOf expr = [expr]
handleAugAssignment target op expr = Assignment target (BinOp op target expr)
handleSlice start stop stride = SliceDef (unwrap start) (unwrap stop) (unwrap stride)
where
unwrap arg = maybe (Constant ConstantNone) id arg
handleTrailers expr trailers = foldl' handleTrailer expr trailers
where
handleTrailer expr (TrailerCall args) = Call expr args
handleTrailer expr (TrailerAttr name) = Attribute expr (T.pack name)
handleTrailer expr (TrailerSub sub) = Subscript expr sub
mkName :: String -> Expression
mkName s = Name . T.pack $ s
parse :: Text -> Either String [Statement]
parse code = do
case L.lex code of
Right tokens -> parseTokens tokens
Left err -> Left $ "SyntaxError: " ++ show err
parseRepl :: Text -> Either String [Statement]
parseRepl code = do
case L.lex code of
Right tokens -> parseLine tokens
Left err -> Left $ show err
parseError t = Left $ "SyntaxError: at " ++ show t
}