-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevp.py
More file actions
3548 lines (2811 loc) · 113 KB
/
devp.py
File metadata and controls
3548 lines (2811 loc) · 113 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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import string
import os
import math
import random
from _thread import start_new_thread
# CONSTANTS
NUMBERS = '0123456789'
NUMDOT = '0123456789.'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + NUMBERS
KEYWORDS = (
'async',
'import',
'bin',
'function',
'attr',
'&',
'|',
'bake',
'var',
'for',
'while',
'null',
'if',
'elif',
'else',
'return',
'continue',
'break',
'method',
'ingredients',
'recipe'
)
BREAK = ';'
IGNORE = ' \t\n'
LIBRARIES = {}
# FUNCTIONS
def string_with_arrows(text, pos_start, pos_end):
result = ''
# Calculate indices
idx_start = max(text.rfind('\n', 0, pos_start.idx), 0)
idx_end = text.find('\n', idx_start + 1)
if idx_end < 0: idx_end = len(text)
# Generate each line
line_count = pos_end.ln - pos_start.ln + 1
for i in range(line_count):
# Calculate line columns
line = text[idx_start:idx_end]
col_start = pos_start.col if i == 0 else 0
col_end = pos_end.col if i == line_count - 1 else len(line) - 1
# Append to result
result += line + '\n'
result += ' ' * col_start + '^' * (col_end - col_start)
# Re-calculate indices
idx_start = idx_end
idx_end = text.find('\n', idx_start + 1)
if idx_end < 0: idx_end = len(text)
return result.replace('\t', '')
# POSITION
class Position:
def __init__(self, idx: int, ln: int, col: int, fn: str, ftext: str) -> None:
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftext = ftext
def advance(self, current_char: str = None):
self.idx += 1
self.col += 1
if current_char == BREAK:
self.ln += 1
self.col = 0
return self
def copy(self):
return Position(self.idx, self.ln, self.col, self.fn, self.ftext)
# ERRORS
class Error:
def __init__(self, pos_start: Position, pos_end: Position, error_name, details) -> None:
self.error_name = error_name
self.details = details
self.pos_start = pos_start
self.pos_end = pos_end
def as_string(self) -> str:
return f'{self.error_name}: {self.details}\nFile {self.pos_start.fn}, line {self.pos_start.ln + 1}\n\n' \
f'{string_with_arrows(self.pos_start.ftext, self.pos_start, self.pos_end)}'
class IllegalCharError(Error):
def __init__(self, start_pos: Position, end_pos: Position, details: str):
super().__init__(start_pos, end_pos, 'Illegal Character', details)
class ExpectedCharError(Error):
def __init__(self, start_pos: Position, end_pos: Position, details: str):
super().__init__(start_pos, end_pos, 'Expected Character', details)
class RTError(Error):
def __init__(self, start_pos: Position, end_pos: Position, details: str, context):
super().__init__(start_pos, end_pos, 'Runtime Error', details)
self.context = context
def as_string(self) -> str:
return f'{self.generate_traceback()}' \
f'{self.error_name}: {self.details}\nFile {self.pos_start.fn}, line {self.pos_start.ln + 1}\n\n' \
f'{string_with_arrows(self.pos_start.ftext, self.pos_start, self.pos_end)}'
def generate_traceback(self) -> str:
result = ''
pos = self.pos_start
ctx = self.context
while ctx:
result = f' File {pos.fn}, line {pos.ln + 1}, in {ctx.display_name}\n' + result
pos = ctx.parent_entry_pos
ctx = ctx.parent
return f'Traceback (most recent call last):\n{result}'
class InvalidSyntax(Error):
def __init__(self, start_pos: Position, end_pos: Position, details: str):
super().__init__(start_pos, end_pos, 'Invalid Syntax', details)
# TOKENS
TT_INT = 'INT'
TT_FLOAT = 'FLOAT'
TT_STRING = 'STRING'
TT_BOOL = 'BOOL'
TT_PLUS = 'PLUS'
TT_MINUS = 'MINUS'
TT_MUL = 'MUL'
TT_DIV = 'DIV'
TT_LPAREN = 'LPAREN'
TT_RPAREN = 'RPAREN'
TT_EOF = 'EoF'
TT_NEWLINE = 'NEWLINE'
TT_POWER = 'POWER'
TT_IDENTIFIER = 'IDENTIFIER'
TT_KEYWORD = 'KEYWORD'
TT_EQ = 'EQ'
TT_EE = 'EE'
TT_NE = 'NE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_AND = 'AND'
TT_OR = 'OR'
TT_NOT = 'NOT'
TT_CLACCESS = '::'
TT_MOD = 'MOD'
TT_QUERY = 'QUERY'
TT_BITE = 'BITE'
TT_DEFAULTQUE = 'DEFAULTQUE'
TT_QUEBACK = 'QUEBACK'
TT_LAMBDA = 'LAMBDA'
TT_STEP = 'STEP'
TT_COMMA = 'COMMA'
TT_OPENSIGN = "OPENSIGN"
TT_CLOSESIGN = "CLOSESIGN"
TT_LSQUARE = 'LSQUARE'
TT_RSQUARE = 'RSQUARE'
TT_OPEN = 'TT_OPEN'
TT_CLOSE = 'TT_CLOSE'
TT_PLE = 'TT_PLUSEQUALS'
TT_MIE = 'TT_MINUSEQUALS'
TT_MUE = 'TT_MULTIPLYEQUALS'
TT_DIE = 'TT_DIVIDEEQUALS'
TT_POE = 'TT_POWEREQUALS'
TT_INCR = 'TT_INCREMENT'
TT_DECR = 'TT_DECREMENT'
TT_DICT = 'TT_DICTIONARY'
TT_DOT = 'TT_DOT'
TOKEY = {
'[': TT_LSQUARE,
'::': TT_CLACCESS,
'%': TT_MOD,
']': TT_RSQUARE,
',': TT_COMMA,
'+': TT_PLUS,
'++': TT_INCR,
'--': TT_DECR,
'>>': TT_STEP,
':': TT_BITE,
'$': TT_QUEBACK,
'$_': TT_DEFAULTQUE,
'?': TT_QUERY,
'-': TT_MINUS,
'*': TT_MUL,
'/': TT_DIV,
'(': TT_LPAREN,
')': TT_RPAREN,
'^': TT_POWER,
'=>': TT_EQ,
'&': TT_AND,
'|': TT_OR,
'->': TT_LAMBDA,
';': TT_NEWLINE,
'{': TT_OPEN,
'}': TT_CLOSE,
'^=': TT_POE,
'*=': TT_MUE,
'/=': TT_DIE,
'+=': TT_PLE,
'-=': TT_MIE,
'.': TT_DOT
}
class Token:
def __init__(self, type_: str, value=None, pos_start: Position = None, pos_end: Position = None) -> None:
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start.copy()
self.pos_end = pos_end.copy() if pos_end else pos_start.copy().advance()
def __repr__(self) -> str:
return f'{self.type}:{self.value}' if self.value else f'{self.type}'
def matches(self, type_, value):
return self.type == type_ and self.value == value
# NODES
class ImportNode:
def __init__(self, file_name_tok):
self.file_name_tok = file_name_tok
self.pos_start = file_name_tok.pos_start
self.pos_end = file_name_tok.pos_end
class FuncDefNode:
def __init__(self, var_name_tok, arg_name_toks, body_node, autoreturn, asynchronous):
self.var_name_tok = var_name_tok
self.asynchronous = asynchronous
self.arg_name_toks = arg_name_toks
self.body_node = body_node
self.autoreturn = autoreturn
self.pos_start = self.var_name_tok.pos_start if self.var_name_tok else \
self.arg_name_toks[0].pos_start if self.arg_name_toks else self.body_node.pos_start
self.pos_end = self.body_node.pos_end
class MethDefNode:
def __init__(self, var_name_tok, arg_name_toks, body_node, autoreturn, bin_, asynchronous):
self.var_name_tok = var_name_tok
self.asynchronous = asynchronous
self.arg_name_toks = arg_name_toks
self.body_node = body_node
self.autoreturn = autoreturn
self.bin = bin_
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.body_node.pos_end
class ClassDefNode:
def __init__(self, class_name_tok, attribute_name_toks, arg_name_toks, make_node, methods, pos_end):
self.class_name_tok = class_name_tok
self.make_node = make_node
self.attribute_name_toks = attribute_name_toks
self.arg_name_toks = arg_name_toks
self.methods = methods
self.pos_start = self.class_name_tok.pos_start
self.pos_end = pos_end
class ClassNode:
def __init__(self, context, methods):
self.context = context
self.methods = methods
class CallNode:
def __init__(self, node_to_call, arg_nodes):
self.node_to_call = node_to_call
self.arg_nodes = arg_nodes
self.pos_start = self.node_to_call.pos_start
self.pos_end = self.arg_nodes[-1].pos_end if self.arg_nodes else self.node_to_call.pos_end
class ReturnNode:
def __init__(self, node_to_return, pos_start, pos_end):
self.node_to_return = node_to_return
self.pos_start = pos_start
self.pos_end = pos_end
class BreakNode:
def __init__(self, pos_start, pos_end):
self.pos_start = pos_start
self.pos_end = pos_end
class ContinueNode:
def __init__(self, pos_start, pos_end):
self.pos_start = pos_start
self.pos_end = pos_end
class ListNode:
def __init__(self, element_nodes, pos_start, pos_end):
self.elements = element_nodes
self.pos_start = pos_start
self.pos_end = pos_end
class DictNode:
def __init__(self, dict_, pos_start, pos_end):
self.dict = dict_
self.pos_start = pos_start
self.pos_end = pos_end
def get(self, key):
return self.dict[key]
def delete(self, key):
del self.dict[key]
return self
def set(self, key, value):
self.dict[key] = value
return self
class ValueNode:
def __init__(self, tok: Token) -> None:
self.tok = tok
self.pos_start = tok.pos_start
self.pos_end = tok.pos_end
def __repr__(self) -> str:
return f'{self.tok}'
class NullNode(ValueNode):
pass
class NumberNode(ValueNode):
pass
class StringNode(ValueNode):
pass
class BooleanNode(ValueNode):
def __repr__(self) -> str:
return 'true' if self.tok.value else 'false'
class QueryNode:
def __init__(self, cases, else_case):
self.else_case = else_case
self.cases = cases
self.pos_start = cases[0][0].pos_start
self.pos_end = (else_case if else_case else cases[-1])[0].pos_end
class ForNode:
def __init__(self, var_name_tok, start_value_node, end_value_node, step_value_node, body_node, retnull):
self.var_name_tok = var_name_tok
self.start_value_node = start_value_node
self.end_value_node = end_value_node
self.step_value_node = step_value_node
self.body_node = body_node
self.retnull = retnull
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.body_node.pos_end
class WhileNode:
def __init__(self, condition_node, body_node, retnull):
self.condition_node = condition_node
self.body_node = body_node
self.retnull = retnull
self.pos_start = self.condition_node.pos_start
self.pos_end = self.body_node.pos_end
class VarAccessNode:
def __init__(self, var_name_tok):
self.var_name_tok = var_name_tok
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.var_name_tok.pos_end
class VarAssignNode:
def __init__(self, var_name_tok, value_node, locked=False):
self.var_name_tok = var_name_tok
self.value_node = value_node
self.locked = locked
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.var_name_tok.pos_end
class VarNode:
def __init__(self, value_node, locked=False):
self.locked = locked
self.value_node = value_node
class AttrAccessNode:
def __init__(self, var_name_tok):
self.var_name_tok = var_name_tok
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.var_name_tok.pos_end
class AttrDeclareNode:
def __init__(self, attr_name_tok):
self.attr_name_tok = attr_name_tok
self.pos_start = self.attr_name_tok.pos_start
self.pos_end = self.attr_name_tok.pos_end
class AttrNode:
def __init__(self, value_node):
self.value_node = value_node
class AttrAssignNode:
def __init__(self, var_name_tok, value_node):
self.var_name_tok = var_name_tok
self.value_node = value_node
self.pos_start = self.var_name_tok.pos_start
self.pos_end = self.var_name_tok.pos_end
class ClaccessNode:
def __init__(self, cls, atr):
self.class_tok = cls
self.attr_name_tok = atr
self.pos_start = cls.pos_start
self.pos_end = atr.pos_end
class BinOpNode:
def __init__(self, left_node, op_tok: Token, right_node) -> None:
self.left_node = left_node
self.op_tok = op_tok
self.right_node = right_node
self.pos_start = left_node.pos_start
self.pos_end = right_node.pos_end
def __repr__(self) -> str:
return f'({self.left_node}, {self.op_tok}, {self.right_node})'
class UnaryOpNode:
def __init__(self, op_tok: Token, node) -> None:
self.op_tok = op_tok
self.node = node
self.pos_start = op_tok.pos_start
self.pos_end = node.pos_end
def __repr__(self) -> str:
return f'({self.op_tok}, {self.node})'
# LEXER
class Lexer:
def __init__(self, fn: str, text: str) -> None:
self.text = text
self.pos = Position(-1, 0, -1, fn, text)
self.current_char = None
self.advance()
def advance(self) -> None:
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def next(self, i: int = 1) -> str:
return self.text[self.pos.idx + i] if self.pos.idx + i < len(self.text) else None
def skip_comment(self):
self.advance()
while self.current_char and self.current_char not in ';\n':
self.advance()
self.advance()
def make_tokens(self) -> tuple:
tokens = []
while self.current_char:
if self.current_char in IGNORE:
self.advance()
elif self.next() and self.current_char + self.next() == "<>":
self.skip_comment()
elif self.current_char in ('"', "'"):
tokens.append(self.make_string(self.current_char))
elif self.current_char == '}':
tokens.append(Token(TT_CLOSE, pos_start=self.pos))
self.advance()
elif self.next() and self.current_char + self.next() in TOKEY:
tokens.append(Token(TOKEY[self.current_char + self.next()], pos_start=self.pos,
pos_end=self.pos.copy().advance().advance()))
self.advance(); self.advance()
elif self.current_char in TOKEY:
tokens.append(Token(TOKEY[self.current_char], pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in NUMBERS:
tokens.append(self.make_number())
elif self.current_char in ('!', '<', '>', '='):
tok, error = self.make_equals_expr()
if error: return [], error
tokens.append(tok)
else:
char, pos_start = self.current_char, self.pos.copy()
self.advance()
return [], IllegalCharError(pos_start, self.pos, f"'{char}'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self, q='"'):
string_ = ''
pos_start = self.pos.copy()
escape_character = False
self.advance()
escape_characters = {
'n': '\n',
't': '\t'
}
while self.current_char and (self.current_char != q or escape_character):
if escape_character:
string_ += escape_characters.get(self.current_char, self.current_char)
escape_character = False
elif self.current_char == '\\':
escape_character = True
else:
string_ += self.current_char
self.advance()
self.advance()
return Token(TT_STRING, string_, pos_start, self.pos)
def make_equals_expr(self):
pos_start = self.pos.copy()
char = self.current_char
self.advance()
if self.current_char == '=':
self.advance()
return Token({
'!': TT_NE,
'>': TT_GTE,
'<': TT_LTE,
'=': TT_EE
}[char], pos_start=pos_start), None
elif char == '=':
self.advance()
return None, ExpectedCharError(pos_start, self.pos,
f"'=' (after '{char}')")
else:
return Token({
'>': TT_GT,
'<': TT_LT,
'!': TT_NOT
}[char], pos_start=pos_start), None
def make_identifier(self) -> Token:
id_str = str()
pos_start = self.pos.copy()
while self.current_char and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
if id_str in ('true', 'false'):
return Token(TT_BOOL, True if id_str == 'true' else False, pos_start, self.pos)
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type, id_str, pos_start, self.pos)
def make_number(self) -> Token:
num = ''
dot_count = 0
pos_start = self.pos.copy()
while self.current_char and self.current_char in NUMDOT:
if self.current_char == '.':
if dot_count == 1: break
dot_count += 1
num += '.'
else:
num += self.current_char
self.advance()
if dot_count == 0:
return Token(TT_INT, int(num), pos_start, self.pos)
return Token(TT_FLOAT, float(num), pos_start, self.pos)
# PARSE RESULT
class ParseResult:
node = None
error: Error = None
advance_count: int = 0
to_reverse_count: int = 0
def register_advancement(self):
self.advance_count += 1
def try_register(self, res):
if res.error:
self.to_reverse_count = res.advance_count
return None
return self.register(res)
def register(self, res):
self.advance_count += res.advance_count
if res.error: self.error = res.error
return res.node
def success(self, node):
self.node = node
return self
def failure(self, error):
if not self.error or not self.advance_count:
self.error = error
return self
# PARSER
# noinspection DuplicatedCode
class Parser:
current_tok: Token
def __init__(self, tokens) -> None:
self.tokens = tokens
self.tok_idx = -1
self.tokount = len(tokens)
self.advance()
def advance(self) -> Token:
self.tok_idx += 1
self.update_tok()
return self.current_tok
def reverse(self, amount=1) -> Token:
self.tok_idx -= amount
self.update_tok()
return self.current_tok
def update_tok(self) -> None:
if 0 <= self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '+', '-', '*', '^', or '/'"
))
return res
def if_expr(self):
res = ParseResult()
all_cases = res.register(self.if_expr_cases('if'))
if res.error: return res
cases, else_case = all_cases
return res.success(QueryNode(cases, else_case))
def elif_expr(self):
return self.if_expr_cases('elif')
def else_expr(self):
res = ParseResult()
else_case = None
if self.current_tok.matches(TT_KEYWORD, 'else'):
res.register_advancement()
self.advance()
if not self.current_tok.type == TT_OPEN:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '{'"
))
res.register_advancement()
self.advance()
statements = res.register(self.statements())
if res.error: return res
else_case = (statements, True)
if not self.current_tok.type == TT_CLOSE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '}'"
))
res.register_advancement()
self.advance()
return res.success(else_case)
def elif_else(self):
res = ParseResult()
cases, else_case = [], None
if self.current_tok.matches(TT_KEYWORD, 'elif'):
all_cases = res.register(self.elif_expr())
if res.error: return res
cases, else_case = all_cases
else:
else_case = res.register(self.else_expr())
if res.error: return res
return res.success((cases, else_case))
def if_expr_cases(self, case_keyword):
res = ParseResult()
cases = []
if not self.current_tok.matches(TT_KEYWORD, case_keyword):
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
f"Expected '{case_keyword}'"
))
res.register_advancement()
self.advance()
condition = res.register(self.expr())
if res.error: return res
if not self.current_tok.type == TT_OPEN:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '{'"
))
res.register_advancement()
self.advance()
statements = res.register(self.statements())
if res.error: return res
cases.append((condition, statements, True))
if self.current_tok.type != TT_CLOSE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '}'"
))
res.register_advancement()
self.advance()
all_cases = res.register(self.elif_else())
if res.error: return res
new_cases, else_case = all_cases
cases.extend(new_cases)
return res.success((cases, else_case))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'for'):
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'for'"
))
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
'Expected identifier'
))
var_name = self.current_tok
res.register_advancement()
self.advance()
if self.current_tok.type != TT_LAMBDA:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected weak assignment ('->')"
))
res.register_advancement()
self.advance()
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.type == TT_BITE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ':'"
))
res.register_advancement()
self.advance()
end_value = res.register(self.expr())
if self.current_tok.type == TT_STEP:
res.register_advancement()
self.advance()
step_value = res.register(self.expr())
else:
step_value = None
if self.current_tok.type == TT_OPEN:
res.register_advancement()
self.advance()
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.type == TT_CLOSE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '}'"
))
res.register_advancement()
self.advance()
return res.success(ForNode(var_name, start_value, end_value, step_value, body, True))
elif self.current_tok.type == TT_EQ:
res.register_advancement()
self.advance()
body = res.register(self.statement())
if res.error: return res
return res.success(ForNode(var_name, start_value, end_value, step_value, body, False))
else:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '{' or '=>'"
))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'while'):
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'while'"
))
res.register_advancement()
self.advance()
condition = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_EQ:
res.register_advancement()
self.advance()
body = res.register(self.statement())
if res.error: return res
return res.success(WhileNode(condition, body, False))
elif self.current_tok.type == TT_OPEN:
res.register_advancement()
self.advance()
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.type == TT_CLOSE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '}'"
))
res.register_advancement()
self.advance()
return res.success(WhileNode(condition, body, True))
else:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '{' or '=>'"
))
def class_def(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'recipe'):
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'recipe'"
))
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected identifier"
))
class_name_tok = self.current_tok
res.register_advancement()
self.advance()
if self.current_tok.type != TT_OPEN:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '{'"
))
self.advance()
res.register_advancement()
attribute_declarations = []
if self.current_tok.type == TT_IDENTIFIER:
attribute_declarations.append(self.current_tok)
self.advance()
res.register_advancement()
while self.current_tok.type == TT_COMMA:
res.register_advancement()
self.advance()
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected identifier"
))
attribute_declarations.append(self.current_tok)
self.advance()
res.register_advancement()
if self.current_tok.type != TT_NEWLINE:
return res.failure(InvalidSyntax(
self.current_tok.pos_start, self.current_tok.pos_end,