-
Notifications
You must be signed in to change notification settings - Fork 0
/
BBthon.py
954 lines (744 loc) · 33.7 KB
/
BBthon.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
from Lexer import *
from Parser import *
import os
import math
######################
# 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.token.value).set_context(context).set_pos(node.pos_start, node.pos_end))
def visit_VariableAccessNode(self, node, context):
res = RTResult()
variable_name = node.variable_name.value
value = context.SymbolTable.GetValue(variable_name)
if not value:
return res.failure(RTError(
f"!םואתפ המ ?המ ?'{variable_name}'", node.pos_start, node.pos_end, context
))
value = value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(value)
def visit_VariableAssignmentNode(self, node, context):
res = RTResult()
variable_name = node.variable_name.value
value = res.register(self.visit(node.value_node, context))
if res.should_return(): return res
context.SymbolTable.SetValue(variable_name, value)
return res.success(value)
def visit_BinOpNode(self, node, context):
res = RTResult()
left = res.register(self.visit(node.lNode, context))
if res.should_return(): return res
right = res.register(self.visit(node.rNode, context))
if res.should_return(): return res
if node.op_token.type == T_PLUS:
result, error = left.added_to(right)
elif node.op_token.type == T_MINUS:
result, error = left.substrcted_by(right)
elif node.op_token.type == T_MUL:
result, error = left.multiplyed_by(right)
elif node.op_token.type == T_DIV:
result, error = left.divided_by(right)
elif node.op_token.type == T_DOLLAR:
result, error = left.dollar_index(right)
elif node.op_token.type == T_POW:
result, error = left.powered_by(right)
elif node.op_token.type == T_EE:
result, error = left.get_comparison_eq(right)
elif node.op_token.type == T_NE:
result, error = left.get_comparison_ne(right)
elif node.op_token.type == T_LT:
result, error = left.get_comparison_lt(right)
elif node.op_token.type == T_GT:
result, error = left.get_comparison_gt(right)
elif node.op_token.type == T_LTE:
result, error = left.get_comparison_lte(right)
elif node.op_token.type == T_GTE:
result, error = left.get_comparison_gte(right)
elif node.op_token.match(T_KEYWORD, 'וגם'):
result, error = left.anded_by(right)
elif node.op_token.match(T_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_token.type == T_MINUS:
number, Error = number.multiplyed_by(Number(-1))
elif node.op_token.match(T_KEYWORD, 'לא'):
number, error = number.notted()
if error:
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, 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 return_null else expr_value)
if node.else_case:
expr, 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 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, context))
if res.should_return(): return res
end_value = res.register(self.visit(node.end_value, context))
if res.should_return(): return res
if node.step_value:
step_value = res.register(self.visit(node.step_value, 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.SymbolTable.SetValue(node.variable_name_token.value, Number(i))
i += step_value.value
value = res.register(self.visit(node.body_node, context))
if res.should_return() and res.is_continue == False and res.is_break == False: return res
if res.is_continue:
continue
if res.is_break:
break
elements.append(value)
return res.success(Number.NULL if node.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.is_continue == False and res.is_break == False: return res
if res.is_continue:
continue
if res.is_break:
break
elements.append(value)
return res.success(Number.NULL if node.return_null else List(elements).set_context(context).set_pos(node.pos_start, node.pos_end))
def visit_FunctionNode(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.return_auto).set_context(context).set_pos(node.pos_start, node.pos_end)
if node.var_name_tok:
context.SymbolTable.SetValue(func_name, func_value)
return res.success(func_value)
def visit_CallFuncNode(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_node:
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_StringNode(self, node, context):
return RTResult().success(
String(node.token.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_ReturnNode(self, node, context):
res = RTResult()
if node.return_node:
value = res.register(self.visit(node.return_node, 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()
#######################
# Symbol Table #
#######################
class SymbolTable:
def __init__(self, parent=None):
self.local_symbols_dict = {}
self.global_symbols_dict = parent
def GetValue(self, name):
value = self.local_symbols_dict.get(name, None)
if value == None and self.global_symbols_dict:
value = self.global_symbols_dict.GetValue(name)
return value
def SetValue(self, name, value):
self.local_symbols_dict[name] = value
def remove(self, name):
del self.local_symbols_dict[name]
#######################
# Context #
#######################
class Context:
def __init__(self, dis_name, parent=None, parent_position=None):
self.dis_name = dis_name
self.parent = parent
self.parent_position = parent_position
self.SymbolTable = None
#######################
# Runtime Result #
#######################
class RTResult:
def __init__(self):
self.reset()
def reset(self):
self.value = None
self.error = None
self.return_value_func = None
self.is_continue = False
self.is_break = False
def register(self, res):
self.error = res.error
self.return_value_func = res.return_value_func
self.is_continue = res.is_continue
self.is_break = res.is_break
return res.value
def success(self, value):
self.reset()
self.value = value
return self
def success_return(self, value):
self.reset()
self.return_value_func = value
return self
def success_continue(self):
self.reset()
self.is_continue = True
return self
def success_break(self):
self.reset()
self.is_break = True
return self
def failure(self, error):
self.reset()
self.error = error
return self
def should_return(self):
return(self.error or self.return_value_func or self.is_continue or self.is_break)
######################
# Values #
######################
class Value:
def __init__(self):
self.set_pos()
self.set_context()
def set_context(self, context=None):
self.context = context
return self
def set_pos(self, pos_start=None, pos_end=None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self, other):
return None, self.illegal_operation(other)
def substrcted_by(self, other):
return None, self.illegal_operation(other)
def multiplyed_by(self, other):
return None, self.illegal_operation(other)
def divided_by(self, other):
return None, self.illegal_operation(other)
def dollar_index(self, other):
return None, self.illegal_operation(other)
def powered_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):
return None, 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, self.context)
class Number(Value):
def __init__(self, value):
self.value = value
self.set_pos()
self.set_context()
def set_context(self, context=None):
self.context = context
return self
def set_pos(self, pos_start=None, pos_end=None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
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.pos_start, self.pos_end)
def substrcted_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.pos_start, self.pos_end)
def multiplyed_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.pos_start, self.pos_end)
def divided_by(self, other):
if isinstance(other, Number):
if other.value == 0:
return None, RTError('ץ"גבב קוליח עצבתה',other.pos_start, other.pos_end, self.context)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self.pos_start, self.pos_end)
def powered_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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
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.pos_start, self.pos_end)
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 __repr__(self):
return str(self.value)
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 multiplyed_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 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 substrcted_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("חווטל ץוחמ אוה יכ הזה סקדניאב רביאה תא קוחמל ןתינ אל", self.pos_start, self.pos_end, self.context)
else:
return None, Value.illegal_operation(self, other)
def multiplyed_by(self, other):
if isinstance(other, Number):
new_list = self.copy()
new_list.elements = new_list.elements * other.value
return new_list, None
else:
return None, Value.illegal_operation(self, other)
def dollar_index(self, other):
if isinstance(other, Number):
try:
return self.elements[other.value], None
except:
return None, RTError("חווטל ץוחמ אוה יכ הזה סקדניאב רביאה תא לבקל ןתינ אל", self.pos_start, self.pos_end, 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 f'{", ".join([str(x) for x in self.elements])}'
def __repr__(self):
return f'[{", ".join([str(x) for x in self.elements])}]'
class BaseFunction(Value):
def __init__(self, name):
super().__init__()
self.name = name or "<ימינונא>"
def create_new_context(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.SymbolTable = SymbolTable(new_context.parent.SymbolTable)
return new_context
def check_args(self, arg_names, args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(f"({len(arg_names) - len(args)}) ולבקתה םיכרע ידמ רתוי",
self.pos_start, self.pos_end, self.context))
if len(args) < len(arg_names):
return res.failure(RTError(f"({len(arg_names) - len(args)}) ולבקתה םיכרע ידמ תצק",
self.pos_start, self.pos_end, self.context))
return res.success(None)
def populate_args(self, args_names, args, exectue_context):
for i in range(len(args)):
arg_name = args_names[i]
arg_value = args[i]
arg_value.set_context(exectue_context)
exectue_context.SymbolTable.SetValue(arg_name, arg_value)
def check_and_populate(self, arg_names, args, exectue_context):
res = RTResult()
res.register(self.check_args(arg_names, args))
if res.should_return(): return res
self.populate_args(arg_names, args, exectue_context)
return res.success(None)
class Function(BaseFunction):
def __init__(self, name, body_node, arg_names, return_auto):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.return_auto = return_auto
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
exec_context = self.create_new_context()
res.register(self.check_and_populate(self.arg_names, args, exec_context))
if res.should_return(): return res
value = res.register(interpreter.visit(self.body_node, exec_context))
if res.should_return() and res.return_value_func == None: return res
ret_value = (value if self.return_auto else None) or res.return_value_func or Number.NULL
return res.success(ret_value)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names, self.return_auto)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __repr__(self):
return f'<{self.name} הייצקנופ>'
class BuiltInFunction(BaseFunction):
def __init__(self, name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_context = self.create_new_context()
method_name = f'execute_{self.name}'
method = getattr(self, method_name, self.no_visit)
res.register(self.check_and_populate(method.arg_names, args, exec_context))
if res.should_return(): return res
return_value = res.register(method(exec_context))
if res.should_return(): return res
return res.success(return_value)
def execute_print(self, exec_context):
print(str(exec_context.SymbolTable.GetValue('value')))
return RTResult().success(String(str(exec_context.SymbolTable.GetValue('value'))))
execute_print.arg_names = ['value']
def execute_input(self, exec_context):
text = input()
return RTResult().success(String(text))
execute_input.arg_names = []
def execute_clear(self, exec_context):
os.system('cls' if os.name == 'nt' else 'clear')
return RTResult().success(Number.NULL)
execute_clear.arg_names = []
def execute_is_number(self, exec_context):
is_number = isinstance(exec_context.SymbolTable.GetValue('value'), Number)
return RTResult().success(Number.LIKUD if is_number else Number.MERETZ)
execute_is_number.arg_names = ['value']
def execute_is_string(self, exec_context):
is_string = isinstance(exec_context.SymbolTable.GetValue('value'), String)
return RTResult().success(Number.LIKUD if is_string else Number.MERETZ)
execute_is_string.arg_names = ['value']
def execute_is_list(self, exec_context):
is_list = isinstance(exec_context.SymbolTable.GetValue('value'), List)
return RTResult().success(Number.LIKUD if is_list else Number.MERETZ)
execute_is_list.arg_names = ['value']
def execute_is_function(self, exec_context):
is_function = isinstance(exec_context.SymbolTable.GetValue('value'), BaseFunction)
return RTResult().success(Number.LIKUD if is_function else Number.MERETZ)
execute_is_function.arg_names = ['value']
def execute_append(self, exec_context):
list_ = exec_context.SymbolTable.GetValue('list')
value = exec_context.SymbolTable.GetValue('value')
if not isinstance(list_, List):
return RTResult().failure(RTError(
"המישר תויהל בייח ןושארה טלקה", self.pos_start, self.pos_end, exec_context
))
list_.elements.append(value)
return RTResult().success(List(list_.elements))
execute_append.arg_names = ['list', 'value']
def execute_remove(self, exec_context):
list_ = exec_context.SymbolTable.GetValue('list')
index = exec_context.SymbolTable.GetValue('index')
if not isinstance(list_, List):
return RTResult().failure(RTError(
"המישר תויהל בייח ןושארה טלקה", self.pos_start, self.pos_end, exec_context
))
if not isinstance(index, Number):
return RTResult().failure(RTError(
"רפסמ תויהל בייח ינשה טלקה", self.pos_start, self.pos_end, exec_context
))
try:
element = list_.elements.pop(index.value)
except:
return RTResult().failure(RTError("חווטל ץוחמ אוה יכ הזה םוקימב רביאה תא לבקל ןתינ אל", self.pos_start, self.pos_end, self.context))
return RTResult().success(element)
execute_remove.arg_names = ['list', 'index']
def execute_pop(self, exec_context):
list_ = exec_context.SymbolTable.GetValue('list')
if not isinstance(list_, List):
return RTResult().failure(RTError(
"המישר תויהל בייח ןושארה טלקה", self.pos_start, self.pos_end, exec_context
))
try:
element = list_.elements.pop(len(list_.elements) - 1)
except:
return RTResult().failure("חווטל ץוחמ אוה יכ הזה סקדניאב רביאה תא לבקל ןתינ אל", self.pos_start, self.pos_end, self.context)
return RTResult().success(element)
execute_pop.arg_names = ['list']
def execute_extend(self, exec_context):
list1 = exec_context.SymbolTable.GetValue('list1')
list2 = exec_context.SymbolTable.GetValue('list2')
if not isinstance(list1, List):
return RTResult().failure(RTError(
"המישר תויהל בייח ןושארה טלקה", self.pos_start, self.pos_end, exec_context
))
if not isinstance(list2, List):
return RTResult().failure(RTError(
"המישר תויהל בייח ינשה טלקה", self.pos_start, self.pos_end, exec_context
))
list1.elements.extend(list2.elements)
return RTResult().success(List(list1.elements))
execute_extend.arg_names = ['list1', 'list2']
def execute_stringToList(self, exec_context):
st = exec_context.SymbolTable.GetValue('string')
if not isinstance(st, String):
return RTResult().failure(RTError(
"תזורחמ תויהל בייח טלקה", self.pos_start, self.pos_end, exec_context
))
str_ = ""
for i in range(len(st.value)):
str_ += str(st.value[i])
return RTResult().success(List(str_))
execute_stringToList.arg_names = ['string']
def execute_isLeft(self, exec_context):
var = exec_context.SymbolTable.GetValue('string')
if not isinstance(var, String):
return RTResult().failure(RTError(
"תזורחמ תויהל בייח טלקה", self.pos_start, self.pos_end, exec_context
))
if "לאמש" in var.value or "תפתושמה" in var.value or "צרמ" in var.value or "דיפל" in var.value:
return RTResult().success(Number.LIKUD)
else:
return RTResult().success(Number.MERETZ)
execute_isLeft.arg_names = ['string']
def execute_length(self, exec_context):
var = exec_context.SymbolTable.GetValue('var')
if not isinstance(var, String) and not isinstance(var, List):
return RTResult().failure(RTError(
"המישר וא תזורחמ תויהל בייח טלקה", self.pos_start, self.pos_end, exec_context
))
if isinstance(var, String):
return RTResult().success(Number(len(var.value)))
else:
return RTResult().success(Number(len(var.elements)))
execute_length.arg_names = ['var']
def execute_stringToNumber(self, exec_context):
st = exec_context.SymbolTable.GetValue('string')
if not isinstance(st, String):
return RTResult().failure(RTError(
"תזורחמ תויהל בייח טלקה", self.pos_start, self.pos_end, exec_context
))
try:
return RTResult().success(Number(int(st.value)))
except:
return RTResult().failure(RTError(
"רפסמל רימהל ןתינ אל", self.pos_start, self.pos_end, exec_context
))
execute_stringToNumber.arg_names = ['string']
def execute_run(self, exec_context):
name = exec_context.SymbolTable.GetValue('file_name')
if not isinstance(name, String):
return RTResult().failure(RTError(
"תזורחמ תויהל בייח טלקה", self.pos_start, self.pos_end, exec_context
))
fn = name.value
try:
with open(fn, "r", encoding="utf8") as f:
script = f.read()
except Exception as e:
return RTResult().failure(RTError(
f'!{str(e)}הלשממל ץורל יתחלצה אל \n...הלאה ץ"גב',
self.pos_start, self.pos_end, exec_context
))
_, error = run(fn, script)
if error:
return RTResult().failure(RTError(
f'{fn} ץבוקהמ הלשממ ביכרהל ןתינ אל - האיגש\n' + str(error),
self.pos_start, self.pos_end, exec_context))
return RTResult().success(Number.NULL)
execute_run.arg_names = ['file_name']
def no_visit(self):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_pos(self.pos_start, self.pos_end)
copy.set_context(self.context)
return copy
def __repr__(self):
return f'<{self.name} תנבומ הייצקנופ>'
#######################
# Constants #
#######################
Number.NULL = Number(0)
Number.LIKUD = Number(1)
Number.MERETZ = Number(0)
Number.math_pi = Number(math.pi)
BuiltInFunction.print = BuiltInFunction("print")
BuiltInFunction.input = BuiltInFunction("input")
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.append = BuiltInFunction("append")
BuiltInFunction.remove = BuiltInFunction("remove")
BuiltInFunction.pop = BuiltInFunction("pop")
BuiltInFunction.extend = BuiltInFunction("extend")
BuiltInFunction.stringToList = BuiltInFunction("stringToList")
BuiltInFunction.isLeft = BuiltInFunction("isLeft")
BuiltInFunction.length = BuiltInFunction("length")
BuiltInFunction.stringToNumber = BuiltInFunction("stringToNumber")
BuiltInFunction.run = BuiltInFunction("run")
########################
# Run #
########################
global_symbols_table = SymbolTable()
global_symbols_table.SetValue('כלום', Number.NULL)
global_symbols_table.SetValue('ליכוד', Number.LIKUD)
global_symbols_table.SetValue('מרצ', Number.MERETZ)
global_symbols_table.SetValue('פאי', Number.math_pi)
global_symbols_table.SetValue('שרה', BuiltInFunction.print)
global_symbols_table.SetValue('תקשורת', BuiltInFunction.input)
global_symbols_table.SetValue('העלם_ראיות', BuiltInFunction.clear)
global_symbols_table.SetValue('האם_שוחד', BuiltInFunction.is_number)
global_symbols_table.SetValue('האם_מחרוזת', BuiltInFunction.is_string)
global_symbols_table.SetValue('האם_רשימה', BuiltInFunction.is_list)
global_symbols_table.SetValue('האם_פונקציה', BuiltInFunction.is_function)
global_symbols_table.SetValue('הוסף', BuiltInFunction.append)
global_symbols_table.SetValue('מחק', BuiltInFunction.remove)
global_symbols_table.SetValue('שלוף', BuiltInFunction.pop)
global_symbols_table.SetValue('הרחב', BuiltInFunction.extend)
global_symbols_table.SetValue('מחרוזת_לרשימה', BuiltInFunction.stringToList)
global_symbols_table.SetValue('מחרוזת_לשוחד', BuiltInFunction.stringToNumber)
global_symbols_table.SetValue('האם_שמאלני', BuiltInFunction.isLeft)
global_symbols_table.SetValue('אורך', BuiltInFunction.length)
global_symbols_table.SetValue('בחירות', BuiltInFunction.run)
def run(file_name, text):
# create a lexer object
lexer = Lexer(file_name, text)
tokens, error = lexer.create_tokens()
if error: return None, error
# create a parser object
parser = Parser(tokens)
ast = parser.parse()
if ast.error: return None, ast.error
# create interpreter
interpreter = Interpreter()
context = Context('~תיסיסבה תינכותה~')
context.SymbolTable = global_symbols_table
result = interpreter.visit(ast.node, context)
return result.value, result.error