This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
1016 lines (816 loc) · 31.4 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
import os
import math
import string
import sys
try:
from symboltable import SymbolTable
from runtime import RTResult
from errors import RTError
from tokens import Tokens
except:
from .symboltable import SymbolTable
from .runtime import RTResult
from .errors import RTError
from .tokens import Tokens
#######################################
# VALUES
#######################################
class Value:
def __init__(self):
self.set_pos()
self.set_context()
def set_pos(self, pos_start=None, pos_end=None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def set_context(self, context=None):
self.context = context
return self
def added_to(self, other):
return None, self.illegal_operation(other)
def subbed_by(self, other):
return None, self.illegal_operation(other)
def multed_by(self, other):
return None, self.illegal_operation(other)
def dived_by(self, other):
return None, self.illegal_operation(other)
def powed_by(self, other):
return None, self.illegal_operation(other)
def get_comparison_eq(self, other):
return None, self.illegal_operation(other)
def get_comparison_ne(self, other):
return None, self.illegal_operation(other)
def get_comparison_lt(self, other):
return None, self.illegal_operation(other)
def get_comparison_gt(self, other):
return None, self.illegal_operation(other)
def get_comparison_lte(self, other):
return None, self.illegal_operation(other)
def get_comparison_gte(self, other):
return None, self.illegal_operation(other)
def anded_by(self, other):
return None, self.illegal_operation(other)
def ored_by(self, other):
return None, self.illegal_operation(other)
def notted(self, other):
return None, self.illegal_operation(other)
def execute(self, args):
return RTResult().failure(self.illegal_operation())
def copy(self):
raise Exception('No copy method defined')
def is_true(self):
return False
def illegal_operation(self, other=None):
if not other: other = self
return RTError(
self.pos_start, other.pos_end,
'Illegal operation',
self.context
)
class Number(Value):
def __init__(self, value):
super().__init__()
self.value = value
def added_to(self, other):
if isinstance(other, Number):
return Number(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def subbed_by(self, other):
if isinstance(other, Number):
return Number(self.value - other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, Number):
return Number(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def dived_by(self, other):
if isinstance(other, Number):
if other.value == 0:
return None, RTError(
other.pos_start, other.pos_end,
'Division by zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def powed_by(self, other):
if isinstance(other, Number):
return Number(self.value ** other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_eq(self, other):
if isinstance(other, Number):
return Number(int(self.value == other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_ne(self, other):
if isinstance(other, Number):
return Number(int(self.value != other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gt(self, other):
if isinstance(other, Number):
return Number(int(self.value > other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lte(self, other):
if isinstance(other, Number):
return Number(int(self.value <= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gte(self, other):
if isinstance(other, Number):
return Number(int(self.value >= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def anded_by(self, other):
if isinstance(other, Number):
return Number(int(self.value and other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def ored_by(self, other):
if isinstance(other, Number):
return Number(int(self.value or other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def notted(self):
return Number(1 if self.value == 0 else 0).set_context(self.context), None
def copy(self):
copy = Number(self.value)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def is_true(self):
return self.value != 0
def __str__(self):
return str(self.value)
def __repr__(self):
return str(self.value)
Number.null = Number(0)
Number.false = Number(0)
Number.true = Number(1)
Number.math_PI = Number(math.pi)
class String(Value):
def __init__(self, value):
super().__init__()
self.value = value
def added_to(self, other):
if isinstance(other, String):
return String(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, Number):
return String(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def is_true(self):
return len(self.value) > 0
def copy(self):
copy = String(self.value)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'"{self.value}"'
class PythonCode(Value):
def __init__(self, value):
super().__init__()
self.value = value
exec(self.value)
def added_to(self, other):
if isinstance(other, PythonCode):
return PythonCode(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def is_true(self):
return len(self.value) > 0
def copy(self):
copy = PythonCode(self.value)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'`{self.value}`'
class List(Value):
def __init__(self, elements):
super().__init__()
self.elements = elements
def added_to(self, other):
new_list = self.copy()
new_list.elements.append(other)
return new_list, None
def subbed_by(self, other):
if isinstance(other, Number):
new_list = self.copy()
try:
new_list.elements.pop(other.value)
return new_list, None
except:
return None, RTError(
other.pos_start, other.pos_end,
'Element at this index could not be removed from list because index is out of bounds',
self.context
)
else:
return None, Value.illegal_operation(self, other)
def multed_by(self, other):
if isinstance(other, List):
new_list = self.copy()
new_list.elements.extend(other.elements)
return new_list, None
else:
return None, Value.illegal_operation(self, other)
def dived_by(self, other):
if isinstance(other, Number):
try:
return self.elements[other.value], None
except:
return None, RTError(
other.pos_start, other.pos_end,
'Element at this index could not be retrieved from list because index is out of bounds',
self.context
)
else:
return None, Value.illegal_operation(self, other)
def copy(self):
copy = List(self.elements)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return ", ".join([str(x) for x in self.elements])
def __repr__(self):
return f'[{", ".join([repr(x) for x in self.elements])}]'
class BaseFunction(Value):
def __init__(self, name):
super().__init__()
self.name = name or "<anonymous>"
def generate_new_context(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self, arg_names, args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into {self}",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into {self}",
self.context
))
return res.success(None)
def populate_args(self, arg_names, args, exec_ctx):
for i in range(len(args)):
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(exec_ctx)
exec_ctx.symbol_table.set(arg_name, arg_value)
def check_and_fix_default_args(self, arg_names, args):
if self.name == "input" and (len(args) < len(arg_names)):
args.append(String(""))
if self.name == "input_int" and (len(args) < len(arg_names)):
args.append(String(""))
if self.name == "write" and (len(args) > len(arg_names)):
full_arg = ""
for i in range(0, len(args)):
t = str(args[i])
if i != 0:
full_arg += f" {t}"
cargs = str(args[0]) + full_arg
args.clear()
args.append(String(cargs))
def check_and_populate_args(self, arg_names, args, exec_ctx):
res = RTResult()
self.check_and_fix_default_args(arg_names, args)
res.register(self.check_args(arg_names, args))
if res.should_return(): return res
self.populate_args(arg_names, args, exec_ctx)
return res.success(None)
class Function(BaseFunction):
def __init__(self, name, body_node, arg_names, should_auto_return):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.should_auto_return = should_auto_return
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
exec_ctx = self.generate_new_context()
res.register(self.check_and_populate_args(self.arg_names, args, exec_ctx))
if res.should_return(): return res
value = res.register(interpreter.visit(self.body_node, exec_ctx))
if res.should_return() and res.func_return_value == None: return res
ret_value = (value if self.should_auto_return else None) or res.func_return_value or Number.null
return res.success(ret_value)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names, self.should_auto_return)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self, name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generate_new_context()
method_name = f'execute_{self.name}'
method = getattr(self, method_name, self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names, args, exec_ctx))
if res.should_return(): return res
return_value = res.register(method(exec_ctx))
if res.should_return(): return res
return res.success(return_value)
def no_visit_method(self, node, context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<built-in function {self.name}>"
#####################################
def execute_write(self, exec_ctx):
print(str(exec_ctx.symbol_table.get('value')).encode("utf8").decode(sys.stdout.encoding))
f = open("_printed_",'a',encoding='utf8')
print(str(exec_ctx.symbol_table.get('value')), file=f)
f.close()
return RTResult().success(Number.null)
execute_write.arg_names = ['value']
def execute_write_ret(self, exec_ctx):
return RTResult().success(String(str(exec_ctx.symbol_table.get('value'))))
execute_write_ret.arg_names = ['value']
def execute_input(self, exec_ctx):
text = input(exec_ctx.symbol_table.get('prompt'))
return RTResult().success(String(text))
execute_input.arg_names = ['prompt']
def execute_input_int(self, exec_ctx):
while True:
text = input(exec_ctx.symbol_table.get('prompt'))
try:
number = int(text)
break
except ValueError:
print(f"'{text}' must be an integer. Try again!")
return RTResult().success(Number(number))
execute_input_int.arg_names = ['prompt']
def execute_clear(self, exec_ctx):
os.system('cls' if os.name == 'nt' else 'cls')
return RTResult().success(Number.null)
execute_clear.arg_names = []
def execute_is_number(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), Number)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_number.arg_names = ["value"]
def execute_is_string(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), String)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_string.arg_names = ["value"]
def execute_is_list(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), List)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_list.arg_names = ["value"]
def execute_is_function(self, exec_ctx):
is_number = isinstance(exec_ctx.symbol_table.get("value"), BaseFunction)
return RTResult().success(Number.true if is_number else Number.false)
execute_is_function.arg_names = ["value"]
def execute_to_string(self, exec_ctx):
result = String(str(exec_ctx.symbol_table.get("value")))
if not isinstance(result, String):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Couldn't convert to a string",
exec_ctx
))
return RTResult().success(result)
execute_to_string.arg_names = ["value"]
def execute_to_number(self, exec_ctx):
if not (isinstance(exec_ctx.symbol_table.get("value"), String) or isinstance(exec_ctx.symbol_table.get("value"), Number)):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Couldn't convert to an integer",
exec_ctx
))
result = Number(int(str(exec_ctx.symbol_table.get("value"))))
return RTResult().success(result)
execute_to_number.arg_names = ["value"]
def execute_type_(self, exec_ctx):
return RTResult().success(String(str(type(exec_ctx.symbol_table.get("value")))))
execute_type_.arg_names = ['value']
def execute_append(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
value = exec_ctx.symbol_table.get("value")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
list_.elements.append(value)
return RTResult().success(Number.null)
execute_append.arg_names = ["list", "value"]
def execute_pop(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
index = exec_ctx.symbol_table.get("index")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
if not isinstance(index, Number):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be number",
exec_ctx
))
try:
element = list_.elements.pop(index.value)
except:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
'Element at this index could not be removed from list because index is out of bounds',
exec_ctx
))
return RTResult().success(element)
execute_pop.arg_names = ["list", "index"]
def execute_select(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
index = exec_ctx.symbol_table.get("index")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
if not isinstance(index, Number):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be number",
exec_ctx
))
try:
element = list_.elements[index.value]
except:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
'Element at this index could not be removed from list because index is out of bounds',
exec_ctx
))
return RTResult().success(element)
execute_select.arg_names = ["list", "index"]
def execute_extend(self, exec_ctx):
listA = exec_ctx.symbol_table.get("listA")
listB = exec_ctx.symbol_table.get("listB")
if not isinstance(listA, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"First argument must be list",
exec_ctx
))
if not isinstance(listB, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be list",
exec_ctx
))
listA.elements.extend(listB.elements)
return RTResult().success(Number.null)
execute_extend.arg_names = ["listA", "listB"]
def execute_len(self, exec_ctx):
list_ = exec_ctx.symbol_table.get("list")
if not isinstance(list_, List):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Argument must be list",
exec_ctx
))
return RTResult().success(Number(len(list_.elements)))
execute_len.arg_names = ["list"]
def execute_import_(self, exec_ctx):
fn = exec_ctx.symbol_table.get("fn")
if not isinstance(fn, String):
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
"Second argument must be string",
exec_ctx
))
fn = fn.value
try:
with open(fn, "r", encoding="utf-8") as f:
script = f.read()
except Exception as e:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
f"Failed to import script \"{fn}\"\n" + str(e),
exec_ctx
))
_, error = _import(fn, script)
if error:
return RTResult().failure(RTError(
self.pos_start, self.pos_end,
f"Failed to finish executing script \"{fn}\"\n" +
error.as_string(),
exec_ctx
))
return RTResult().success(Number.null)
execute_import_.arg_names = ["fn"]
BuiltInFunction.write = BuiltInFunction("write")
BuiltInFunction.write_ret = BuiltInFunction("write_ret")
BuiltInFunction.input = BuiltInFunction("input")
BuiltInFunction.input_int = BuiltInFunction("input_int")
BuiltInFunction.clear = BuiltInFunction("clear")
BuiltInFunction.is_number = BuiltInFunction("is_number")
BuiltInFunction.is_string = BuiltInFunction("is_string")
BuiltInFunction.is_list = BuiltInFunction("is_list")
BuiltInFunction.is_function = BuiltInFunction("is_function")
BuiltInFunction.to_string = BuiltInFunction("to_string")
BuiltInFunction.to_number = BuiltInFunction("to_number")
BuiltInFunction.type_ = BuiltInFunction("type_")
BuiltInFunction.append = BuiltInFunction("append")
BuiltInFunction.pop = BuiltInFunction("pop")
BuiltInFunction.select = BuiltInFunction("select")
BuiltInFunction.extend = BuiltInFunction("extend")
BuiltInFunction.len = BuiltInFunction("len")
BuiltInFunction.import_ = BuiltInFunction("import_")
#######################################
# CONTEXT
#######################################
class Context:
def __init__(self, display_name, parent=None, parent_entry_pos=None):
self.display_name = display_name
self.parent = parent
self.parent_entry_pos = parent_entry_pos
self.symbol_table = None
#######################################
# INTERPRETER
#######################################
class Interpreter:
def visit(self, node, context):
method_name = f'visit_{type(node).__name__}'
method = getattr(self, method_name, self.no_visit_method)
return method(node, context)
def no_visit_method(self, node, context):
raise Exception(f'No visit_{type(node).__name__} method defined')
###################################
def visit_NumberNode(self, node, context):
return RTResult().success(
Number(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_StringNode(self, node, context):
return RTResult().success(
String(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_PythonCodeNode(self, node, context):
return RTResult().success(
PythonCode(node.tok.value).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_ListNode(self, node, context):
res = RTResult()
elements = []
for element_node in node.element_nodes:
elements.append(res.register(self.visit(element_node, context)))
if res.should_return(): return res
return res.success(
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_VarAccessNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = context.symbol_table.get(var_name)
if not value:
return res.failure(RTError(
node.pos_start, node.pos_end,
f"'{var_name}' is not defined",
context
))
value = value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(value)
def visit_VarAssignNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = res.register(self.visit(node.value_node, context))
if res.should_return(): return res
context.symbol_table.set(var_name, value)
return res.success(value)
def visit_BinOpNode(self, node, context):
res = RTResult()
left = res.register(self.visit(node.left_node, context))
if res.should_return(): return res
right = res.register(self.visit(node.right_node, context))
if res.should_return(): return res
if node.op_tok.type == Tokens['PLUS']:
result, error = left.added_to(right)
elif node.op_tok.type == Tokens['MINUS']:
result, error = left.subbed_by(right)
elif node.op_tok.type == Tokens['MUL']:
result, error = left.multed_by(right)
elif node.op_tok.type == Tokens['DIV']:
result, error = left.dived_by(right)
elif node.op_tok.type == Tokens['POWER']:
result, error = left.powed_by(right)
elif node.op_tok.type == Tokens['EQEQ']:
result, error = left.get_comparison_eq(right)
elif node.op_tok.type == Tokens['NOTEQ']:
result, error = left.get_comparison_ne(right)
elif node.op_tok.type == Tokens['LESSTHAN']:
result, error = left.get_comparison_lt(right)
elif node.op_tok.type == Tokens['GREATERTHAN']:
result, error = left.get_comparison_gt(right)
elif node.op_tok.type == Tokens['LTEQ']:
result, error = left.get_comparison_lte(right)
elif node.op_tok.type == Tokens['GTEQ']:
result, error = left.get_comparison_gte(right)
elif node.op_tok.matches(Tokens['KEYWORD'], 'and'):
result, error = left.anded_by(right)
elif node.op_tok.matches(Tokens['KEYWORD'], 'සහ'):
result, error = left.anded_by(right)
elif node.op_tok.matches(Tokens['KEYWORD'], 'or'):
result, error = left.ored_by(right)
elif node.op_tok.matches(Tokens['KEYWORD'], 'හෝ'):
result, error = left.ored_by(right)
if error:
return res.failure(error)
else:
return res.success(result.set_pos(node.pos_start, node.pos_end))
def visit_UnaryOpNode(self, node, context):
res = RTResult()
number = res.register(self.visit(node.node, context))
if res.should_return(): return res
error = None
if node.op_tok.type == Tokens['MINUS']:
number, error = number.multed_by(Number(-1))
elif node.op_tok.matches(Tokens['KEYWORD'], 'not') or node.op_tok.matches(Tokens['KEYWORD'], 'නොමැත') or node.op_tok.matches(Tokens['KEYWORD'], 'නොව') or node.op_tok.matches(Tokens['KEYWORD'], 'නැත') or node.op_tok.matches(Tokens['KEYWORD'], 'නොවේ') or node.op_tok.matches(Tokens['KEYWORD'], 'නොව'):
number, error = number.notted()
if error:
return res.failure(error)
else:
return res.success(number.set_pos(node.pos_start, node.pos_end))
def visit_IfNode(self, node, context):
res = RTResult()
for condition, expr, should_return_null in node.cases:
condition_value = res.register(self.visit(condition, context))
if res.should_return(): return res
if condition_value.is_true():
expr_value = res.register(self.visit(expr, context))
if res.should_return(): return res
return res.success(Number.null if should_return_null else expr_value)
if node.else_case:
expr, should_return_null = node.else_case
expr_value = res.register(self.visit(expr, context))
if res.should_return(): return res
return res.success(Number.null if should_return_null else expr_value)
return res.success(Number.null)
def visit_ForNode(self, node, context):
res = RTResult()
elements = []
start_value = res.register(self.visit(node.start_value_node, context))
if res.should_return(): return res
end_value = res.register(self.visit(node.end_value_node, context))
if res.should_return(): return res
if node.step_value_node:
step_value = res.register(self.visit(node.step_value_node, context))
if res.should_return(): return res
else:
step_value = Number(1)
i = start_value.value
if step_value.value >= 0:
condition = lambda: i < end_value.value
else:
condition = lambda: i > end_value.value
while condition():
context.symbol_table.set(node.var_name_tok.value, Number(i))
i += step_value.value
value = res.register(self.visit(node.body_node, context))
if res.should_return() and res.loop_should_continue == False and res.loop_should_break == False: return res
if res.loop_should_continue:
continue
if res.loop_should_break:
break
elements.append(value)
return res.success(
Number.null if node.should_return_null else
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_WhileNode(self, node, context):
res = RTResult()
elements = []
while True:
condition = res.register(self.visit(node.condition_node, context))
if res.should_return(): return res
if not condition.is_true():
break
value = res.register(self.visit(node.body_node, context))
if res.should_return() and res.loop_should_continue == False and res.loop_should_break == False: return res
if res.loop_should_continue:
continue
if res.loop_should_break:
break
elements.append(value)
return res.success(
Number.null if node.should_return_null else
List(elements).set_context(context).set_pos(node.pos_start, node.pos_end)
)
def visit_FuncDefNode(self, node, context):
res = RTResult()
func_name = node.var_name_tok.value if node.var_name_tok else None
body_node = node.body_node
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
func_value = Function(func_name, body_node, arg_names, node.should_auto_return).set_context(context).set_pos(node.pos_start, node.pos_end)
if node.var_name_tok:
context.symbol_table.set(func_name, func_value)
return res.success(func_value)
def visit_CallNode(self, node, context):
res = RTResult()
args = []
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.should_return(): return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.should_return(): return res
return_value = res.register(value_to_call.execute(args))
if res.should_return(): return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
def visit_ReturnNode(self, node, context):
res = RTResult()
if node.node_to_return:
value = res.register(self.visit(node.node_to_return, context))
if res.should_return(): return res
else:
value = Number.null
return res.success_return(value)
def visit_ContinueNode(self, node, context):
return RTResult().success_continue()
def visit_BreakNode(self, node, context):
return RTResult().success_break()
#######################################
# RUN
#######################################
global_symbol_table = SymbolTable()
global_symbol_table.set("null", Number.null)
global_symbol_table.set("false", Number.false)
global_symbol_table.set("true", Number.true)
global_symbol_table.set("math_pi", Number.math_PI)
global_symbol_table.set("write", BuiltInFunction.write)
global_symbol_table.set("preturn", BuiltInFunction.write_ret)
global_symbol_table.set("input", BuiltInFunction.input)
global_symbol_table.set("int_input", BuiltInFunction.input_int)
global_symbol_table.set("clear", BuiltInFunction.clear)
global_symbol_table.set("cls", BuiltInFunction.clear)
global_symbol_table.set("is_num", BuiltInFunction.is_number)
global_symbol_table.set("is_str", BuiltInFunction.is_string)
global_symbol_table.set("is_list", BuiltInFunction.is_list)
global_symbol_table.set("is_function", BuiltInFunction.is_function)
global_symbol_table.set("to_str", BuiltInFunction.to_string)
global_symbol_table.set("to_num", BuiltInFunction.to_number)
global_symbol_table.set("type", BuiltInFunction.type_)
global_symbol_table.set("append", BuiltInFunction.append)
global_symbol_table.set("pop", BuiltInFunction.pop)
global_symbol_table.set("select", BuiltInFunction.select)
global_symbol_table.set("extend", BuiltInFunction.extend)
global_symbol_table.set("len", BuiltInFunction.len)
global_symbol_table.set("import", BuiltInFunction.import_)
def _import(fn, text):
try:
from lexer import Lexer
from _parser import Parser
except:
from .lexer import Lexer
from ._parser import Parser
# Generate tokens