-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.py
2041 lines (1834 loc) · 97.7 KB
/
interpreter.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-2024 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.errors.errors import RunTimeError, RTNotDefinedError, RTTypeError, RTAttributeError, InvalidSyntaxError
from src.errors.errors import RTAssertionError, RTIndexError, RTFileNotFoundError, RTRecursionError
from src.lexer.token_types import TT, TOKENS_NOT_TO_QUOTE
from src.lexer.token import Token
from src.lexer.position import Position, DEFAULT_POSITION
from src.parser.nodes import *
from src.runtime.values.basevalues.basevalues import Number, String, List, NoneValue, Value, Module, Constructor
from src.runtime.values.basevalues.basevalues import Object, DefaultValue
from src.runtime.values.functions.function import Function, Method
from src.runtime.values.functions.base_function import BaseFunction
from src.runtime.runtime_result import RTResult
from src.runtime.context import Context
from src.runtime.symbol_table import SymbolTable
from src.misc import clear_screen, RunFunction, print_in_red
from src.noug_version import LIB_VERSION
import src.conffiles
# built-in python imports
from inspect import signature
from collections import Counter
import os.path
import importlib
import pprint
_ORIGIN_FILE = "src.runtime.interpreter.Interpreter"
# ##########
# INTERPRETER
# ##########
# noinspection PyPep8Naming
class Interpreter:
def __init__(self, run: RunFunction, noug_dir_: str, args: list[String], work_dir: str,
lexer_metas: dict[str, str | bool], file_name: str = ""):
debug = src.conffiles.access_data("debug")
if debug is None:
debug = 0
self.debug = bool(int(debug))
self.run = run
self.noug_dir = noug_dir_
self.args = args
self.work_dir = work_dir
self.file_name = file_name
self.lexer_metas = lexer_metas
self._methods = None
self.init_methods()
assert self._methods is not None
def init_methods(self):
self._methods = {
"AbsNode": self.visit_AbsNode,
"AssertNode": self.visit_AssertNode,
"BinOpCompNode": self.visit_BinOpCompNode,
"BinOpNode": self.visit_BinOpNode,
"BreakNode": self.visit_BreakNode,
"CallNode": self.visit_CallNode,
"ClassNode": self.visit_ClassNode,
"ContinueNode": self.visit_ContinueNode,
"DefaultNode": self.visit_DefaultNode,
"DoWhileNode": self.visit_DoWhileNode,
"DollarPrintNode": self.visit_DollarPrintNode,
"ExportNode": self.visit_ExportNode,
"ForNode": self.visit_ForNode,
"ForNodeList": self.visit_ForNodeList,
"FuncDefNode": self.visit_FuncDefNode,
"IfNode": self.visit_IfNode,
"ImportNode": self.visit_ImportNode,
"ListNode": self.visit_ListNode,
"LoopNode": self.visit_LoopNode,
"NoNode": self.visit_NoNode,
"NumberENumberNode": self.visit_NumberENumberNode,
"NumberNode": self.visit_NumberNode,
"ReadNode": self.visit_ReadNode,
"ReturnNode": self.visit_ReturnNode,
"StringNode": self.visit_StringNode,
"UnaryOpNode": self.visit_UnaryOpNode,
"VarAccessNode": self.visit_VarAccessNode,
"VarAssignNode": self.visit_VarAssignNode,
"VarDeleteNode": self.visit_VarDeleteNode,
"WhileNode": self.visit_WhileNode,
"WriteNode": self.visit_WriteNode
}
@staticmethod
def update_symbol_table(ctx: Context):
assert ctx.symbol_table is not None
symbols_copy: dict[str, Value] = ctx.symbol_table.symbols.copy()
if '__symbol_table__' in symbols_copy.keys():
del symbols_copy['__symbol_table__']
ctx.symbol_table.set(
'__symbol_table__',
String(pprint.pformat(symbols_copy), DEFAULT_POSITION.copy(), DEFAULT_POSITION.copy())
)
def visit(self, node: Node, ctx: Context, methods_instead_of_funcs: bool, other_ctx: Context | None = None,
main_visit: bool = False) -> RTResult:
"""Visit a node."""
method_name = f'{type(node).__name__}'
assert self._methods is not None
method = self._methods.get(method_name, self.no_visit_method)
if other_ctx is None:
other_ctx = ctx.copy()
PARAMETERS = signature(method).parameters
match len(PARAMETERS):
# un-comment if you add some static methods without any parameters
# case 0: # def method(self) is 1 param, def staticmethod() is 0 param
# result = method() # type: ignore
case 1: # def method(self) is 1 param, def staticmethod() is 0 param
result = method(node) # type: ignore
case 3:
result = method(node, ctx, methods_instead_of_funcs=methods_instead_of_funcs) # type: ignore
case 4:
result = method(node, ctx, other_ctx, methods_instead_of_funcs=methods_instead_of_funcs) # type: ignore
case _:
result = method(node, ctx) # type: ignore
if main_visit:
if result.loop_should_break:
assert result.break_or_continue_pos is not None
errmsg_label = ""
if result.break_label is not None:
errmsg_label = f" Maybe you forgot to create a loop labelled '{result.break_label}'?"
return result.failure(RunTimeError(
result.break_or_continue_pos[0], result.break_or_continue_pos[1],
f"'break' outside of a loop.{errmsg_label}", ctx,
origin_file=f"{_ORIGIN_FILE}.visit"
))
if result.loop_should_continue:
assert result.break_or_continue_pos is not None
errmsg_label = ""
if result.continue_label is not None:
errmsg_label = f" Maybe you forgot to create a loop labelled '{result.continue_label}'?"
return result.failure(RunTimeError(
result.break_or_continue_pos[0], result.break_or_continue_pos[1],
f"'continue' outside of a loop.{errmsg_label}", ctx,
origin_file=f"{_ORIGIN_FILE}.visit"
))
if result.function_return_value is not None:
assert result.return_pos is not None
return result.failure(RunTimeError(
result.return_pos[0], result.return_pos[1],
"'return' outside of a function.", ctx,
origin_file=f"{_ORIGIN_FILE}.visit"
))
return result
def _undefined(
self,
pos_start: Position,
pos_end: Position,
var_name: str,
ctx: Context,
result: RTResult,
origin_file: str = f"{_ORIGIN_FILE}._undefined",
edit: bool = False
) -> RTResult:
"""Returns a RTNotDefinedError with a proper message.
Note: `edit` parameter is used when the user wants to edit an undefined variable"""
assert ctx.symbol_table is not None
close_match_in_symbol_table = ctx.symbol_table.best_match(var_name)
IS_NOUGARO_LIB = os.path.exists(os.path.abspath(self.noug_dir + f"/lib_/{var_name}.noug"))
IS_PYTHON_LIB = os.path.exists(os.path.abspath(self.noug_dir + f"/lib_/{var_name}_.py"))
if edit:
err_msg = f"name '{var_name}' is not defined or is not editable in current scope."
else:
err_msg = f"name '{var_name}' is not defined."
if IS_NOUGARO_LIB or IS_PYTHON_LIB:
if ctx.symbol_table.exists(f'__{var_name}__'):
# e.g. user entered `var foo += 1` instead of `var __foo__ += 1`
return result.failure(RTNotDefinedError(
pos_start, pos_end,
f"{err_msg} Maybe you forgot to import it? Or maybe you did mean '__{var_name}__'?",
ctx, origin_file + " (is lib and __var_name__ exists)"
))
elif close_match_in_symbol_table is not None:
return result.failure(RTNotDefinedError(
pos_start, pos_end,
f"{err_msg} Maybe you forgot to import it? Or maybe you did mean '{close_match_in_symbol_table}'?",
ctx, origin_file + " (is lib and close match in symbol table)"
))
return result.failure(RTNotDefinedError(
pos_start, pos_end,
f"{err_msg} Maybe you forgot to import it?",
ctx, origin_file + " (is lib and no other match)"
))
elif ctx.symbol_table.exists(f'__{var_name}__'):
# e.g. user entered `var foo += 1` instead of `var __foo__ += 1`
return result.failure(RTNotDefinedError(
pos_start, pos_end,
f"{err_msg} Did you mean '__{var_name}__'?",
ctx, origin_file + " (is NOT lib and __var_name__ exists)"
))
elif close_match_in_symbol_table is not None:
return result.failure(RTNotDefinedError(
pos_start, pos_end,
f"{err_msg} Did you mean '{close_match_in_symbol_table}'?",
ctx, origin_file + " (is NOT lib and close match in symbol table)"
))
else:
return result.failure(RTNotDefinedError(
pos_start, pos_end,
err_msg,
ctx, origin_file + " (is NOT lib and no other match)"
))
def _visit_value_that_can_have_attributes(
self, node_or_list: Node | list[Node], result: RTResult, context: Context,
methods_instead_of_funcs: bool
) -> RTResult | Value:
"""If node_or_list is Node, visit is and return it. If it is a list, visit the value and its attributes."""
if not isinstance(node_or_list, list):
value = result.register(self.visit(node_or_list, context, methods_instead_of_funcs))
if result.should_return() or value is None: # check for errors
return result
else: # attributes
value = result.register(self.visit(node_or_list[0], context, methods_instead_of_funcs))
if result.should_return() or value is None: # check for errors
return result
if len(node_or_list) != 1:
for node_ in node_or_list[1:]:
new_ctx = Context(
display_name=f"attribute of {repr(value)}",
entry_pos=node_.pos_start,
parent=context,
value_im_attribute_of=repr(value)
)
new_ctx.symbol_table = SymbolTable()
new_ctx.symbol_table.set_whole_table(value.attributes)
new_ctx.symbol_table.parent = context.symbol_table
if not (isinstance(node_, VarAccessNode) or isinstance(node_, CallNode)):
return result.failure(RunTimeError(
node_.pos_start, node_.pos_end,
f"unexpected node: {node_.__class__.__name__}.",
context,
origin_file=f"{_ORIGIN_FILE}._visit_value_that_can_have_attributes"
))
node_.attr = True
attr_ = result.register(self.visit(node_, new_ctx, methods_instead_of_funcs, other_ctx=context))
if result.should_return() or attr_ is None:
return result
value = attr_
return value
@staticmethod
def no_visit_method(node: Node, ctx: Context):
"""The method visit_FooNode (with FooNode given in self.visit) does not exist."""
print(ctx)
print(f"NOUGARO INTERNAL ERROR: No visit_{type(node).__name__} method defined in {_ORIGIN_FILE}.\n"
f"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with all informations "
f"above.")
raise Exception(f'No visit_{type(node).__name__} method defined in {_ORIGIN_FILE}.')
@staticmethod
def visit_NumberNode(node: NumberNode, ctx: Context) -> RTResult:
"""Visit NumberNode."""
assert node.token.value is not None
assert not isinstance(node.token.value, str)
return RTResult().success(
Number(node.token.value, node.pos_start, node.pos_end).set_context(ctx)
)
@staticmethod
def visit_NumberENumberNode(node: NumberENumberNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit NumberENumberNode."""
assert node.exponent_token.value is not None
assert not isinstance(node.exponent_token.value, str)
assert node.num_token.value is not None
assert not isinstance(node.num_token.value, str)
value = node.num_token.value * (10 ** node.exponent_token.value)
if isinstance(value, int) or isinstance(value, float):
return RTResult().success(
Number(value, node.pos_start, node.pos_end).set_context(ctx)
)
else:
print(ctx)
print(f"NOUGARO INTERNAL ERROR: in visit_NumberENumberNode method defined in {_ORIGIN_FILE},\n"
f"{value=}, {methods_instead_of_funcs=}\n"
f"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with all "
f"informations above.")
raise Exception(f'{value=} in {_ORIGIN_FILE}.visit_NumberENumberNode.')
@staticmethod
def visit_StringNode(node: StringNode, ctx: Context) -> RTResult:
"""Visit StringNode"""
assert isinstance(node.token.value, str)
return RTResult().success(
String(node.token.value, node.pos_start, node.pos_end).set_context(ctx)
)
def visit_AbsNode(self, node: AbsNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit AbsNode"""
result = RTResult()
node_to_abs = node.node_to_abs
if isinstance(node_to_abs, list):
if len(node_to_abs) == 1:
value_to_abs = result.register(self.visit(node_to_abs[0], ctx, methods_instead_of_funcs))
else:
print(ctx)
print(
f"NOUGARO INTERNAL ERROR: len(node.node) != 1 in {_ORIGIN_FILE}.visit_AbsNode.\n"
f"{node_to_abs=}, {methods_instead_of_funcs=}\n"
f"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with the "
f"information above.")
raise Exception(f"len(node.node) != 1 in {_ORIGIN_FILE}.visit_AbsNode.")
else:
value_to_abs = result.register(self.visit(node_to_abs, ctx, methods_instead_of_funcs))
if result.should_return():
return result
if not isinstance(value_to_abs, Number):
assert value_to_abs is not None
return result.failure(RTTypeError(
value_to_abs.pos_start, value_to_abs.pos_end,
f"expected number, got {value_to_abs.type_}.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_AbsNode"
))
new_value = value_to_abs.copy()
new_value.value = abs(new_value.value)
return result.success(new_value.set_context(ctx).set_pos(node.pos_start, node.pos_end))
def visit_ListNode(self, node: ListNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit ListNode"""
result = RTResult()
elements: list[Value] = []
for element_node, mul in node.element_nodes: # we visit every node from the list
if not mul:
value = result.register(self.visit(element_node, ctx, methods_instead_of_funcs))
if result.should_return() or value is None: # if there is an error
return result
elements.append(value)
else:
extend_list_: Value | None = result.register(self.visit(element_node, ctx, methods_instead_of_funcs))
if result.should_return() or extend_list_ is None: # if there is an error
return result
if not isinstance(extend_list_, List):
return result.failure(RTTypeError(
extend_list_.pos_start, extend_list_.pos_end,
f"expected a list value after '*', but got {extend_list_.type_}.",
ctx,
origin_file=f"{_ORIGIN_FILE}.visit_ListNode"
))
elements.extend(extend_list_.elements)
return result.success(List(elements, node.pos_start, node.pos_end).set_context(ctx))
def visit_BinOpNode(self, node: BinOpNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit BinOpNode"""
res = RTResult()
left = self._visit_value_that_can_have_attributes(node.left_node, res, ctx, methods_instead_of_funcs)
if res.should_return():
return res
assert isinstance(left, Value)
if node.op_token.matches(TT["KEYWORD"], 'and') and left.is_false():
# operator is "and" and the value is false
return res.success(Number(False, node.pos_start, node.pos_end))
if node.op_token.matches(TT["KEYWORD"], 'or') and left.is_true():
# operator is "or" and the value is true
return res.success(Number(True, node.pos_start, node.pos_end))
right = self._visit_value_that_can_have_attributes(node.right_node, res, ctx, methods_instead_of_funcs)
if res.should_return():
return res
assert isinstance(right, Value)
# we check for what is the operator token, then we execute the corresponding method
if node.op_token.type == TT["PLUS"]:
result, error = left.added_to(right)
elif node.op_token.type == TT["MINUS"]:
result, error = left.subbed_by(right)
elif node.op_token.type == TT["MUL"]:
result, error = left.multiplied_by(right)
elif node.op_token.type == TT["DIV"]:
result, error = left.divided_by(right)
elif node.op_token.type == TT["PERC"]:
result, error = left.modded_by(right)
elif node.op_token.type == TT["FLOORDIV"]:
result, error = left.floor_divided_by(right)
elif node.op_token.type == TT["POW"]:
result, error = left.powered_by(right)
elif node.op_token.type == TT["EE"]:
result, error = left.get_comparison_eq(right)
elif node.op_token.type == TT["NE"]:
result, error = left.get_comparison_ne(right)
elif node.op_token.type == TT["LT"]:
result, error = left.get_comparison_lt(right)
elif node.op_token.type == TT["GT"]:
result, error = left.get_comparison_gt(right)
elif node.op_token.type == TT["LTE"]:
result, error = left.get_comparison_lte(right)
elif node.op_token.type == TT["GTE"]:
result, error = left.get_comparison_gte(right)
elif node.op_token.matches(TT["KEYWORD"], 'and'):
result, error = left.and_(right)
elif node.op_token.matches(TT["KEYWORD"], 'or'):
result, error = left.or_(right)
elif node.op_token.matches(TT["KEYWORD"], 'xor'):
result, error = left.xor_(right)
elif node.op_token.type == TT["BITWISEAND"]:
result, error = left.bitwise_and(right)
elif node.op_token.type == TT["BITWISEOR"]:
result, error = left.bitwise_or(right)
elif node.op_token.type == TT["BITWISEXOR"]:
result, error = left.bitwise_xor(right)
else:
print(ctx)
print("NOUGARO INTERNAL ERROR: Result is not defined after executing "
f"{_ORIGIN_FILE}.visit_BinOpNode because of an invalid token.\n"
f"{methods_instead_of_funcs=}\n"
"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with the information "
"above")
raise Exception(f"Result is not defined after executing {_ORIGIN_FILE}.visit_BinOpNode")
if error is not None: # there is an error
return res.failure(error)
assert result is not None
return res.success(result.set_pos(node.pos_start, node.pos_end))
def visit_BinOpCompNode(self, node: BinOpCompNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit BinOpCompNode"""
res = RTResult()
nodes_and_tokens_list = node.nodes_and_tokens_list
IS_COMPARISON = len(nodes_and_tokens_list) != 1
if not IS_COMPARISON:
assert isinstance(nodes_and_tokens_list[0], Node) or isinstance(nodes_and_tokens_list[0], list)
value = self._visit_value_that_can_have_attributes(
nodes_and_tokens_list[0], res, ctx, methods_instead_of_funcs
)
if res.should_return():
return res
assert isinstance(value, Value)
return res.success(value)
visited_nodes_and_tokens_list: list[Value | Token] = []
# just list of visited nodes
for index, element in enumerate(nodes_and_tokens_list):
if index % 2 == 0: # we take only nodes and not ops
assert isinstance(element, Node) or isinstance(element, list)
value = self._visit_value_that_can_have_attributes(element, res, ctx, methods_instead_of_funcs)
if res.should_return():
return res
assert isinstance(value, Value)
visited_nodes_and_tokens_list.append(value)
else:
assert isinstance(element, Token)
visited_nodes_and_tokens_list.append(element)
test_result = Number(False, node.pos_start, node.pos_end)
# let's test!
for index, element in enumerate(visited_nodes_and_tokens_list):
if index % 2 != 0: # we take only nodes and not ops
continue
assert isinstance(element, Value)
# test
try:
op_token = visited_nodes_and_tokens_list[index + 1]
right = visited_nodes_and_tokens_list[index + 2]
assert isinstance(op_token, Token)
assert isinstance(right, Value)
except IndexError:
break
if op_token.type == TT["EE"]:
test_result, error = element.get_comparison_eq(right)
elif op_token.type == TT["NE"]:
test_result, error = element.get_comparison_ne(right)
elif op_token.type == TT["LT"]:
test_result, error = element.get_comparison_lt(right)
elif op_token.type == TT["GT"]:
test_result, error = element.get_comparison_gt(right)
elif op_token.type == TT["LTE"]:
test_result, error = element.get_comparison_lte(right)
elif op_token.type == TT["GTE"]:
test_result, error = element.get_comparison_gte(right)
elif op_token.matches(TT["KEYWORD"], 'in'):
test_result, error = element.is_in(right)
else:
print(ctx)
print(
f"NOUGARO INTERNAL ERROR: Result is not defined after executing "
f"{_ORIGIN_FILE}.visit_BinOpCompNode because of an invalid token.\n"
f"{methods_instead_of_funcs}\n"
f"Note for devs: the actual invalid token is {op_token.type}:{op_token.value}.\n"
f"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with the "
f"information above")
raise Exception("Result is not defined after executing "
f"{_ORIGIN_FILE}.visit_BinOpCompNode")
if error is not None: # there is an error
return res.failure(error)
assert test_result is not None
if test_result.is_false(): # the test is false so far: no need to continue
return res.success(test_result.set_pos(node.pos_start, node.pos_end))
return res.success(test_result.set_pos(node.pos_start, node.pos_end))
def visit_UnaryOpNode(self, node: UnaryOpNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit UnaryOpNode (-x, not x, ~x)"""
result = RTResult()
if isinstance(node.node, list):
if len(node.node) == 1:
value = result.register(self.visit(node.node[0], ctx, methods_instead_of_funcs))
else:
print(ctx)
print(
f"NOUGARO INTERNAL ERROR: len(node.node) != 1 in {_ORIGIN_FILE}.visit_UnaryOpNode.\n"
f"{node.node=}, {methods_instead_of_funcs=}\n"
f"Please report this bug at https://jd-develop.github.io/nougaro/bugreport.html with the "
f"information above.")
raise Exception(f"len(node.node) != 1 in {_ORIGIN_FILE}.visit_UnaryOpNode.")
else:
value = result.register(self.visit(node.node, ctx, methods_instead_of_funcs))
if result.should_return():
return result
assert value is not None
error = None
if node.op_token.type == TT["MINUS"]:
value, error = value.multiplied_by(
Number(-1, node.op_token.pos_start, node.op_token.pos_end)
) # -x is like x*-1
elif node.op_token.matches(TT["KEYWORD"], 'not'):
value = Number(not value.is_true(), node.pos_start, node.pos_end)
elif node.op_token.type == TT["BITWISENOT"]:
value, error = value.bitwise_not()
if error is not None: # there is an error
return result.failure(error)
assert value is not None
return result.success(value.set_pos(node.pos_start, node.pos_end))
def visit_VarAccessNode(self, node: VarAccessNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit VarAccessNode"""
attribute_error = node.attr
result = RTResult()
var_names_list: list[Token | Node] = node.var_name_tokens_list # there is a list because it can be `a ? b ? c`
value = None
var_name: Token | Node = var_names_list[0] # first we take the first identifier
for var_name in var_names_list: # we check for all the identifiers
IS_IDENTIFIER = isinstance(var_name, Token) and var_name.type == TT["IDENTIFIER"]
if not IS_IDENTIFIER:
assert isinstance(var_name, Node)
value = result.register(self.visit(var_name, ctx, methods_instead_of_funcs)) # here var_name is an expr
if result.should_return():
return result
break
assert ctx.symbol_table is not None
assert isinstance(var_name, Token)
assert isinstance(var_name.value, str)
value = ctx.symbol_table.get(var_name.value) # we get the value of the variable
if value is not None: # if the variable is defined, we can stop here
break
VARIABLE_IS_DEFINED = value is not None
if not VARIABLE_IS_DEFINED:
if attribute_error:
assert isinstance(var_name, Token)
assert isinstance(var_name.value, str)
return result.failure(RTAttributeError(
node.pos_start, node.pos_end, ctx.value_im_attribute_of, var_name.value, ctx,
f"{_ORIGIN_FILE}.visit_varAccessNode"
))
SINGLE_IDENTIFIER = len(var_names_list) == 1
if SINGLE_IDENTIFIER:
assert isinstance(var_name, Token)
assert isinstance(var_name.value, str)
return self._undefined(
node.pos_start, node.pos_end, var_name.value, ctx, result, f"{_ORIGIN_FILE}.visit_VarAccessNode"
)
else: # none of the identifiers is defined
return result.failure(RTNotDefinedError(
node.pos_start, node.pos_end, f"none of the given identifiers is defined.", ctx,
f"{_ORIGIN_FILE}.visit_varAccessNode"
))
# we get the value
value = value.set_pos(node.pos_start, node.pos_end).set_context(ctx)
return result.success(value)
def visit_VarAssignNode(self, node: VarAssignNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit VarAssignNode"""
result = RTResult()
var_names: list[list[Token | Node]] = node.var_names
values: list[Value] = []
if node.value_nodes is not None:
for value_node in node.value_nodes: # we get the values
value = result.register(self.visit(value_node, ctx, methods_instead_of_funcs))
if result.should_return() or result.old_should_return or value is None:
return result
assert value is not None
values.append(value)
equal = node.equal.type # we get the equal type
if equal in [TT["INCREMENT"], TT["DECREMENT"]]:
values = [Number(1, node.equal.pos_start, node.equal.pos_end)] * len(var_names)
if equal == TT["INCREMENT"]:
equal = TT["PLUSEQ"]
else:
equal = TT["MINUSEQ"]
if len(var_names) != len(values):
return result.failure(RunTimeError(
node.pos_start, node.pos_end,
f"there should be the same amount of identifiers and values. "
f"There are {len(var_names)} identifiers and {len(values)} values.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_VarAssignNode"
))
final_values: list[Value] = []
assert ctx.symbol_table is not None
for i, var_name in enumerate(var_names):
IS_SINGLE_VAR_NAME = len(var_name) == 1
if IS_SINGLE_VAR_NAME:
NAME_IS_IDENTIFIER = isinstance(var_name[0], Token) and var_name[0].type == TT["IDENTIFIER"]
if not NAME_IS_IDENTIFIER:
return result.failure(RunTimeError(
var_name[0].pos_start, var_name[0].pos_end,
"excepted identifier.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_VarAssignNode"
))
assert isinstance(var_name[0], Token)
assert isinstance(var_name[0].value, str)
final_var_name: str = var_name[0].value
variable_exists = final_var_name in ctx.symbol_table.symbols
if variable_exists:
var_actual_value: Value | None = ctx.symbol_table.get(final_var_name)
else:
var_actual_value: Value | None = None
value: Value | None = None
else: # var a.b.(...).z = value
if isinstance(var_name[0], Token) and var_name[0].type == TT["IDENTIFIER"]:
assert isinstance(var_name[0].value, str)
value = ctx.symbol_table.get(var_name[0].value)
if value is None:
return self._undefined(
var_name[0].pos_start, var_name[0].pos_end, var_name[0].value, ctx, result,
origin_file="src.runtime.interpreter.Interpreter.visit_VarAssignNode"
)
elif isinstance(var_name[0], Token):
if var_name[0].type in TOKENS_NOT_TO_QUOTE:
err_msg = f"unexpected token: {var_name[0].type}."
else:
err_msg = f"unexpected token: '{var_name[0].type}'."
return result.failure(InvalidSyntaxError(
var_name[0].pos_start, var_name[0].pos_end,
err_msg, origin_file="src.runtime.interpreter.Interpreter.visit_VarAssignNode"
))
else:
value = result.register(self.visit(var_name[0], ctx, methods_instead_of_funcs))
if result.should_return():
return result
assert isinstance(value, Value)
for node_or_tok in var_name[1:-1]:
new_ctx = Context(
display_name=f"attribute of {repr(value)}",
entry_pos=node_or_tok.pos_start,
parent=ctx,
value_im_attribute_of=repr(value)
)
new_ctx.symbol_table = SymbolTable()
new_ctx.symbol_table.set_whole_table(value.attributes)
new_ctx.symbol_table.parent = ctx.symbol_table
if isinstance(node_or_tok, Token) and node_or_tok.type == TT["IDENTIFIER"]:
assert isinstance(node_or_tok.value, str)
value = new_ctx.symbol_table.get(node_or_tok.value)
if value is None:
return self._undefined(
node_or_tok.pos_start, node_or_tok.pos_end, node_or_tok.value, new_ctx, result,
origin_file=f"{_ORIGIN_FILE}.visit_VarAssignNode"
)
elif isinstance(node_or_tok, Token):
if node_or_tok.type in TOKENS_NOT_TO_QUOTE:
err_msg = f"unexpected token: {node_or_tok.type}."
else:
err_msg = f"unexpected token: '{node_or_tok.type}'."
return result.failure(InvalidSyntaxError(
node_or_tok.pos_start, node_or_tok.pos_end,
err_msg, origin_file="src.runtime.interpreter.Interpreter.visit_VarAssignNode"
))
else:
if not (isinstance(node_or_tok, VarAccessNode) or isinstance(node_or_tok, CallNode)):
return result.failure(RunTimeError(
node_or_tok.pos_start, node_or_tok.pos_end,
f"unexpected node: {node_or_tok.__class__.__name__}.",
ctx, origin_file="src.runtime.interpreter.Interpreter.visit_VarAssignNode"
))
value = result.register(self.visit(node_or_tok, new_ctx, methods_instead_of_funcs,
other_ctx=ctx))
if result.should_return():
return result
assert value is not None
assert isinstance(var_name[-1], Token)
TOKEN_IS_IDENTIFIER = var_name[-1].type == TT["IDENTIFIER"]
if not TOKEN_IS_IDENTIFIER:
return result.failure(RunTimeError(
var_name[-1].pos_start, var_name[-1].pos_end,
"expected valid identifier.",
ctx, origin_file="src.runtime.interpreter.Interpreter.visit_VarAssignNode"
))
assert isinstance(var_name[-1].value, str)
final_var_name: str = var_name[-1].value
variable_exists = final_var_name in value.attributes
if variable_exists:
var_actual_value: Value | None = value.attributes[final_var_name]
else:
var_actual_value: Value | None = None
if equal == TT["EQ"]: # just a regular equal, we can modify/create the variable in the symbol table
final_value, error = values[i], None # we want to return the new value of the variable
elif variable_exists: # edit variable
assert isinstance(var_actual_value, Value) # a little cheesy
var_actual_value.set_pos(var_name[0].pos_start, var_name[-1].pos_end)
if equal == TT["PLUSEQ"]:
final_value, error = var_actual_value.added_to(values[i])
elif equal == TT["MINUSEQ"]:
final_value, error = var_actual_value.subbed_by(values[i])
elif equal == TT["MULTEQ"]:
final_value, error = var_actual_value.multiplied_by(values[i])
elif equal == TT["DIVEQ"]:
final_value, error = var_actual_value.divided_by(values[i])
elif equal == TT["POWEQ"]:
final_value, error = var_actual_value.powered_by(values[i])
elif equal == TT["FLOORDIVEQ"]:
final_value, error = var_actual_value.floor_divided_by(values[i])
elif equal == TT["PERCEQ"]:
final_value, error = var_actual_value.modded_by(values[i])
elif equal == TT["OREQ"]:
final_value, error = var_actual_value.or_(values[i])
elif equal == TT["XOREQ"]:
final_value, error = var_actual_value.xor_(values[i])
elif equal == TT["ANDEQ"]:
final_value, error = var_actual_value.and_(values[i])
elif equal == TT["BITWISEANDEQ"]:
final_value, error = var_actual_value.bitwise_and(values[i])
elif equal == TT["BITWISEOREQ"]:
final_value, error = var_actual_value.bitwise_or(values[i])
elif equal == TT["BITWISEXOREQ"]:
final_value, error = var_actual_value.bitwise_xor(values[i])
elif equal == TT["EEEQ"]:
final_value, error = var_actual_value.get_comparison_eq(values[i])
elif equal == TT["LTEQ"]:
final_value, error = var_actual_value.get_comparison_lt(values[i])
elif equal == TT["GTEQ"]:
final_value, error = var_actual_value.get_comparison_gt(values[i])
elif equal == TT["LTEEQ"]:
final_value, error = var_actual_value.get_comparison_lte(values[i])
elif equal == TT["GTEEQ"]:
final_value, error = var_actual_value.get_comparison_gte(values[i])
else: # this is not supposed to happen
print(
f"Note: there was a problem in {_ORIGIN_FILE}.visit_VarAssignNode.\n"
"Please report this error at https://jd-develop.github.io/nougaro/bugreport.html "
"with all infos.\n"
"Note that your variable will be set to the value you given.\n"
f"For the dev: equal token '{equal}' is in EQUALS but not planned in "
"visit_VarAssignNode"
)
error = None
final_value = values[i]
else: # variable does not exist
return self._undefined(node.pos_start, node.pos_end, final_var_name, ctx, result,
f"{_ORIGIN_FILE}.visit_VarAssignNode", edit=True)
if error is not None: # there is an error
error.set_pos(node.pos_start, node.pos_end)
return result.failure(error)
if not IS_SINGLE_VAR_NAME:
assert value is not None
assert isinstance(var_name[-1], Token)
assert isinstance(var_name[-1].value, str)
assert final_value is not None
value.attributes[var_name[-1].value] = final_value
else:
assert final_value is not None
if final_var_name == "javascript":
print_in_red(
"DEPRECATION WARNING: naming a variable 'javascript' is deprecated and will be removed in 2.0.0."
)
ctx.symbol_table.set(final_var_name, final_value)
final_values.append(final_value)
self.update_symbol_table(ctx)
# we return the (new) value(s) of the variable(s).
if len(final_values) != 1:
return result.success(
List(final_values, node.pos_start, node.pos_end)
)
else:
return result.success(
final_values[0].set_pos(node.pos_start, node.pos_end)
)
def visit_VarDeleteNode(self, node: VarDeleteNode, ctx: Context) -> RTResult:
"""Visit VarDeleteNode"""
result = RTResult()
var_name = node.var_name_token.value # we get the var name
assert isinstance(var_name, str)
assert ctx.symbol_table is not None
if var_name not in ctx.symbol_table.symbols: # the variable is not defined, so we can't delete it
return self._undefined(node.pos_start, node.pos_end, var_name, ctx, result,
f"{_ORIGIN_FILE}.visit_varDeleteNode")
ctx.symbol_table.remove(var_name)
self.update_symbol_table(ctx)
return result.success(NoneValue(node.pos_start, node.pos_end, False).set_context(ctx))
def visit_IfNode(self, node: IfNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit IfNode"""
result = RTResult()
IF_AND_ELIF_CASES = node.cases
for condition, body_expr in IF_AND_ELIF_CASES:
condition_value = result.register(self.visit(condition, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert condition_value is not None
if condition_value.is_true(): # if it is true: we execute the body code then we return the value
expr_value = result.register(self.visit(body_expr, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert expr_value is not None
return result.success(expr_value)
ELSE_CASE = node.else_case is not None
if ELSE_CASE:
assert node.else_case is not None
else_value = result.register(self.visit(node.else_case, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert else_value is not None
return result.success(else_value)
return result.success(NoneValue(node.pos_start, node.pos_end, False).set_context(ctx))
def visit_AssertNode(self, node: AssertNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit AssertNode"""
result = RTResult()
assertion = result.register(self.visit(node.assertion, ctx, methods_instead_of_funcs)) # we get the assertion
if result.should_return(): # check for errors
return result
assert assertion is not None
errmsg = result.register(self.visit(node.errmsg, ctx, methods_instead_of_funcs)) # we get the error message
if result.should_return(): # check for errors
return result
assert errmsg is not None
if assertion.is_false(): # the assertion is not true, we return an error
return result.failure(RTAssertionError(
assertion.pos_start, assertion.pos_end,
errmsg.to_python_str(),
ctx, f"{_ORIGIN_FILE}.visit_AssertNode"
))
return result.success(NoneValue(node.pos_start, node.pos_end, False).set_context(ctx))
def visit_ForNode(self, node: ForNode, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit ForNode. for i = start to end then"""
result = RTResult()
elements: list[Value] = []
start_value = result.register(self.visit(node.start_value_node, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert start_value is not None
if not (isinstance(start_value, Number) and isinstance(start_value.value, int)):
return result.failure(RTTypeError(
start_value.pos_start, start_value.pos_end,
f"start value should be an integer, not {start_value.type_}.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_ForNode"
))
end_value = result.register(self.visit(node.end_value_node, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert end_value is not None
if not (isinstance(end_value, Number) and isinstance(end_value.value, int)):
return result.failure(RTTypeError(
end_value.pos_start, end_value.pos_end,
f"end value should be an integer, not {end_value.type_}.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_ForNode"
))
if node.step_value_node is not None: # we get the step value, if there is one
step_value = result.register(self.visit(node.step_value_node, ctx, methods_instead_of_funcs))
if result.should_return(): # check for errors
return result
assert step_value is not None
else:
step_value = Number(1, node.start_value_node.pos_start, node.body_node.pos_start) # no step value: default is 1
if not (isinstance(step_value, Number) and isinstance(step_value.value, int)):
return result.failure(RTTypeError(
step_value.pos_start, step_value.pos_end,
f"step value should be an integer, not {step_value.type_}.",
ctx, origin_file=f"{_ORIGIN_FILE}.visit_ForNode"
))
# we make an end condition
# if step value is *positive*, the end value is *more* than the initial value
# if step value is *negative*, the end value is *less* than the initial value
i = start_value.value
POSITIVE_STEP = step_value.value >= 0
if POSITIVE_STEP:
condition = (lambda: i < end_value.value)
else:
condition = (lambda: i > end_value.value)
assert ctx.symbol_table is not None
assert isinstance(node.var_name_token.value, str)
value_to_return = None
outer_loop_should_break = False
outer_loop_should_continue = False
while condition():
ctx.symbol_table.set(
node.var_name_token.value, Number(i, node.var_name_token.pos_start, node.var_name_token.pos_end)
) # we set the iterating variable
self.update_symbol_table(ctx)
i += step_value.value # we add up the step value to the iterating variable
value = result.register(self.visit(node.body_node, ctx, methods_instead_of_funcs))
if result.loop_should_continue:
if self.lexer_metas.get("appendNoneOnContinue") is not None:
elements.append(NoneValue(node.body_node.pos_start, node.body_node.pos_end, False))
if result.continue_label is not None and node.label != result.continue_label:
outer_loop_should_continue = True
break
continue
if result.loop_should_break:
value_to_return = result.break_value # which is a Value or None
if self.lexer_metas.get("appendNoneOnBreak") is not None:
elements.append(NoneValue(node.body_node.pos_start, node.body_node.pos_end, False))
if result.break_label is not None and node.label != result.break_label:
outer_loop_should_break = True
break
if result.should_return(True):
# if there is an error or a 'return' statement
return result
assert value is not None
elements.append(value)
if outer_loop_should_continue:
assert result.break_or_continue_pos is not None
pos_start, pos_end = result.break_or_continue_pos
return result.success_continue(pos_start, pos_end, result.continue_label)
if outer_loop_should_break:
assert result.break_or_continue_pos is not None
pos_start, pos_end = result.break_or_continue_pos
return result.success_break(pos_start, pos_end, result.break_value, result.break_label)
if value_to_return is not None:
return result.success(value_to_return)
return result.success(
List(elements, node.pos_start, node.pos_end).set_context(ctx)
)
def visit_ForNodeList(self, node: ForNodeList, ctx: Context, methods_instead_of_funcs: bool) -> RTResult:
"""Visit ForNodeList. for i in list then"""
result = RTResult()
elements: list[Value] = []
iterable_ = result.register(self.visit(node.list_node, ctx, methods_instead_of_funcs)) # we get the list
if result.should_return(): # check for errors
return result
if isinstance(iterable_, List):
python_iterable = iterable_.elements