SNAPKITTYWEST commited on
Commit
48a06a9
·
verified ·
1 Parent(s): f25b50c

Mirror from SNAPKITTYWEST: parser/parser.py

Browse files
Files changed (1) hide show
  1. parser/parser.py +317 -0
parser/parser.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parser/parser.py
2
+ from __future__ import annotations
3
+ from lexer.lexer import tokenize, Token
4
+ from mantra_ast.nodes import *
5
+ from typing import List, Iterator
6
+
7
+ class ParseError(Exception):
8
+ pass
9
+
10
+ class Parser:
11
+ def __init__(self, tokens):
12
+ self.tokens = list(tokens)
13
+ self.i = 0
14
+
15
+ def peek(self) -> Token:
16
+ return self.tokens[self.i] if self.i < len(self.tokens) else Token('EOF', '', 0, 0)
17
+
18
+ def peek2(self) -> Token:
19
+ return self.tokens[self.i+1] if self.i+1 < len(self.tokens) else Token('EOF', '', 0, 0)
20
+
21
+ def advance(self) -> Token:
22
+ t = self.peek()
23
+ self.i += 1
24
+ return t
25
+
26
+ def expect(self, typ: str) -> Token:
27
+ t = self.advance()
28
+ if t.type != typ:
29
+ raise ParseError(f"Expected {typ} at {t.line}:{t.col}, got {t.type!r} ({t.value!r})")
30
+ return t
31
+
32
+ def match(self, *types) -> bool:
33
+ return self.peek().type in types
34
+
35
+ # ── top level ─────────────────────────────────────────────────────────
36
+
37
+ def parse(self) -> Program:
38
+ modules, items = [], []
39
+ while not self.match('EOF'):
40
+ if self.match('MODULE'):
41
+ modules.append(self._parse_module())
42
+ else:
43
+ items.append(self._parse_item())
44
+ if not modules:
45
+ modules = [Module(name='main', items=items)]
46
+ return Program(modules=modules)
47
+
48
+ def _parse_module(self) -> Module:
49
+ self.expect('MODULE')
50
+ name = self.expect('IDENT').value
51
+ self.expect('LBRACE')
52
+ items = []
53
+ while not self.match('RBRACE', 'EOF'):
54
+ items.append(self._parse_item())
55
+ self.expect('RBRACE')
56
+ return Module(name=name, items=items)
57
+
58
+ # ── item ──────────────────────────────────────────────────────────────
59
+
60
+ def _parse_item(self) -> Node:
61
+ ann = self._parse_annotations()
62
+ t = self.peek()
63
+ if t.type == 'CONST':
64
+ return self._parse_const(ann)
65
+ if t.type == 'LET':
66
+ return self._parse_let(ann)
67
+ if t.type == 'DEFINE':
68
+ return self._parse_define(ann)
69
+ if t.type == 'ASSERT':
70
+ self.advance()
71
+ return Assert(expr=self._parse_expr())
72
+ # expression statement
73
+ return self._parse_expr()
74
+
75
+ def _parse_annotations(self) -> List[Annotation]:
76
+ ann = []
77
+ while self.match('ANNOT'):
78
+ raw = self.advance().value
79
+ if '(' in raw:
80
+ name, rest = raw.split('(', 1)
81
+ ann.append(Annotation(name=name[1:], args=rest.rstrip(')')))
82
+ else:
83
+ ann.append(Annotation(name=raw[1:], args=None))
84
+ return ann
85
+
86
+ def _parse_const(self, ann) -> ConstDecl:
87
+ self.expect('CONST')
88
+ name = self.expect('IDENT').value
89
+ self.expect('ASSIGN')
90
+ val = self._parse_expr()
91
+ return ConstDecl(name=name, value=val, annotations=ann)
92
+
93
+ def _parse_let(self, ann) -> LetDecl:
94
+ self.expect('LET')
95
+ name = self.expect('IDENT').value
96
+ self.expect('ASSIGN')
97
+ val = self._parse_expr()
98
+ return LetDecl(name=name, value=val, annotations=ann)
99
+
100
+ def _parse_define(self, ann) -> FunctionDecl:
101
+ self.expect('DEFINE')
102
+ name = self.expect('IDENT').value
103
+ self.expect('LPAREN')
104
+ params = []
105
+ while not self.match('RPAREN', 'EOF'):
106
+ params.append(self.expect('IDENT').value)
107
+ if self.match('COMMA'):
108
+ self.advance()
109
+ self.expect('RPAREN')
110
+ self.expect('BEGIN')
111
+ body = []
112
+ while not self.match('END', 'EOF'):
113
+ if self.match('RETURN'):
114
+ self.advance()
115
+ body.append(Return(expr=self._parse_expr()))
116
+ elif self.match('ASSERT'):
117
+ self.advance()
118
+ body.append(Assert(expr=self._parse_expr()))
119
+ elif self.match('LET'):
120
+ body.append(self._parse_let([]))
121
+ elif self.match('CONST'):
122
+ body.append(self._parse_const([]))
123
+ else:
124
+ body.append(self._parse_expr())
125
+ self.expect('END')
126
+ return FunctionDecl(name=name, params=params, body=body, annotations=ann)
127
+
128
+ # ── expressions (Pratt-style precedence climbing) ─────────────────────
129
+
130
+ def _parse_expr(self) -> Node:
131
+ return self._parse_or()
132
+
133
+ def _parse_or(self) -> Node:
134
+ left = self._parse_and()
135
+ while self.match('OR', 'PIPE'):
136
+ op = self.advance().value
137
+ left = BinaryExpr(op='or', left=left, right=self._parse_and())
138
+ return left
139
+
140
+ def _parse_and(self) -> Node:
141
+ left = self._parse_equality()
142
+ while self.match('AND', 'AMP'):
143
+ op = self.advance().value
144
+ left = BinaryExpr(op='and', left=left, right=self._parse_equality())
145
+ return left
146
+
147
+ def _parse_equality(self) -> Node:
148
+ left = self._parse_relational()
149
+ while self.match('EQ', 'NEQ'):
150
+ op = self.advance().value
151
+ left = BinaryExpr(op=op, left=left, right=self._parse_relational())
152
+ return left
153
+
154
+ def _parse_relational(self) -> Node:
155
+ left = self._parse_shift()
156
+ while self.match('LT', 'GT', 'LE', 'GE'):
157
+ op = self.advance().value
158
+ left = BinaryExpr(op=op, left=left, right=self._parse_shift())
159
+ return left
160
+
161
+ def _parse_shift(self) -> Node:
162
+ left = self._parse_bitor()
163
+ while self.match('LSH', 'RSH'):
164
+ op = self.advance().value
165
+ left = BinaryExpr(op=op, left=left, right=self._parse_bitor())
166
+ return left
167
+
168
+ def _parse_bitor(self) -> Node:
169
+ left = self._parse_bitxor()
170
+ while self.match('PIPE'):
171
+ self.advance()
172
+ left = BinaryExpr(op='|', left=left, right=self._parse_bitxor())
173
+ return left
174
+
175
+ def _parse_bitxor(self) -> Node:
176
+ left = self._parse_bitand()
177
+ while self.match('CARET'):
178
+ self.advance()
179
+ left = BinaryExpr(op='^', left=left, right=self._parse_bitand())
180
+ return left
181
+
182
+ def _parse_bitand(self) -> Node:
183
+ left = self._parse_add()
184
+ while self.match('AMP'):
185
+ self.advance()
186
+ left = BinaryExpr(op='&', left=left, right=self._parse_add())
187
+ return left
188
+
189
+ def _parse_add(self) -> Node:
190
+ left = self._parse_mul()
191
+ while self.match('PLUS', 'MINUS'):
192
+ op = self.advance().value
193
+ left = BinaryExpr(op=op, left=left, right=self._parse_mul())
194
+ return left
195
+
196
+ def _parse_mul(self) -> Node:
197
+ left = self._parse_unary()
198
+ while self.match('STAR', 'SLASH', 'PERCENT', 'POW'):
199
+ op = self.advance().value
200
+ left = BinaryExpr(op=op, left=left, right=self._parse_unary())
201
+ return left
202
+
203
+ def _parse_unary(self) -> Node:
204
+ if self.match('MINUS', 'TILDE', 'NOT'):
205
+ op = self.advance().value
206
+ return UnaryExpr(op=op, operand=self._parse_unary())
207
+ return self._parse_postfix()
208
+
209
+ def _parse_postfix(self) -> Node:
210
+ node = self._parse_primary()
211
+ while self.match('DOT'):
212
+ self.advance()
213
+ field = self.expect('IDENT').value
214
+ node = FieldAccess(obj=node, field=field)
215
+ return node
216
+
217
+ def _parse_primary(self) -> Node:
218
+ t = self.peek()
219
+
220
+ if t.type == 'NUMBER':
221
+ self.advance()
222
+ return IntegerLiteral(int(t.value))
223
+
224
+ if t.type == 'HEX':
225
+ self.advance()
226
+ return HexLiteral(raw=t.value)
227
+
228
+ if t.type in ('TRUE', 'FALSE'):
229
+ self.advance()
230
+ return BoolLiteral(t.type == 'TRUE')
231
+
232
+ if t.type == 'STRING':
233
+ self.advance()
234
+ s = t.value[1:-1].encode('utf-8').decode('unicode_escape')
235
+ return StringLiteral(s)
236
+
237
+ if t.type == 'BYTES':
238
+ self.advance()
239
+ raw = t.value[2:-1]
240
+ b = raw.encode('utf-8').decode('unicode_escape').encode('latin1')
241
+ return BytesLiteral(b)
242
+
243
+ if t.type == 'SOME':
244
+ self.advance()
245
+ self.expect('LPAREN')
246
+ v = self._parse_expr()
247
+ self.expect('RPAREN')
248
+ return OptionLiteral(tag='some', value=v)
249
+
250
+ if t.type == 'NONE':
251
+ self.advance()
252
+ return OptionLiteral(tag='none', value=None)
253
+
254
+ # identifiers and keyword-named builtins (concat, len, slice, sha256_hex, etc.)
255
+ _CALLABLE_KEYWORDS = {'CONCAT', 'LEN', 'SLICE', 'SOME', 'OK', 'ERR',
256
+ 'BYTES', 'BYTE', 'OPTION', 'RESULT'}
257
+ if t.type == 'IDENT' or t.type in _CALLABLE_KEYWORDS:
258
+ name = self.advance().value
259
+ if self.match('LPAREN'):
260
+ self.advance()
261
+ args = []
262
+ while not self.match('RPAREN', 'EOF'):
263
+ args.append(self._parse_expr())
264
+ if self.match('COMMA'):
265
+ self.advance()
266
+ self.expect('RPAREN')
267
+ return Call(callee=name, args=args)
268
+ return Identifier(name=name)
269
+
270
+ if t.type == 'LPAREN':
271
+ self.advance()
272
+ expr = self._parse_expr()
273
+ self.expect('RPAREN')
274
+ return expr
275
+
276
+ if t.type == 'LBRACE':
277
+ return self._parse_dict_or_list()
278
+
279
+ if t.type == 'LBRACKET':
280
+ self.advance()
281
+ items = []
282
+ while not self.match('RBRACKET', 'EOF'):
283
+ items.append(self._parse_expr())
284
+ if self.match('COMMA'):
285
+ self.advance()
286
+ self.expect('RBRACKET')
287
+ return ListLiteral(items=items)
288
+
289
+ raise ParseError(f"Unexpected token {t.type!r} ({t.value!r}) at {t.line}:{t.col}")
290
+
291
+ def _parse_dict_or_list(self) -> Node:
292
+ self.expect('LBRACE')
293
+ # peek: if next is IDENT COLON → dict
294
+ if self.peek().type == 'IDENT' and self.peek2().type == 'COLON':
295
+ pairs = []
296
+ while not self.match('RBRACE', 'EOF'):
297
+ key = self.expect('IDENT').value
298
+ self.expect('COLON')
299
+ val = self._parse_expr()
300
+ pairs.append((key, val))
301
+ if self.match('COMMA'):
302
+ self.advance()
303
+ self.expect('RBRACE')
304
+ return DictLiteral(pairs=pairs)
305
+ else:
306
+ items = []
307
+ while not self.match('RBRACE', 'EOF'):
308
+ items.append(self._parse_expr())
309
+ if self.match('COMMA'):
310
+ self.advance()
311
+ self.expect('RBRACE')
312
+ return ListLiteral(items=items)
313
+
314
+
315
+ def parse(code: str) -> Program:
316
+ tokens = tokenize(code)
317
+ return Parser(tokens).parse()