-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.py
2303 lines (1976 loc) · 88.8 KB
/
parser.py
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
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Nougaro : a python-interpreted high-level programming language
# Copyright (C) 2021-2025 Jean Dubois (https://github.com/jd-develop) <[email protected]>
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# IMPORTS
# nougaro modules imports
from src.lexer.token_types import TT, TOKENS_NOT_TO_QUOTE, EQUALS
from src.errors.errors import InvalidSyntaxError, Error
from src.parser.parse_result import ParseResult
from src.lexer.token import Token
from src.parser.nodes import *
from src.lexer.position import Position
# built-in python imports
from typing import Any, Iterable, Callable
# ##########
# PARSER
# ##########
class Parser:
""" The Parser (transforms Tokens from the Lexer to Nodes for the Interpreter).
Please see grammar.txt for AST.
"""
def __init__(self, tokens: list[Token], metas: dict[str, str | bool] | None = None):
if metas is None:
metas = dict()
self.tokens = tokens # tokens from the lexer
self.metas = metas # metas from the parser
self.token_index = -1 # we start at -1, because we advance 2 lines after, so the index will be 0
self.current_token: Token | None = None # Token is imported in src.nodes
self.advance()
self.then_s: list[tuple[Position, Position]] = [] # pos start then pos end
def parse(self):
"""Parse tokens and return a result that contain a main node"""
result = self.statements()
return result
def advance(self):
"""Advance of 1 token"""
self.token_index += 1
self.update_current_token()
return self.current_token
def next_token(self):
"""Return the next token, or the current one if EOF"""
if 0 <= self.token_index + 1 < len(self.tokens):
return self.tokens[self.token_index + 1]
else:
return self.current_token
def reverse(self, amount: int = 1):
"""Advance of -1 token"""
# this is just the opposite of self.advance ^^
self.token_index -= amount
self.update_current_token()
return self.current_token
def update_current_token(self):
"""Update current token after having advanced"""
if 0 <= self.token_index < len(self.tokens): # if the index is correct
self.current_token = self.tokens[self.token_index] # we update
def advance_and_check_for(
self,
result: ParseResult,
errmsg: str,
tok_type: str,
tok_value: str | None = None,
origin_file: str = "advance_and_check_for",
pos_start: Position | None = None,
pos_end: Position | None = None,
del_a_then: bool = False
):
"""Advance, then run `self.check_for`."""
result.register_advancement()
self.advance()
return self.check_for(result, errmsg, tok_type, tok_value, origin_file, pos_start, pos_end, del_a_then)
def check_for_and_advance(
self,
result: ParseResult,
errmsg: str,
tok_type: str,
tok_value: str | None = None,
origin_file: str = "advance_and_check_for",
pos_start: Position | None = None,
pos_end: Position | None = None,
del_a_then: bool = False
):
"""Run `self.check_for`, then advance."""
result = self.check_for(result, errmsg, tok_type, tok_value, origin_file, pos_start, pos_end, del_a_then)
result.register_advancement()
self.advance()
return result
def advance_check_for_and_advance(
self,
result: ParseResult,
errmsg: str,
tok_type: str,
tok_value: str | None = None,
origin_file: str = "advance_and_check_for",
pos_start: Position | None = None,
pos_end: Position | None = None,
del_a_then: bool = False
):
"""Advance, then run `self.check_for`, and then advance."""
result.register_advancement()
self.advance()
result = self.check_for(result, errmsg, tok_type, tok_value, origin_file, pos_start, pos_end, del_a_then)
result.register_advancement()
self.advance()
return result
def check_for(
self,
result: ParseResult,
errmsg: str,
tok_type: str | list[str],
tok_value: str | None = None,
origin_file: str = "check_for",
pos_start: Position | None = None,
pos_end: Position | None = None,
del_a_then: bool = False
):
"""Check for a token of type tok_type, eventually with value tok_value. Returns the result.
* `errmsg` is the error message that should be used if the token is not found. Note that the returned error
is InvalidSyntaxError. Any occurence of the substring "%toktype%" is replaced by the current token’s type.
* if `tok_type` is a str, it checks for TT[tok_type]. If it is a list, it checks if the type of the current
token is in the list. Note that the values in the list need to be values of the TT dict, not the keys.
* `tok_value`, if given, is used in the .matches() method. It can not be a list.
* `origin_file` is used in the debug `origin_file` argument of the error. It is the name of the parser’s
method. For instance, "atom" (converted to "src.parser.parser.Parser.atom")
* `pos_start` and `pos_end` are the positions for the InvalidSyntaxError. By default (if not given or None),
pos_start and pos_end are those of the current token.
* `del_a_then`, if set to True, deletes the last element of the self.thens list.
"""
assert self.current_token is not None
if pos_start is None:
pos_start = self.current_token.pos_start
if pos_end is None:
pos_end = self.current_token.pos_end
if tok_value is None:
if isinstance(tok_type, str):
condition = self.current_token.type != TT[tok_type]
else:
condition = self.current_token.type not in tok_type
if condition:
if self.current_token.type in TOKENS_NOT_TO_QUOTE:
current_tok_type = self.current_token.type
else:
current_tok_type = f"'{self.current_token.type}'"
return result.failure(InvalidSyntaxError(
pos_start, pos_end,
errmsg.replace("%toktype%", current_tok_type),
f"src.parser.parser.Parser.{origin_file}"
))
else:
if isinstance(tok_type, list):
raise ValueError("please don’t use tok type lists AND tok values.")
if not self.current_token.matches(TT[tok_type], tok_value):
if self.current_token.type in TOKENS_NOT_TO_QUOTE:
current_tok_type = self.current_token.type
else:
current_tok_type = f"'{self.current_token.type}'"
return result.failure(InvalidSyntaxError(
pos_start, pos_end,
errmsg.replace("%toktype%", current_tok_type),
f"src.parser.parser.Parser.{origin_file}"
))
if del_a_then:
del self.then_s[-1]
return result
# GRAMMARS ATOMS (AST) :
def statements(self, stop: list[tuple[Any, str] | str] | None = None) -> ParseResult:
"""
statements : NEWLINE* statement (NEWLINE+ statement)* NEWLINE
The returned node in the parse result is ALWAYS a ListNode here.
If stop is not specified or None, stop is [TT["EOF"]]"""
assert self.current_token is not None
if stop is None:
stop = [TT["EOF"]] # token(s) that stops parser in this function
result = ParseResult() # we create the result
statements: list[tuple[Node, bool]] = [] # list of statements
pos_start = self.current_token.pos_start.copy() # pos_start
# NEWLINE*
while self.current_token.type == TT["NEWLINE"]: # skip new lines
result.register_advancement()
self.advance()
if self.current_token.type == TT["EOF"]: # End Of File -> nothing to parse!
return result.success(NoNode())
last_token_type = self.current_token.type
# statement
statement = result.register(self.statement()) # we register a statement
if result.error is not None: # we check for errors
return result
assert statement is not None
assert not isinstance(statement, list)
statements.append((statement, False)) # we append the statement to our list of there is no error
# (NEWLINE+ statement)*
while True: # 'break' inside the loop
newline_count = 0
while self.current_token.type == TT["NEWLINE"]: # skip new lines
result.register_advancement()
self.advance()
newline_count += 1
# we check if we have to stop parsing
# in stop there can be tok types or tuples like (tok_type, tok_value)
# I made a HUGE optimization here: there was a 'for' loop (git blame for date)
if self.current_token.type in stop or (self.current_token.type, self.current_token.value) in stop:
break
if newline_count == 0: # there was no new line between the last statement and this one: unexpected
if self.current_token.type in TOKENS_NOT_TO_QUOTE:
quote = ""
else:
quote = "'"
# token
last_tok_is_identifier = last_token_type == TT["IDENTIFIER"]
current_tok_is_equal = self.current_token.type in \
EQUALS + [TT["INCREMENT"], TT["DECREMENT"]]
missing_var_error_message = False
if last_tok_is_identifier and current_tok_is_equal:
# there was no new line but there is 'id =' (need 'var')
missing_var_error_message = True
elif last_token_type == TT["IDENTIFIER"] and self.current_token.type == TT["COMMA"]:
result.register_advancement()
self.advance()
missing_var = True
while self.current_token.type == TT["IDENTIFIER"]:
result.register_advancement()
self.advance()
if self.current_token.type in EQUALS:
break # missing_var is already True
if not (self.current_token.type == TT["COMMA"] or self.current_token.type in EQUALS):
missing_var = False
break
result.register_advancement()
self.advance()
if missing_var and self.current_token.type in EQUALS:
# there was no new line but there is 'id1, id2, ... =' (need 'var')
missing_var_error_message = True
error_msg = f"unexpected token: {quote}{self.current_token}{quote}."
if missing_var_error_message:
error_msg += " To declare or update a variable, use 'var' "\
"keyword."
return result.failure(InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end,
error_msg,
"src.parser.parser.Parser.statements"
))
if self.current_token.type == TT["EOF"] and len(self.then_s) != 0:
return result.failure(InvalidSyntaxError(
self.then_s[-1][0], self.then_s[-1][1],
"expected 'end' to close a statement, surely this one.",
"src.parser.parser.Parser.statements"
))
# we replace the last token type
last_token_type = self.current_token.type
# we register a statement, check for errors and append the statement if all is OK
# statement
statement = result.register(self.statement())
if result.error is not None:
return result
assert statement is not None
assert not isinstance(statement, list)
statements.append((statement, False))
return result.success(ListNode( # we put all the nodes parsed here into a ListNode
statements,
pos_start,
self.current_token.pos_end.copy()
))
def statement(self) -> ParseResult: # only one statement
"""
statement : KEYWORD:RETURN expr?
: KEYWORD:IMPORT IDENTIFIER (DOT IDENTIFIER)?* (KEYWORD:AS IDENTIFIER)?
: KEYWORD:EXPORT expr AS IDENTIFIER
: KEYWORD:EXPORT IDENTIFIER (KEYWORD:AS IDENTIFIER)?
: KEYWORD:CONTINUE (COLON IDENTIFIER)?
: KEYWORD:BREAK (COLON IDENTIFIER)? (KEYWORD:AND KEYWORD:RETURN expr)?
: expr
"""
# we create the result and get the pos start from the current token
result = ParseResult()
assert self.current_token is not None
pos_start = self.current_token.pos_start.copy()
# we check for tokens
# KEYWORD:RETURN expr?
if self.current_token.matches(TT["KEYWORD"], 'return'):
result.register_advancement()
self.advance()
# expr?
expr = result.try_register(self.expr()) # we try to register an expression
if expr is None: # there is no expr : we reverse
self.reverse(result.to_reverse_count)
# assert expr is not None
assert not isinstance(expr, list)
return result.success(ReturnNode(expr, pos_start, self.current_token.pos_start.copy()))
# KEYWORD:IMPORT IDENTIFIER
if self.current_token.matches(TT["KEYWORD"], 'import'):
result = self.advance_and_check_for(result, "expected identifier after 'import'.",
"IDENTIFIER", origin_file="statement")
if result.error is not None:
return result
identifiers = [self.current_token]
result.register_advancement()
self.advance()
while self.current_token.type == TT["DOT"]:
result = self.advance_and_check_for(result, "expected identifier after 'import'.",
"IDENTIFIER", origin_file="statement")
if result.error is not None:
return result
identifiers.append(self.current_token)
result.register_advancement()
self.advance()
as_identifier = None
if self.current_token.matches(TT["KEYWORD"], "as"):
result = self.advance_and_check_for(result, "expected identifier after 'as'.",
"IDENTIFIER", origin_file="statement")
if result.error is not None:
return result
as_identifier = self.current_token
result.register_advancement()
self.advance()
return result.success(ImportNode(
identifiers, pos_start, self.current_token.pos_start.copy(), as_identifier
))
if self.current_token.matches(TT["KEYWORD"], 'export'):
# we advance
result.register_advancement()
self.advance()
is_identifier = self.current_token.type == TT["IDENTIFIER"]
next_tok = self.next_token()
assert next_tok is not None
next_is_as_or_newline = next_tok.matches(TT["KEYWORD"], 'as') or next_tok.type in [TT["NEWLINE"], TT["EOF"]]
if is_identifier and next_is_as_or_newline:
expr_or_identifier = self.current_token
as_required = False
result.register_advancement()
self.advance()
else:
# we register an expr
expr_or_identifier = result.register(self.expr())
if result.error is not None:
return result
assert expr_or_identifier is not None
as_required = True
current_tok_is_as = self.current_token.matches(TT["KEYWORD"], "as")
if as_required and not current_tok_is_as:
return result.failure(InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end,
"expected keyword 'as'.",
"src.parser.parser.Parser.statement"
))
if current_tok_is_as:
result = self.advance_and_check_for(result, "expected identifier after 'as'.",
"IDENTIFIER", origin_file="statement")
if result.error is not None:
return result
as_identifier = self.current_token
result.register_advancement()
self.advance()
else:
as_identifier = None
assert not isinstance(expr_or_identifier, list)
return result.success(
ExportNode(expr_or_identifier, as_identifier, pos_start, self.current_token.pos_start.copy())
)
# KEYWORD:CONTINUE
if self.current_token.matches(TT["KEYWORD"], 'continue'):
result.register_advancement()
self.advance()
label = None
if self.current_token.type == TT["COLON"]:
result = self.advance_and_check_for(
result, "expected label identifier after ':'.", "IDENTIFIER",
origin_file="statement"
)
if result.error is not None:
return result
label = self.current_token.value
assert isinstance(label, str)
result.register_advancement()
self.advance()
return result.success(ContinueNode(pos_start, self.current_token.pos_start.copy(), label))
# KEYWORD:BREAK
if self.current_token.matches(TT["KEYWORD"], 'break'):
result.register_advancement()
self.advance()
label = None
if self.current_token.type == TT["COLON"]:
result = self.advance_and_check_for(
result, "expected label identifier after ':'.", "IDENTIFIER",
origin_file="statement"
)
if result.error is not None:
return result
label = self.current_token.value
assert isinstance(label, str)
result.register_advancement()
self.advance()
expr_to_return = None
if self.current_token.matches(TT["KEYWORD"], "and"):
result = self.advance_check_for_and_advance(
result, "expected keyword “return” after “and”.", "KEYWORD",
"return", "statement"
)
if result.error is not None:
return result
expr_to_return = result.register(self.expr())
if result.error is not None:
return result
return result.success(
BreakNode(pos_start, self.current_token.pos_start.copy(), expr_to_return, label)
)
# expr
expr = result.register(self.expr())
if result.error is not None:
return result
assert expr is not None
return result.success(expr)
def expr(self) -> ParseResult:
"""
expr : var_assign
: KEYWORD:DEL IDENTIFIER
: KEYWORD:WRITE expr (TO|TO_AND_OVERWRITE) expr INT?
: KEYWORD:READ expr (TO IDENTIFIER)? INT?
: KEYWORD:ASSERT expr (COMMA expr)?
: comp_expr ((KEYWORD:AND|KEYWORD:OR|KEYWORD:XOR|BITWISEAND|BITWISEOR|BITWISEXOR) comp_expr)*
"""
# we create the result and the pos start
result = ParseResult()
assert self.current_token is not None
pos_start = self.current_token.pos_start.copy()
# var_assign
if self.current_token.matches(TT["KEYWORD"], 'var'):
var_assign_node = result.register(self.var_assign())
if result.error is not None:
return result
assert var_assign_node is not None
return result.success(var_assign_node)
# KEYWORD:DEL IDENTIFIER
if self.current_token.matches(TT["KEYWORD"], 'del'):
return self.var_delete()
# KEYWORD:WRITE expr (TO|TO_AND_OVERWRITE) expr INT?
if self.current_token.matches(TT["KEYWORD"], 'write'):
return self.write_expr(pos_start)
# KEYWORD:READ expr (TO IDENTIFIER)? INT?
if self.current_token.matches(TT["KEYWORD"], 'read'):
return self.read_expr(pos_start)
# KEYWORD:ASSERT expr (COMMA expr)?
if self.current_token.matches(TT["KEYWORD"], "assert"):
return self.assert_expr(pos_start)
if self.current_token.matches(TT["KEYWORD"], "end"):
if len(self.then_s) == 0:
return result.failure(InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end,
"didn't expect 'end', because there is nothing to close.",
"src.parser.parser.Parser.expr"
))
# comp_expr ((KEYWORD:AND|KEYWORD:OR|KEYWORD:XOR|BITWISEAND|BITWISEOR|BITWISEXOR) comp_expr)*
node = result.register(self.bin_op(self.comp_expr,
(
(TT["KEYWORD"], "and"),
(TT["KEYWORD"], "or"),
(TT["KEYWORD"], 'xor'),
TT["BITWISEAND"],
TT["BITWISEOR"],
TT["BITWISEXOR"]
)
))
if result.error is not None:
return result
assert node is not None
return result.success(node)
def var_delete(self) -> ParseResult:
# todo: accept attributes
result = ParseResult()
result.register_advancement()
self.advance()
assert self.current_token is not None
# if the current tok is not an identifier, return an error
if self.current_token.type != TT["IDENTIFIER"]:
if self.current_token.type == TT["KEYWORD"]:
error_msg = "using a keyword as idendifier is illegal."
elif self.current_token.type in TOKENS_NOT_TO_QUOTE:
error_msg = f"expected identifier, but got {self.current_token.type}."
else:
error_msg = f"expected identifier, but got '{self.current_token.type}'."
return result.failure(InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end, error_msg,
"src.parser.parser.Parser.var_delete"
))
# we assign the identifier to a variable then we advance
var_name = self.current_token
result.register_advancement()
self.advance()
if result.error is not None:
return result
return result.success(VarDeleteNode(var_name))
def write_expr(self, pos_start: Position) -> ParseResult:
result = ParseResult()
result.register_advancement()
self.advance()
assert self.current_token is not None
# we check for an expr
expr_to_write = result.register(self.expr())
if result.error is not None:
return result
assert expr_to_write is not None
# (TO|TO_AND_OVERWRITE)
result = self.check_for(
result,
"'>>' or '!>>' is missing. The correct syntax is 'write <expr> >> <expr>' or "
"'write <expr> !>> <expr>' to override.",
[TT["TO"], TT["TO_AND_OVERWRITE"]], None, "write_expr"
)
if result.error is not None:
return result
to_token = self.current_token
result.register_advancement()
self.advance()
# we check for an expr
file_name_expr = result.register(self.expr())
if result.error is not None:
return result
assert file_name_expr is not None
# We check if there is an 'int' token. If not, we will return the default value
if self.current_token.type == TT["INT"]:
line_number = self.current_token.value
assert isinstance(line_number, int)
result.register_advancement()
self.advance()
else:
line_number = 'last'
assert not isinstance(expr_to_write, list)
assert not isinstance(file_name_expr, list)
return result.success(WriteNode(
expr_to_write, file_name_expr, to_token, line_number,
pos_start, self.current_token.pos_start.copy()
))
def read_expr(self, pos_start: Position) -> ParseResult:
result = ParseResult()
assert self.current_token is not None
result.register_advancement()
self.advance()
# we check for an expr
file_name_expr = result.register(self.expr())
if result.error is not None:
return result
assert file_name_expr is not None
identifier = None
# (TO IDENTIFIER)?
if self.current_token.type == TT["TO"]:
result = self.advance_and_check_for(
result, f"expected identifier, got {self.current_token.type}.",
"IDENTIFIER", None, "read_expr"
)
if result.error is not None:
return result
identifier = self.current_token
result.register_advancement()
self.advance()
# INT?
if self.current_token.type == TT["INT"]:
line_number = self.current_token.value
assert isinstance(line_number, int)
result.register_advancement()
self.advance()
else:
line_number = 'all'
assert not isinstance(file_name_expr, list)
return result.success(ReadNode(
file_name_expr, identifier, line_number,
pos_start, self.current_token.pos_start.copy()
))
def assert_expr(self, pos_start: Position) -> ParseResult:
result = ParseResult()
result.register_advancement()
self.advance()
assert self.current_token is not None
# we check for expr
assertion = result.register(self.expr())
if result.error is not None:
return result
assert assertion is not None
# we check for comma
if self.current_token.type == TT["COMMA"]:
# register an error message to print if the assertion is false.
# if there is no comma, there is no error message
result.register_advancement()
self.advance()
# we check for an expr
errmsg = result.register(self.expr())
if result.error is not None:
return result
assert not isinstance(assertion, list)
assert not isinstance(errmsg, list)
return result.success(AssertNode(
assertion, pos_start, self.current_token.pos_start.copy(),
errmsg=errmsg
))
assert not isinstance(assertion, list)
return result.success(AssertNode(assertion, pos_start, self.current_token.pos_start.copy()))
def var_assign(self) -> ParseResult:
"""
var_assign : KEYWORD:VAR assign_id (COMMA assign_id)?* assign_eq assign_expr
: KEYWORD:VAR assign_id (INCREMENT|DECREMENT)
"""
result = ParseResult()
assert self.current_token is not None
pos_start = self.current_token.pos_start.copy()
result = self.check_for_and_advance(
result, "expected 'var' keyboard.", "KEYWORD", "var", "var_assign"
)
if result.error is not None:
return result
all_names_list: list[list[Node | Token]] = []
while self.current_token.type not in EQUALS:
# if current token is not identifier we have to register expr
result = self.check_for(result, "expected identifier.", "IDENTIFIER", None, "var_assign")
if result.error is not None:
return result
current_name_nodes_and_tokens_list, error = self.assign_identifier()
if error is not None:
return result.failure(error)
assert current_name_nodes_and_tokens_list is not None
all_names_list.append(current_name_nodes_and_tokens_list)
if self.current_token.type != TT["COMMA"]:
break
else:
result.register_advancement()
self.advance()
if len(all_names_list) == 0:
return result.failure(InvalidSyntaxError(
pos_start, self.current_token.pos_start,
"expected at least one identifier.",
origin_file="src.parser.parser.Parser.var_assign"
))
equal = self.current_token
if equal.type in [TT["INCREMENT"], TT["DECREMENT"]]:
result.register_advancement()
self.advance()
return result.success(VarAssignNode(all_names_list, None, equal))
elif equal.type not in EQUALS:
if self.current_token.type in [TT["EE"], TT["GT"], TT["LT"], TT["GTE"], TT["LTE"], TT["NE"]]:
error_msg = f"expected an assignation equal, but got a test equal ('{self.current_token.type}')."
elif self.current_token.type in TOKENS_NOT_TO_QUOTE:
error_msg = f"expected an equal, but got {self.current_token.type}."
else:
error_msg = f"expected an equal, but got '{self.current_token.type}'."
return result.failure(InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end, error_msg,
"src.parser.parser.Parser.expr"
))
result.register_advancement()
self.advance()
# expr (COMMA expr)?*
# we register an expr
first_node = result.register(self.expr())
if result.error is not None:
return result
assert first_node is not None
assert not isinstance(first_node, list)
expressions = [first_node]
while self.current_token.type == TT["COMMA"]: # (COMMA expr)?*
result.register_advancement()
self.advance()
node = result.register(self.expr())
if result.error is not None:
return result
assert node is not None
assert not isinstance(node, list)
expressions.append(node)
return result.success(VarAssignNode(all_names_list, expressions, equal))
def assign_identifier(self) -> tuple[list[Node | Token], None] | tuple[None, Error]:
"""
assign_id : (IDENTIFIER (LPAREN NEWLINE?* (MUL? expr (COMMA NEWLINE?* MUL? expr)?*)? NEWLINE?* RPAREN)?* DOT)?* IDENTIFIER
"""
result = ParseResult()
current_name_nodes_and_tokens_list: list[Node | Token] = []
identifier_expected = False
is_attr = False
assert self.current_token is not None
while self.current_token.type == TT["IDENTIFIER"]:
identifier_expected = False
identifier = self.current_token
result.register_advancement()
self.advance()
call_node = identifier
call_node_node = VarAccessNode([identifier], is_attr)
is_call = self.current_token.type == TT["LPAREN"]
while self.current_token.type == TT["LPAREN"]:
result.register_advancement()
self.advance()
arg_nodes: list[tuple[Node, bool]] = []
cur_tok = self.current_token
while cur_tok is not None and cur_tok.type == TT["NEWLINE"]:
result.register_advancement()
cur_tok = self.advance()
comma_expected = False
mul = False
# we check for the closing paren.
if self.current_token.type == TT["RPAREN"]:
pos_end = self.current_token.pos_end.copy()
result.register_advancement()
self.advance()
call_node_node = CallNode(call_node_node, arg_nodes, pos_end)
continue
# (MUL? expr (COMMA MUL? expr)?*)?
if self.current_token.type == TT["MUL"]: # MUL?
mul = True
# we advance
result.register_advancement()
self.advance()
# expr
expr_node = result.register(self.expr())
if result.error is not None:
return None, result.error
assert expr_node is not None
assert not isinstance(expr_node, list)
arg_nodes.append((expr_node, mul))
while self.current_token.type == TT["COMMA"]: # (COMMA MUL? expr)?*
mul = False
# we advance
result.register_advancement()
self.advance()
cur_tok = self.current_token
while cur_tok is not None and cur_tok.type == TT["NEWLINE"]:
result.register_advancement()
cur_tok = self.advance()
if self.current_token.type == TT["MUL"]: # MUL?
mul = True
# we advance
result.register_advancement()
self.advance()
# expr
# we register an expr then check for an error
expr_node = result.register(self.expr())
if result.error is not None:
# type ignore is required because type checking strict is DUMB
return None, result.error # type: ignore
assert expr_node is not None
assert not isinstance(expr_node, list)
arg_nodes.append((expr_node, mul))
cur_tok = self.current_token
while cur_tok is not None and cur_tok.type == TT["NEWLINE"]:
result.register_advancement()
cur_tok = self.advance()
pos_end = self.current_token.pos_end.copy()
result = self.check_for_and_advance(
result, "expected ',' or ')'." if comma_expected else "expected ')'.",
"RPAREN", None, "assign_identifier"
)
if result.error is not None:
return None, result.error
call_node_node = CallNode(call_node_node, arg_nodes, pos_end)
if is_call:
call_node = call_node_node
if self.current_token.type == TT["DOT"]:
is_attr = True
current_name_nodes_and_tokens_list.append(call_node) # call_node can be identifier token
result.register_advancement()
self.advance()
identifier_expected = True
elif is_call:
return None, InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end,
"expected dot.",
origin_file="src.parser.parser.Parser.assign_identifier"
)
else:
current_name_nodes_and_tokens_list.append(call_node)
break
if identifier_expected:
return None, InvalidSyntaxError(
self.current_token.pos_start, self.current_token.pos_end,
"expected identifier after dot.",
origin_file="src.parser.parser.Parser.assign_identifier"
)
return current_name_nodes_and_tokens_list, None
def comp_expr(self) -> ParseResult:
"""
comp_expr : (KEYWORD:NOT|BITWISENOT) comp_expr
: arith_expr ((EE|LT|GT|LTE|GTE|KEYWORD:IN) arith_expr)*
"""
# we create a result
result = ParseResult()
assert self.current_token is not None
# (KEYWORD:NOT|BITWISENOT) comp_expr
is_not_keyword = self.current_token.matches(TT["KEYWORD"], 'not')
is_bitwise_not = self.current_token.type == TT["BITWISENOT"]
if is_not_keyword or is_bitwise_not:
op_token = self.current_token
result.register_advancement()
self.advance()
# we check for comp_expr
node = result.register(self.comp_expr())
if result.error is not None:
return result
assert node is not None
return result.success(UnaryOpNode(op_token, node))
# arith_expr ((EE|LT|GT|LTE|GTE|KEYWORD:IN) arith_expr)*
node = result.register(
self.bin_op(self.arith_expr, (
TT["EE"],
TT["NE"],
TT["LT"],
TT["GT"],
TT["LTE"],
TT["GTE"],
(TT["KEYWORD"], "in")
), left_has_priority=False)
)
if result.error is not None:
return result
assert node is not None
return result.success(node)
def arith_expr(self) -> ParseResult:
"""
arith_expr : term ((PLUS|MINUS) term)*
"""
# term ((PLUS|MINUS) term)*
return self.bin_op(self.term, (TT["PLUS"], TT["MINUS"]))
def term(self) -> ParseResult:
"""
term : factor ((MUL|DIV|PERC|FLOORDIV) factor)*
"""
# factor ((MUL|DIV|PERC|FLOORDIV) factor)*
return self.bin_op(self.factor, (TT["MUL"], TT["DIV"], TT["PERC"], TT["FLOORDIV"]))
def factor(self) -> ParseResult:
"""
factor : (PLUS|MINUS) factor
: power
"""
result = ParseResult()
token = self.current_token
assert token is not None
# (PLUS|MINUS) factor
if token.type in (TT["PLUS"], TT["MINUS"]):
result.register_advancement()
self.advance()
# we check for factor
factor = result.register(self.factor())
if result.error is not None:
return result
assert factor is not None
return result.success(UnaryOpNode(token, factor))
elif token.type == TT["LEGACYABS"]:
pos = (token.pos_start, token.pos_end)
result.register_advancement()
self.advance()
# we check for factor
factor = result.register(self.factor())
if result.error is not None:
return result
assert factor is not None
result = self.check_for_and_advance(
result,
"this '|' (absolute value) was never closed, or an invalid expression was given.",
"LEGACYABS", None, "factor", *pos
)
return result.success(AbsNode(factor))
# power
return self.power()
def power(self) -> ParseResult:
"""
power : call (DOT call)?* (POW factor)*