This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.py
More file actions
812 lines (685 loc) · 29.1 KB
/
parser.py
File metadata and controls
812 lines (685 loc) · 29.1 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
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, List, Optional, Tuple, Union
from fractions import Fraction
from lexer import PrefixParseError, Token
@dataclass(slots=True)
class SourceLocation:
file: str
line: int
column: int
statement: str
@dataclass(slots=True)
class Node:
location: SourceLocation
@dataclass(slots=True)
class Program(Node):
statements: List["Statement"]
class Statement(Node):
pass
@dataclass(slots=True)
class Block(Node):
statements: List[Statement]
@dataclass(slots=True)
class Assignment(Statement):
target: str
declared_type: Optional[str]
expression: "Expression"
@dataclass(slots=True)
class Declaration(Statement):
name: str
declared_type: str
@dataclass(slots=True)
class ExpressionStatement(Statement):
expression: "Expression"
@dataclass(slots=True)
class IfBranch:
condition: "Expression"
block: Block
@dataclass(slots=True)
class IfStatement(Statement):
condition: "Expression"
then_block: Block
elifs: List[IfBranch]
else_block: Optional[Block]
@dataclass(slots=True)
class WhileStatement(Statement):
condition: "Expression"
block: Block
@dataclass(slots=True)
class ForStatement(Statement):
counter: str
target_expr: "Expression"
block: Block
@dataclass(slots=True)
class ParForStatement(Statement):
counter: str
target_expr: "Expression"
block: Block
@dataclass(slots=True)
class FuncDef(Statement):
name: str
params: List["Param"]
return_type: str
body: Block
@dataclass(slots=True)
class Param:
type: str
name: str
default: Optional["Expression"]
@dataclass(slots=True)
class ReturnStatement(Statement):
expression: Optional["Expression"]
@dataclass(slots=True)
class PopStatement(Statement):
expression: "Expression"
@dataclass(slots=True)
class BreakStatement(Statement):
expression: "Expression"
@dataclass(slots=True)
class GotoStatement(Statement):
expression: "Expression"
@dataclass(slots=True)
class GotopointStatement(Statement):
expression: "Expression"
@dataclass(slots=True)
class ContinueStatement(Statement):
pass
@dataclass(slots=True)
class AsyncStatement(Statement):
block: Block
@dataclass(slots=True)
class ThrStatement(Statement):
symbol: str
block: Block
@dataclass(slots=True)
class TryStatement(Statement):
try_block: Block
catch_symbol: Optional[str]
catch_block: Block
class Expression(Node):
pass
@dataclass(slots=True)
class LambdaExpression(Expression):
params: List["Param"]
return_type: str
body: Block
@dataclass(slots=True)
class TensorLiteral(Expression):
items: List["Expression"]
@dataclass(slots=True)
class MapLiteral(Expression):
items: List[Tuple["Expression", "Expression"]]
@dataclass(slots=True)
class AsyncExpression(Expression):
block: Block
@dataclass(slots=True)
class IndexExpression(Expression):
base: Expression
indices: List[Expression]
# True when the indices were written with angle-brackets `<...>` (map-style),
# False when written with square brackets `[...]` (tensor-style).
is_map: bool
@dataclass(slots=True)
class Range(Expression):
lo: Expression
hi: Expression
@dataclass(slots=True)
class Star(Expression):
"""Represents a full-dimension slice `*` used inside tensor indices."""
pass
@dataclass(slots=True)
class TensorSetStatement(Statement):
target: IndexExpression
value: "Expression"
@dataclass(slots=True)
class Literal(Expression):
value: Union[int, float, str]
literal_type: str
@dataclass(slots=True)
class Identifier(Expression):
name: str
@dataclass(slots=True)
class PointerExpression(Expression):
target: str
@dataclass(slots=True)
class TypedTarget(Expression):
declared_type: str
target: Expression
@dataclass(slots=True)
class CallExpression(Expression):
callee: Expression
args: List["CallArgument"]
@dataclass(slots=True)
class CallArgument:
name: Optional[str]
expression: Expression
class Parser:
def __init__(
self,
tokens: List[Token],
filename: str,
source_lines: List[str],
*,
type_names: Optional[Iterable[str]] = None,
):
self.tokens = tokens
self.filename = filename
self.source_lines = source_lines
self.type_names = set(type_names) if type_names is not None else {"INT", "FLT", "STR", "TNS", "FUNC", "MAP", "THR"}
self.index = 0
def _parse_flt_literal(self, raw: str, *, token: Token) -> float:
# raw is of the form [-]?[01]+\.[01]+
text = raw.strip()
neg = text.startswith("-")
if neg:
text = text[1:]
if "." not in text:
raise PrefixParseError(f"Invalid FLT literal at line {token.line}")
left, right = text.split(".", 1)
if left == "" or right == "":
raise PrefixParseError(f"Invalid FLT literal at line {token.line}")
if not set(left).issubset({"0", "1"}) or not set(right).issubset({"0", "1"}):
raise PrefixParseError(f"Invalid FLT literal at line {token.line}")
numerator = (int(left, 2) << len(right)) + int(right, 2)
denom = 1 << len(right)
value = float(Fraction(numerator, denom))
return -value if neg else value
def parse(self) -> Program:
statements: List[Statement] = self._parse_statements(stop_tokens={"EOF"})
eof_token: Token = self._peek()
return Program(location=self._location_from_token(eof_token), statements=statements)
def _parse_statements(self, stop_tokens: Iterable[str]) -> List[Statement]:
statements: List[Statement] = []
while self._peek().type not in stop_tokens:
if self._match("NEWLINE"):
continue
statements.append(self._parse_statement())
self._consume_newlines()
return statements
def _parse_statement(self) -> Statement:
if self._is_typed_assignment_start():
return self._parse_typed_assignment()
token = self._peek()
if self._looks_like_index_assignment():
return self._parse_index_assignment()
if token.type == "TRY":
return self._parse_try()
if token.type == "CATCH":
raise PrefixParseError(f"CATCH must immediately follow a TRY block at line {token.line}")
if token.type == "FUNC":
return self._parse_func()
if token.type == "IF":
return self._parse_if()
if token.type == "THR":
return self._parse_thr()
if token.type == "ASYNC":
return self._parse_async()
if token.type == "WHILE":
return self._parse_while()
if token.type == "PARFOR":
return self._parse_parfor()
if token.type == "FOR":
return self._parse_for()
if token.type == "RETURN":
return self._parse_return()
if token.type == "POP":
return self._parse_pop()
if token.type == "BREAK":
return self._parse_break()
if token.type == "CONTINUE":
return self._parse_continue()
if token.type == "GOTO":
return self._parse_goto()
if token.type == "GOTOPOINT":
return self._parse_gotopoint()
if token.type == "IDENT" and self._peek_next().type == "EQUALS":
return self._parse_assignment(None)
expr: Expression = self._parse_expression()
return ExpressionStatement(location=expr.location, expression=expr)
def _parse_assignment(self, declared_type: Optional[str]) -> Assignment:
ident = self._consume("IDENT")
self._consume("EQUALS")
expr = self._parse_expression()
location: SourceLocation = self._location_from_token(ident)
return Assignment(location=location, target=ident.value, expression=expr, declared_type=declared_type)
def _parse_typed_assignment(self) -> Statement:
type_token = self._consume_type_token()
self._consume("COLON")
# Allow a bare type declaration (e.g. `INT: x`) which records the
# symbol's declared type but does not perform an assignment. If an
# equals follows, parse as a normal typed assignment.
if self._peek().type == "IDENT" and self._peek_next().type == "EQUALS":
return self._parse_assignment(type_token.value)
ident = self._consume("IDENT")
location: SourceLocation = self._location_from_token(type_token)
return Declaration(location=location, name=ident.value, declared_type=type_token.value)
def _parse_index_assignment(self) -> TensorSetStatement:
target = self._parse_index_expression()
equals_token = self._consume("EQUALS")
value_expr = self._parse_expression()
return TensorSetStatement(location=self._location_from_token(equals_token), target=target, value=value_expr)
def _parse_func(self) -> FuncDef:
keyword = self._consume("FUNC")
name_token = self._consume("IDENT")
self._consume("LPAREN")
params: List[Param] = []
seen_default = False
if self._peek().type != "RPAREN":
while True:
type_token = self._consume_type_token()
self._consume("COLON")
name_tok = self._consume("IDENT")
default_expr: Optional[Expression] = None
if self._match("EQUALS"):
seen_default = True
default_expr = self._parse_expression()
elif seen_default:
raise PrefixParseError(
f"Positional parameter cannot follow parameter with default at line {name_tok.line}")
params.append(Param(type=type_token.value, name=name_tok.value, default=default_expr))
if not self._match("COMMA"):
break
self._consume("RPAREN")
self._consume("COLON")
return_type = self._consume_type_token()
block: Block = self._parse_block()
location: SourceLocation = self._location_from_token(keyword)
return FuncDef(location=location, name=name_token.value, params=params, return_type=return_type.value, body=block)
def _parse_lambda(self) -> LambdaExpression:
keyword = self._consume("LAMBDA")
self._consume("LPAREN")
params: List[Param] = []
seen_default = False
if self._peek().type != "RPAREN":
while True:
type_token = self._consume_type_token()
self._consume("COLON")
name_tok = self._consume("IDENT")
default_expr: Optional[Expression] = None
if self._match("EQUALS"):
seen_default = True
default_expr = self._parse_expression()
elif seen_default:
raise PrefixParseError(
f"Positional parameter cannot follow parameter with default at line {name_tok.line}")
params.append(Param(type=type_token.value, name=name_tok.value, default=default_expr))
if not self._match("COMMA"):
break
self._consume("RPAREN")
self._consume("COLON")
return_type = self._consume_type_token()
block: Block = self._parse_block()
location: SourceLocation = self._location_from_token(keyword)
return LambdaExpression(location=location, params=params, return_type=return_type.value, body=block)
def _parse_if(self) -> IfStatement:
keyword = self._consume("IF")
condition: Expression = self._parse_parenthesized_expression()
then_block: Block = self._parse_block()
elifs: List[IfBranch] = []
while self._match("ELSEIF"):
cond: Expression = self._parse_parenthesized_expression()
block: Block = self._parse_block()
elifs.append(IfBranch(condition=cond, block=block))
else_block: Optional[Block] = self._parse_block() if self._match("ELSE") else None
return IfStatement(
location=self._location_from_token(keyword),
condition=condition,
then_block=then_block,
elifs=elifs,
else_block=else_block,
)
def _parse_while(self) -> WhileStatement:
keyword = self._consume("WHILE")
condition: Expression = self._parse_parenthesized_expression()
block: Block = self._parse_block()
return WhileStatement(location=self._location_from_token(keyword), condition=condition, block=block)
def _parse_for(self) -> ForStatement:
keyword = self._consume("FOR")
self._consume("LPAREN")
counter = self._consume("IDENT")
self._consume("COMMA")
target: Expression = self._parse_expression()
self._consume("RPAREN")
block: Block = self._parse_block()
return ForStatement(location=self._location_from_token(keyword), counter=counter.value, target_expr=target, block=block)
def _parse_parfor(self) -> ParForStatement:
keyword = self._consume("PARFOR")
self._consume("LPAREN")
counter = self._consume("IDENT")
self._consume("COMMA")
target: Expression = self._parse_expression()
self._consume("RPAREN")
block: Block = self._parse_block()
return ParForStatement(location=self._location_from_token(keyword), counter=counter.value, target_expr=target, block=block)
def _parse_return(self) -> ReturnStatement:
keyword = self._consume("RETURN")
expression: Expression = self._parse_parenthesized_expression()
return ReturnStatement(location=self._location_from_token(keyword), expression=expression)
def _parse_pop(self) -> PopStatement:
keyword = self._consume("POP")
expression: Expression = self._parse_parenthesized_expression()
return PopStatement(location=self._location_from_token(keyword), expression=expression)
def _parse_break(self) -> BreakStatement:
keyword = self._consume("BREAK")
expression: Expression = self._parse_parenthesized_expression()
return BreakStatement(location=self._location_from_token(keyword), expression=expression)
def _parse_goto(self) -> GotoStatement:
keyword = self._consume("GOTO")
expression: Expression = self._parse_parenthesized_expression()
return GotoStatement(location=self._location_from_token(keyword), expression=expression)
def _parse_gotopoint(self) -> GotopointStatement:
keyword = self._consume("GOTOPOINT")
expression: Expression = self._parse_parenthesized_expression()
return GotopointStatement(location=self._location_from_token(keyword), expression=expression)
def _parse_continue(self) -> ContinueStatement:
keyword = self._consume("CONTINUE")
# Expect empty parentheses: CONTINUE()
self._consume("LPAREN")
self._consume("RPAREN")
return ContinueStatement(location=self._location_from_token(keyword))
def _parse_async(self) -> AsyncStatement:
keyword = self._consume("ASYNC")
block: Block = self._parse_block()
return AsyncStatement(location=self._location_from_token(keyword), block=block)
def _parse_thr(self) -> ThrStatement:
keyword = self._consume("THR")
self._consume("LPAREN")
ident = self._consume("IDENT")
self._consume("RPAREN")
block: Block = self._parse_block()
return ThrStatement(location=self._location_from_token(keyword), symbol=ident.value, block=block)
def _parse_try(self) -> TryStatement:
keyword = self._consume("TRY")
try_block: Block = self._parse_block()
# Allow newlines between the TRY block and its required CATCH.
self._consume_newlines()
if self._peek().type != "CATCH":
tok = self._peek()
raise PrefixParseError(
f"TRY must be followed by a CATCH block (found {tok.type}) at line {tok.line}"
)
self._consume("CATCH")
catch_symbol: Optional[str] = None
if self._match("LPAREN"):
# Syntax: CATCH(sym){...} or CATCH() for no symbol.
if self._peek().type == "RPAREN":
# Empty parentheses: CATCH()
self._consume("RPAREN")
elif self._peek().type == "IDENT":
# Single identifier: CATCH(name)
sym = self._consume("IDENT")
self._consume("RPAREN")
catch_symbol = sym.value
else:
tok = self._peek()
raise PrefixParseError(
f"Invalid CATCH syntax (found {tok.type}) at line {tok.line}"
)
catch_block: Block = self._parse_block()
return TryStatement(
location=self._location_from_token(keyword),
try_block=try_block,
catch_symbol=catch_symbol,
catch_block=catch_block,
)
def _parse_block(self) -> Block:
opening = self._peek().type
if opening == "LBRACE":
start = self._consume("LBRACE")
closing = "RBRACE"
else:
raise PrefixParseError(f"Expected '{{' to start block but found {opening}")
statements: List[Statement] = self._parse_statements(stop_tokens={closing})
self._consume(closing)
return Block(location=self._location_from_token(start), statements=statements)
def _parse_expression(self) -> Expression:
expr = self._parse_primary()
while True:
tok_type = self._peek().type
if tok_type == "LBRACKET" or tok_type == "LANGLE":
expr = self._parse_index_suffix(expr)
continue
if tok_type == "LPAREN":
expr = self._parse_call_suffix(expr)
continue
break
return expr
def _parse_primary(self) -> Expression:
token = self._peek()
if token.type == "NUMBER":
number: Token = self._consume("NUMBER")
sval = number.value
if sval.startswith("-"):
if len(sval) == 1:
raise PrefixParseError(f"Invalid numeric literal at line {number.line}")
value = -int(sval[1:], 2)
else:
value = int(sval, 2)
return Literal(location=self._location_from_token(number), value=value, literal_type="INT")
if token.type == "FLOAT":
flt: Token = self._consume("FLOAT")
flt_value = self._parse_flt_literal(flt.value, token=flt)
return Literal(location=self._location_from_token(flt), value=flt_value, literal_type="FLT")
if token.type == "STRING":
string_token = self._consume("STRING")
return Literal(location=self._location_from_token(string_token), value=string_token.value, literal_type="STR")
if token.type == "LBRACKET":
return self._parse_tensor_literal()
if token.type == "LANGLE":
return self._parse_map_literal()
if token.type == "LAMBDA":
return self._parse_lambda()
if token.type == "ASYNC":
return self._parse_async_expression()
if token.type == "IDENT":
ident: Token = self._consume("IDENT")
location: SourceLocation = self._location_from_token(ident)
return Identifier(location=location, name=ident.value)
if token.type == "AT":
at_tok = self._consume("AT")
ident_tok = self._consume("IDENT")
location = self._location_from_token(at_tok)
return PointerExpression(location=location, target=ident_tok.value)
if token.type == "LPAREN":
self._consume("LPAREN")
expr: Expression = self._parse_expression()
self._consume("RPAREN")
return expr
raise PrefixParseError(f"Unexpected token {token.type} in expression at line {token.line}")
def _parse_index_suffix(self, base: Expression) -> IndexExpression:
start_tok = self._peek()
if start_tok.type == "LBRACKET":
lbracket = self._consume("LBRACKET")
closing = "RBRACKET"
else:
lbracket = self._consume("LANGLE")
closing = "RANGLE"
indices: List[Expression] = []
if self._peek().type != closing:
while True:
# Support star `*` (full-dimension slice), and slice
# syntax lo - hi inside index brackets. The lexer emits a
# DASH token for '-' when it's not starting a signed number.
if self._peek().type == "STAR":
star_tok = self._consume("STAR")
indices.append(Star(location=self._location_from_token(star_tok)))
else:
first = self._parse_expression()
if self._peek().type == "DASH":
self._consume("DASH")
second = self._parse_expression()
indices.append(Range(lo=first, hi=second, location=first.location))
else:
indices.append(first)
if not self._match("COMMA"):
break
self._consume(closing)
is_map = start_tok.type == "LANGLE"
return IndexExpression(location=self._location_from_token(lbracket), base=base, indices=indices, is_map=is_map)
def _parse_index_expression(self) -> IndexExpression:
expr = self._parse_primary()
if self._peek().type not in ("LBRACKET", "LANGLE"):
raise PrefixParseError(f"Expected '[' or '<' in indexed assignment at line {self._peek().line}")
expr = self._parse_index_suffix(expr)
while self._peek().type in ("LBRACKET", "LANGLE"):
expr = self._parse_index_suffix(expr)
if not isinstance(expr, IndexExpression):
raise PrefixParseError(f"Invalid indexed assignment at line {self._peek().line}")
return expr
def _parse_call_suffix(self, callee: Expression) -> CallExpression:
lparen = self._consume("LPAREN")
args: List[CallArgument] = []
seen_kw = False
if self._peek().type != "RPAREN":
arg_index = 0
while True:
if isinstance(callee, Identifier) and callee.name == "ASSIGN" and arg_index == 0:
# ASSIGN allows a typed target in its first argument: ASSIGN(INT: x, expr)
if self._peek().value in self.type_names and self._peek_next().type == "COLON":
type_tok = self._consume_type_token()
self._consume("COLON")
if self._peek().type != "IDENT":
raise PrefixParseError(f"ASSIGN typed target must be an identifier at line {self._peek().line}")
ident_tok = self._consume("IDENT")
ident_expr = Identifier(location=self._location_from_token(ident_tok), name=ident_tok.value)
typed_expr = TypedTarget(
location=self._location_from_token(type_tok),
declared_type=type_tok.value,
target=ident_expr,
)
args.append(CallArgument(name=None, expression=typed_expr))
else:
arg_expr = self._parse_expression()
if not isinstance(arg_expr, (Identifier, IndexExpression)):
raise PrefixParseError(f"ASSIGN target must be identifier or indexed target at line {self._peek().line}")
args.append(CallArgument(name=None, expression=arg_expr))
else:
if self._peek().type == "IDENT" and self._peek_next().type == "EQUALS":
name_tok = self._consume("IDENT")
self._consume("EQUALS")
arg_expr = self._parse_expression()
seen_kw = True
args.append(CallArgument(name=name_tok.value, expression=arg_expr))
else:
if seen_kw:
raise PrefixParseError(
f"Positional argument cannot follow keyword argument at line {self._peek().line}")
args.append(CallArgument(name=None, expression=self._parse_expression()))
if not self._match("COMMA"):
break
arg_index += 1
self._consume("RPAREN")
return CallExpression(location=self._location_from_token(lparen), callee=callee, args=args)
def _parse_tensor_literal(self) -> TensorLiteral:
lbracket = self._consume("LBRACKET")
items: List[Expression] = []
if self._peek().type != "RBRACKET":
while True:
items.append(self._parse_expression())
if not self._match("COMMA"):
break
self._consume("RBRACKET")
return TensorLiteral(location=self._location_from_token(lbracket), items=items)
def _parse_map_literal(self) -> MapLiteral:
langle = self._consume("LANGLE")
items: List[Tuple[Expression, Expression]] = []
if self._peek().type != "RANGLE":
while True:
key_expr = self._parse_expression()
self._consume("EQUALS")
val_expr = self._parse_expression()
items.append((key_expr, val_expr))
if not self._match("COMMA"):
break
self._consume("RANGLE")
return MapLiteral(location=self._location_from_token(langle), items=items)
def _parse_async_expression(self) -> AsyncExpression:
keyword = self._consume("ASYNC")
block: Block = self._parse_block()
return AsyncExpression(location=self._location_from_token(keyword), block=block)
def _parse_parenthesized_expression(self) -> Expression:
self._consume("LPAREN")
expr = self._parse_expression()
self._consume("RPAREN")
return expr
def _looks_like_index_assignment(self) -> bool:
i = self.index
tokens = self.tokens
if i >= len(tokens) or tokens[i].type != "IDENT":
return False
i += 1
if i >= len(tokens) or tokens[i].type not in ("LBRACKET", "LANGLE"):
return False
# Walk balanced brackets to find the end of the indexed target.
depth = 0
while i < len(tokens):
tok = tokens[i]
if tok.type in ("LBRACKET", "LANGLE"):
depth += 1
elif tok.type in ("RBRACKET", "RANGLE"):
depth -= 1
if depth == 0:
i += 1
break
i += 1
if depth != 0:
return False
# Support additional bracketed or angled suffixes like a[1][2] or a[1]<"k">.
while i < len(tokens) and tokens[i].type in ("LBRACKET", "LANGLE"):
# We advance past the opening bracket/angle and treat that as
# one level of depth already; initialize depth=1 accordingly.
depth = 1
i += 1
while i < len(tokens):
tok = tokens[i]
if tok.type in ("LBRACKET", "LANGLE"):
depth += 1
elif tok.type in ("RBRACKET", "RANGLE"):
depth -= 1
if depth == 0:
i += 1
break
i += 1
if depth != 0:
return False
while i < len(tokens) and tokens[i].type == "NEWLINE":
i += 1
return i < len(tokens) and tokens[i].type == "EQUALS"
def _consume(self, token_type: str) -> Token:
token = self._peek()
if token.type != token_type:
raise PrefixParseError(f"Expected token {token_type} but found {token.type} at line {token.line}")
self.index += 1
return token
def _match(self, token_type: str) -> bool:
if self._peek().type == token_type:
self.index += 1
return True
return False
def _consume_newlines(self) -> None:
while self._match("NEWLINE"):
continue
def _peek(self) -> Token:
return self.tokens[self.index]
def _peek_next(self) -> Token:
return self.tokens[self.index + 1]
def _location_from_token(self, token: Token) -> SourceLocation:
line_index = token.line - 1
statement = ""
if 0 <= line_index < len(self.source_lines):
statement = self.source_lines[line_index].strip()
return SourceLocation(file=self.filename, line=token.line, column=token.column, statement=statement)
def _consume_type_token(self) -> Token:
token = self._peek()
if token.value not in self.type_names:
raise PrefixParseError(f"Unknown type '{token.value}' at line {token.line}")
self.index += 1
return token
def _is_typed_assignment_start(self) -> bool:
current = self._peek()
if current.value not in self.type_names:
return False
if self.index + 1 >= len(self.tokens):
return False
return self._peek_next().type == "COLON"