-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.py
More file actions
911 lines (762 loc) · 37.7 KB
/
Copy pathparser.py
File metadata and controls
911 lines (762 loc) · 37.7 KB
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
from typing import List, Optional
from lexer import Token, TokenType, Lexer
from ast_nodes import *
class Parser:
def __init__(self, tokens: List[Token]):
self.tokens = tokens
self.pos = 0
self.paren_depth = 0 # Track parenthesis nesting
def current_token(self) -> Token:
if self.pos < len(self.tokens):
return self.tokens[self.pos]
return self.tokens[-1] # Return EOF
def peek_token(self, offset=1) -> Token:
pos = self.pos + offset
if pos < len(self.tokens):
return self.tokens[pos]
return self.tokens[-1]
def advance(self) -> Token:
token = self.current_token()
self.pos += 1
return token
def expect(self, token_type: TokenType) -> Token:
token = self.current_token()
if token.type != token_type:
raise SyntaxError(f"Expected {token_type}, got {token.type} at line {token.line}")
return self.advance()
def skip_newlines(self):
while self.current_token().type == TokenType.NEWLINE:
self.advance()
def parse(self) -> Program:
declarations = []
blocks = []
main = None
while self.current_token().type != TokenType.EOF:
self.skip_newlines()
if self.current_token().type == TokenType.EOF:
break
# Check for main block
if self.current_token().type == TokenType.MAIN:
if main is not None:
raise SyntaxError("Multiple main blocks defined")
main = self.parse_main_block()
# Check for block definitions
elif self.current_token().type in [TokenType.OS, TokenType.DE, TokenType.FO, TokenType.PARALLEL]:
blocks.append(self.parse_block())
# Check for function declarations
elif self.current_token().type == TokenType.DEF:
declarations.append(self.parse_function())
# Check for class declarations
elif self.current_token().type == TokenType.CLASS:
declarations.append(self.parse_class())
# Check for import statements
elif self.current_token().type == TokenType.IMPORT:
declarations.append(self.parse_import())
elif self.current_token().type == TokenType.FROM:
declarations.append(self.parse_from_import())
# Variable declarations or assignments
elif self.current_token().type == TokenType.IDENTIFIER:
# Check for tuple unpacking at global level
if self.peek_token().type == TokenType.COMMA:
# Parse tuple unpacking: a, b, c = expr
# We need to handle this specially at the declaration level
# For now, let's create it as a special VarDeclaration with tuple unpacking
stmt = self.parse_statement() # This will parse it as TupleUnpackingAssignment
# Convert it to declarations - we'll handle it in the interpreter
declarations.append(stmt)
elif self.peek_token().type == TokenType.ASSIGN:
declarations.append(self.parse_var_declaration())
else:
raise SyntaxError(f"Unexpected identifier at line {self.current_token().line}")
else:
raise SyntaxError(f"Unexpected token {self.current_token().type} at line {self.current_token().line}")
self.skip_newlines()
if main is None:
raise SyntaxError("No main block defined")
return Program(declarations, blocks, main)
def parse_main_block(self) -> MainBlock:
self.expect(TokenType.MAIN)
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
body = self.parse_statements()
self.expect(TokenType.DEDENT)
return MainBlock("main", body)
def parse_block(self) -> Block:
parallel = False
if self.current_token().type == TokenType.PARALLEL:
parallel = True
self.advance()
block_type = self.current_token().type
self.advance()
name_token = self.expect(TokenType.IDENTIFIER)
name = name_token.value
# Handle parentheses for all block types (optional for OS/FO, required for DE)
iterations = None
if self.current_token().type == TokenType.LPAREN:
self.advance()
if block_type == TokenType.DE:
# Check if it's a number or identifier
if self.current_token().type == TokenType.NUMBER:
iterations = int(self.current_token().value)
self.advance()
elif self.current_token().type == TokenType.IDENTIFIER:
# Store variable name as string
iterations = self.current_token().value
self.advance()
else:
raise SyntaxError(f"DE block requires iteration count or variable, got {self.current_token().type}")
self.expect(TokenType.RPAREN)
elif block_type == TokenType.DE:
raise SyntaxError(f"DE block '{name}' requires iteration count in parentheses")
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
body = self.parse_statements()
self.expect(TokenType.DEDENT)
if block_type == TokenType.OS:
return OSBlock(name, body)
elif block_type == TokenType.DE:
if parallel:
return ParallelDEBlock(name, body, iterations)
return DEBlock(name, body, iterations)
elif block_type == TokenType.FO:
if parallel:
return ParallelFOBlock(name, body)
return FOBlock(name, body)
def parse_function(self) -> FuncDeclaration:
self.expect(TokenType.DEF)
name = self.expect(TokenType.IDENTIFIER).value
self.expect(TokenType.LPAREN)
params = []
while self.current_token().type != TokenType.RPAREN:
param_name = self.expect(TokenType.IDENTIFIER).value
default_value = None
# Check for default parameter
if self.current_token().type == TokenType.ASSIGN:
self.advance()
default_value = self.parse_expression()
params.append(Parameter(param_name, default_value))
if self.current_token().type == TokenType.COMMA:
self.advance()
self.expect(TokenType.RPAREN)
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
body = self.parse_statements()
self.expect(TokenType.DEDENT)
return FuncDeclaration(name, params, body)
def parse_class(self) -> ClassDeclaration:
self.expect(TokenType.CLASS)
class_name = self.expect(TokenType.IDENTIFIER).value
# Check for base class
base_class = None
if self.current_token().type == TokenType.LPAREN:
self.advance()
if self.current_token().type == TokenType.IDENTIFIER:
base_class = self.advance().value
self.expect(TokenType.RPAREN)
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
methods = []
attributes = []
while self.current_token().type != TokenType.DEDENT:
self.skip_newlines()
if self.current_token().type == TokenType.DEF:
# Parse method
methods.append(self.parse_function())
elif self.current_token().type == TokenType.IDENTIFIER:
# Parse attribute
if self.peek_token().type == TokenType.ASSIGN:
name = self.advance().value
self.expect(TokenType.ASSIGN)
value = self.parse_expression()
attributes.append(VarDeclaration(name, value))
self.skip_newlines()
else:
raise SyntaxError(f"Unexpected identifier in class body at line {self.current_token().line}")
elif self.current_token().type == TokenType.DEDENT:
break
else:
raise SyntaxError(f"Unexpected token in class body: {self.current_token().type} at line {self.current_token().line}")
self.expect(TokenType.DEDENT)
return ClassDeclaration(class_name, base_class, methods, attributes)
def parse_var_declaration(self) -> VarDeclaration:
name = self.expect(TokenType.IDENTIFIER).value
self.expect(TokenType.ASSIGN)
value = self.parse_expression()
self.skip_newlines()
return VarDeclaration(name, value)
def parse_import(self) -> ImportDeclaration:
self.expect(TokenType.IMPORT)
# Parse dotted module name (e.g., urllib.request)
module_parts = [self.expect(TokenType.IDENTIFIER).value]
while self.current_token().type == TokenType.DOT:
self.advance() # consume dot
module_parts.append(self.expect(TokenType.IDENTIFIER).value)
module = '.'.join(module_parts)
alias = None
if self.current_token().type == TokenType.AS:
self.advance()
alias = self.expect(TokenType.IDENTIFIER).value
self.skip_newlines()
return ImportDeclaration(module, alias)
def parse_from_import(self) -> FromImportDeclaration:
self.expect(TokenType.FROM)
# Parse dotted module name (e.g., urllib.parse)
module_parts = [self.expect(TokenType.IDENTIFIER).value]
while self.current_token().type == TokenType.DOT:
self.advance() # consume dot
module_parts.append(self.expect(TokenType.IDENTIFIER).value)
module = '.'.join(module_parts)
self.expect(TokenType.IMPORT)
names = []
aliases = []
# Parse first name
names.append(self.expect(TokenType.IDENTIFIER).value)
if self.current_token().type == TokenType.AS:
self.advance()
aliases.append(self.expect(TokenType.IDENTIFIER).value)
else:
aliases.append(None)
# Parse additional names
while self.current_token().type == TokenType.COMMA:
self.advance()
names.append(self.expect(TokenType.IDENTIFIER).value)
if self.current_token().type == TokenType.AS:
self.advance()
aliases.append(self.expect(TokenType.IDENTIFIER).value)
else:
aliases.append(None)
self.skip_newlines()
return FromImportDeclaration(module, names, aliases)
def parse_statements(self) -> List[Statement]:
statements = []
while self.current_token().type not in [TokenType.DEDENT, TokenType.EOF]:
self.skip_newlines()
if self.current_token().type == TokenType.DEDENT:
break
stmt = self.parse_statement()
if stmt:
statements.append(stmt)
self.skip_newlines()
return statements
def parse_statement(self) -> Optional[Statement]:
token = self.current_token()
if token.type == TokenType.WHEN:
return self.parse_when_statement()
elif token.type == TokenType.WITH:
return self.parse_with_statement()
elif token.type == TokenType.BREAK:
self.advance()
return BreakStatement()
elif token.type == TokenType.CONTINUE:
self.advance()
return ContinueStatement()
elif token.type == TokenType.EXIT:
self.advance()
return ExitStatement()
elif token.type == TokenType.PASS:
self.advance()
return PassStatement()
elif token.type == TokenType.RETURN:
self.advance()
values = []
if self.current_token().type not in [TokenType.NEWLINE, TokenType.EOF]:
values.append(self.parse_expression())
while self.current_token().type == TokenType.COMMA:
self.advance()
values.append(self.parse_expression())
return ReturnStatement(values)
elif token.type == TokenType.GLOBAL:
self.advance()
names = []
names.append(self.expect(TokenType.IDENTIFIER).value)
while self.current_token().type == TokenType.COMMA:
self.advance()
names.append(self.expect(TokenType.IDENTIFIER).value)
return GlobalStatement(names)
elif token.type == TokenType.IDENTIFIER:
# Check for tuple unpacking: a, b = expr
if self.peek_token().type == TokenType.COMMA:
# Parse tuple unpacking targets
targets = []
targets.append(self.advance().value) # Get first identifier
while self.current_token().type == TokenType.COMMA:
self.advance() # Skip comma
targets.append(self.expect(TokenType.IDENTIFIER).value)
self.expect(TokenType.ASSIGN)
# Parse the right-hand side - could be a single expression or multiple comma-separated
values = []
values.append(self.parse_expression())
# Check if there are more comma-separated values on the right
while self.current_token().type == TokenType.COMMA:
self.advance() # Skip comma
# Only continue if not at end of statement
if self.current_token().type not in [TokenType.NEWLINE, TokenType.EOF, TokenType.DEDENT]:
values.append(self.parse_expression())
else:
break
# If multiple values, create a tuple literal, otherwise use single value
if len(values) > 1:
value = TupleLiteral(values)
else:
value = values[0]
return TupleUnpackingAssignment(targets, value)
# Parse the left side as an expression first
# Check for simple assignment shortcut
elif self.peek_token().type == TokenType.ASSIGN:
# Simple assignment: var = value
name = self.advance().value
self.advance() # skip =
value = self.parse_expression()
return Assignment(name, value)
else:
# Parse as expression and check if it's an assignment target
expr = self.parse_expression()
# Check if this expression is followed by an assignment
if self.current_token().type == TokenType.ASSIGN:
self.advance() # skip =
value = self.parse_expression()
# Determine what kind of assignment this is
if isinstance(expr, MemberAccess):
# obj.attr = value
return AttributeAssignment(expr.object, expr.member, value)
elif isinstance(expr, IndexExpression):
# obj[index] = value or obj.attr[index] = value
return IndexAssignment(expr.object, expr.index, value)
else:
# This shouldn't happen with valid syntax
raise SyntaxError(f"Invalid assignment target at line {self.current_token().line}")
else:
# Just an expression statement
return ExpressionStatement(expr)
else:
expr = self.parse_expression()
if expr:
return ExpressionStatement(expr)
return None
def parse_when_statement(self) -> WhenStatement:
self.expect(TokenType.WHEN)
condition = self.parse_expression()
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
body = self.parse_statements()
self.expect(TokenType.DEDENT)
return WhenStatement(condition, body)
def parse_with_statement(self) -> WithStatement:
self.expect(TokenType.WITH)
context_expr = self.parse_expression()
var_name = None
if self.current_token().type == TokenType.AS:
self.advance()
var_name = self.expect(TokenType.IDENTIFIER).value
self.expect(TokenType.COLON)
self.skip_newlines()
self.expect(TokenType.INDENT)
body = self.parse_statements()
self.expect(TokenType.DEDENT)
return WithStatement(context_expr, var_name, body)
def parse_expression(self) -> Expression:
return self.parse_ternary()
def parse_ternary(self) -> Expression:
# Parse the main expression (which could be the true_expr in ternary)
expr = self.parse_comparison()
# Only skip newlines if we're inside parentheses
if self.paren_depth > 0:
self.skip_newlines()
# Check for ternary operator: expr when condition else false_expr
if self.current_token().type == TokenType.WHEN:
self.advance() # consume 'when'
self.skip_newlines() # Allow newlines after 'when'
condition = self.parse_comparison()
self.skip_newlines() # Allow newlines before 'else'
self.expect(TokenType.ELSE)
self.skip_newlines() # Allow newlines after 'else'
false_expr = self.parse_ternary() # Allow nested ternaries
return TernaryOp(expr, condition, false_expr)
return expr
def parse_comparison(self) -> Expression:
left = self.parse_logical_and()
while self.current_token().type in [TokenType.EQ, TokenType.NE, TokenType.LT,
TokenType.GT, TokenType.LE, TokenType.GE, TokenType.IN, TokenType.NOT, TokenType.IS]:
# Handle "not in" compound operator
if self.current_token().type == TokenType.NOT and self.peek_token().type == TokenType.IN:
self.advance() # consume "not"
self.advance() # consume "in"
op = "not in"
right = self.parse_logical_and()
left = BinaryOp(left, op, right)
# Handle "is not" compound operator
elif self.current_token().type == TokenType.IS and self.peek_token().type == TokenType.NOT:
self.advance() # consume "is"
self.advance() # consume "not"
op = "is not"
right = self.parse_logical_and()
left = BinaryOp(left, op, right)
# Handle regular "is"
elif self.current_token().type == TokenType.IS:
self.advance() # consume "is"
op = "is"
right = self.parse_logical_and()
left = BinaryOp(left, op, right)
else:
op_token = self.advance()
op = op_token.value if op_token.value else op_token.type.name.lower()
right = self.parse_logical_and()
left = BinaryOp(left, op, right)
return left
def parse_logical_and(self) -> Expression:
left = self.parse_logical_or()
while self.current_token().type == TokenType.AND:
op = self.advance().value
right = self.parse_logical_or()
left = BinaryOp(left, op, right)
return left
def parse_logical_or(self) -> Expression:
left = self.parse_addition()
while self.current_token().type == TokenType.OR:
op = self.advance().value
right = self.parse_addition()
left = BinaryOp(left, op, right)
return left
def parse_addition(self) -> Expression:
left = self.parse_multiplication()
while self.current_token().type in [TokenType.PLUS, TokenType.MINUS]:
op = self.advance().value
right = self.parse_multiplication()
left = BinaryOp(left, op, right)
return left
def parse_multiplication(self) -> Expression:
left = self.parse_unary()
while self.current_token().type in [TokenType.MULTIPLY, TokenType.DIVIDE, TokenType.MODULO, TokenType.FLOORDIV]:
op = self.advance().value
right = self.parse_unary()
left = BinaryOp(left, op, right)
return left
def parse_unary(self) -> Expression:
if self.current_token().type == TokenType.MINUS:
op = self.advance().value
operand = self.parse_unary()
return UnaryOp(op, operand)
elif self.current_token().type == TokenType.NOT:
# Check for "not in" compound operator
if self.peek_token().type == TokenType.IN:
# This is "not in" - let the comparison parser handle it
return self.parse_postfix()
else:
# Regular "not" unary operator
op = self.advance().value
operand = self.parse_unary()
return UnaryOp(op, operand)
return self.parse_postfix()
def parse_postfix(self) -> Expression:
expr = self.parse_primary()
while True:
if self.current_token().type == TokenType.LBRACKET:
self.advance()
# Check for slice syntax
start = None
stop = None
step = None
is_slice = False
# Parse start (or could be a regular index)
if self.current_token().type != TokenType.COLON:
start = self.parse_expression()
# Check if this is a slice
if self.current_token().type == TokenType.COLON:
is_slice = True
self.advance() # Skip colon
# Parse stop
if self.current_token().type not in [TokenType.COLON, TokenType.RBRACKET]:
stop = self.parse_expression()
# Check for step
if self.current_token().type == TokenType.COLON:
self.advance() # Skip second colon
if self.current_token().type != TokenType.RBRACKET:
step = self.parse_expression()
self.expect(TokenType.RBRACKET)
if is_slice:
expr = SliceExpression(expr, start, stop, step)
else:
# Regular index expression
expr = IndexExpression(expr, start)
elif self.current_token().type == TokenType.DOT:
self.advance()
# Check if next token is a keyword that would normally be an identifier
if self.current_token().type in [TokenType.START, TokenType.STOP, TokenType.SAVE, TokenType.SAVESTOP, TokenType.STARTSAVE, TokenType.DISCARD]:
keyword_token = self.advance()
member = keyword_token.value
else:
member_token = self.expect(TokenType.IDENTIFIER)
member = member_token.value
# Handle special block operations
if member == "start" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StartExpression(expr.name)
elif member == "stop" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StopExpression(expr.name)
elif member == "save" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return SaveExpression(expr.name)
elif member == "savestop" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return SaveStopExpression(expr.name)
elif member == "startsave" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StartSaveExpression(expr.name)
elif member == "discard" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return DiscardExpression(expr.name)
else:
# Check if this is a method call
if self.current_token().type == TokenType.LPAREN:
self.advance()
args = []
kwargs = []
while self.current_token().type != TokenType.RPAREN:
# Check if this is a keyword argument (identifier=value)
if (self.current_token().type == TokenType.IDENTIFIER and
self.peek_token().type == TokenType.ASSIGN):
kw_name = self.advance().value
self.advance() # consume =
kw_value = self.parse_expression()
kwargs.append(KeywordArg(kw_name, kw_value))
else:
# Regular positional argument
args.append(self.parse_expression())
if self.current_token().type == TokenType.COMMA:
self.advance()
self.expect(TokenType.RPAREN)
# Create method call with current expression as object
expr = MethodCall(expr, member, args, kwargs if kwargs else None)
else:
# Regular member access
expr = MemberAccess(expr, member)
else:
break
return expr
def parse_primary(self) -> Expression:
token = self.current_token()
if token.type == TokenType.NUMBER:
self.advance()
return NumberLiteral(token.value)
elif token.type == TokenType.STRING:
self.advance()
return StringLiteral(token.value)
elif token.type == TokenType.FSTRING:
self.advance()
return FStringLiteral(token.value)
elif token.type == TokenType.TRUE:
self.advance()
return BooleanLiteral(True)
elif token.type == TokenType.FALSE:
self.advance()
return BooleanLiteral(False)
elif token.type == TokenType.NONE:
self.advance()
return NoneLiteral()
elif token.type == TokenType.LBRACKET:
return self.parse_list()
elif token.type == TokenType.LBRACE:
return self.parse_dict()
elif token.type == TokenType.LPAREN:
# Check if this is a tuple or just a parenthesized expression
self.advance()
self.paren_depth += 1 # Entering parentheses
self.skip_newlines() # Allow newlines after opening paren
# Empty tuple case
if self.current_token().type == TokenType.RPAREN:
self.advance()
self.paren_depth -= 1 # Exiting parentheses
return TupleLiteral([])
# Parse first element
first_expr = self.parse_expression()
self.skip_newlines() # Allow newlines after expression
# If we see a comma, it's definitely a tuple
if self.current_token().type == TokenType.COMMA:
elements = [first_expr]
self.advance() # consume comma
# Parse remaining elements
while self.current_token().type != TokenType.RPAREN:
elements.append(self.parse_expression())
if self.current_token().type == TokenType.COMMA:
self.advance()
elif self.current_token().type != TokenType.RPAREN:
break
self.expect(TokenType.RPAREN)
self.paren_depth -= 1 # Exiting parentheses
return TupleLiteral(elements)
else:
# Single element in parentheses - check for trailing comma to disambiguate
if self.current_token().type == TokenType.COMMA:
self.advance() # consume trailing comma
self.expect(TokenType.RPAREN)
self.paren_depth -= 1 # Exiting parentheses
return TupleLiteral([first_expr])
else:
# Just a parenthesized expression
self.expect(TokenType.RPAREN)
self.paren_depth -= 1 # Exiting parentheses
return first_expr
elif token.type == TokenType.IDENTIFIER:
name = self.advance().value
# Check for function call
if self.current_token().type == TokenType.LPAREN:
self.advance()
args = []
kwargs = []
while self.current_token().type != TokenType.RPAREN:
# Check if this is a keyword argument (identifier=value)
if (self.current_token().type == TokenType.IDENTIFIER and
self.peek_token().type == TokenType.ASSIGN):
kw_name = self.advance().value
self.advance() # consume =
kw_value = self.parse_expression()
kwargs.append(KeywordArg(kw_name, kw_value))
else:
# Regular positional argument
args.append(self.parse_expression())
if self.current_token().type == TokenType.COMMA:
self.advance()
self.expect(TokenType.RPAREN)
return CallExpression(name, args, kwargs if kwargs else None)
# Check for member access (.start, .stop) or chained member/method access
elif self.current_token().type == TokenType.DOT:
expr = Identifier(name)
# Handle chained dot access
while self.current_token().type == TokenType.DOT:
self.advance()
# Check if next token is a keyword that would normally be an identifier
if self.current_token().type in [TokenType.START, TokenType.STOP, TokenType.SAVE, TokenType.SAVESTOP, TokenType.STARTSAVE, TokenType.DISCARD]:
member = self.advance().value
else:
member = self.expect(TokenType.IDENTIFIER).value
# Special handling for block operations
if member == "start" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StartExpression(expr.name)
elif member == "stop" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StopExpression(expr.name)
elif member == "save" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return SaveExpression(expr.name)
elif member == "savestop" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return SaveStopExpression(expr.name)
elif member == "startsave" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return StartSaveExpression(expr.name)
elif member == "discard" and isinstance(expr, Identifier):
if self.current_token().type == TokenType.LPAREN:
self.advance()
self.expect(TokenType.RPAREN)
return DiscardExpression(expr.name)
else:
# Check if this is a method call
if self.current_token().type == TokenType.LPAREN:
self.advance()
args = []
kwargs = []
while self.current_token().type != TokenType.RPAREN:
# Check if this is a keyword argument (identifier=value)
if (self.current_token().type == TokenType.IDENTIFIER and
self.peek_token().type == TokenType.ASSIGN):
kw_name = self.advance().value
self.advance() # consume =
kw_value = self.parse_expression()
kwargs.append(KeywordArg(kw_name, kw_value))
else:
# Regular positional argument
args.append(self.parse_expression())
if self.current_token().type == TokenType.COMMA:
self.advance()
self.expect(TokenType.RPAREN)
# Create method call with current expression as object
expr = MethodCall(expr, member, args, kwargs if kwargs else None)
else:
# Regular member access
expr = MemberAccess(expr, member)
return expr
else:
return Identifier(name)
raise SyntaxError(f"Unexpected token {token.type} at line {token.line}")
def parse_list(self) -> ListLiteral:
self.expect(TokenType.LBRACKET)
elements = []
# Skip any newlines after opening bracket
self.skip_newlines()
if self.current_token().type != TokenType.RBRACKET:
elements.append(self.parse_expression())
while True:
self.skip_newlines()
if self.current_token().type != TokenType.COMMA:
break
self.advance() # consume comma
self.skip_newlines()
if self.current_token().type == TokenType.RBRACKET:
break # trailing comma
elements.append(self.parse_expression())
self.skip_newlines()
self.expect(TokenType.RBRACKET)
return ListLiteral(elements)
def parse_dict(self) -> DictLiteral:
self.expect(TokenType.LBRACE)
keys = []
values = []
# Skip any newlines after opening brace
self.skip_newlines()
if self.current_token().type != TokenType.RBRACE:
# Parse first key-value pair
key = self.parse_expression()
self.skip_newlines()
self.expect(TokenType.COLON)
self.skip_newlines()
value = self.parse_expression()
keys.append(key)
values.append(value)
# Parse remaining key-value pairs
while True:
self.skip_newlines()
if self.current_token().type != TokenType.COMMA:
break
self.advance() # consume comma
self.skip_newlines()
if self.current_token().type == TokenType.RBRACE:
break # trailing comma
key = self.parse_expression()
self.skip_newlines()
self.expect(TokenType.COLON)
self.skip_newlines()
value = self.parse_expression()
keys.append(key)
values.append(value)
self.skip_newlines()
self.expect(TokenType.RBRACE)
return DictLiteral(keys, values)