-
Notifications
You must be signed in to change notification settings - Fork 0
/
cantonese.py
3379 lines (2868 loc) · 104 KB
/
cantonese.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
"""
Created at 2021/1/16 16:23
Last update at 2021/6/6 9:11
The interpreter for Cantonese
"""
import cmd
import re
import sys
import os
import argparse
# 施工中... 请戴好安全帽
from enum import Enum, unique
from collections import namedtuple
import six
class can_env(object):
_env = {}
def add(self, func, name, n_args) -> None:
self._env[name] = [func, n_args]
def Cantonesetype(args):
var = args[0]
print(type(var))
return type(var)
def CantoneseInput(args):
assert len(args) == 1
return input(args[0])
Env = can_env()
Env.add(Cantonesetype, "type", 1)
Env.add(CantoneseInput, "input", 1)
@unique
class OpCode(Enum):
OP_LOAD_CONST = 0
OP_POP_TOP = 1
OP_PRINT_ITEM = 2
class Instruction(object):
def __init__(self, index, opcode, args) -> None:
self.index = index
self.opcode = opcode
self.args = args
def get_opcode(self):
return self.opcode
def get_args(self):
return self.args
def get_idx(self):
return self.index
def set_args(self, args):
self.args = args
def __str__(self) -> str:
return str(self.index) + ' ' + self.opcode + ' ' + \
str(self.args)
class Arithmetic(object):
def mul(a, b):
return a * b
def div(a, b):
return a / b
def fdiv(a, b):
return a // b
def mod(a, b):
return a % b
def add(a, b):
return a + b
def sub(a, b):
return a - b
def getitem(a, b):
return a[b]
def lshift(a, b):
return a << b
def rshift(a, b):
return a >> b
def and_(a, b):
return a & b
def xor(a, b):
return a ^ b
def or_(a, b):
return a | b
def pos(a):
return +a
def neg(a):
return -a
def not_(a):
return not a
def invert(a):
return ~a
BINARY_OPERATORS = {
'POWER': pow, # a ** b
'MULTIPLY': Arithmetic.mul, # a * b
'DIVIDE': Arithmetic.div, # a / b
'FLOOR_DIVIDE': Arithmetic.fdiv, # a // b
'MODULO': Arithmetic.mod, # a % b
'ADD': Arithmetic.add, # a + b
'SUBTRACT': Arithmetic.sub, # a - b
'SUBSCR': Arithmetic.getitem, # a[b]
'LSHIFT': Arithmetic.lshift, # a << b
'RSHIFT': Arithmetic.rshift, # a >> b
'AND': Arithmetic.and_, # a & b
'XOR': Arithmetic.xor, # a ^ b
'OR': Arithmetic.or_, # a | b
}
UNARY_OPERATORS = {
'POSITIVE': Arithmetic.pos, # +a
'NEGATIVE': Arithmetic.neg, # -a
'NOT': Arithmetic.not_, # not a
'CONVERT': repr, # str(a)
'INVERT': Arithmetic.invert, # ~ a
}
class CanBlock(object):
def __init__(self, _type, handler, level) -> None:
self.type = _type
self.handler = handler
self.level = level
class Code(object):
def __init__(self) -> None:
self.co_argcount = None
self.co_nlocals = None
self.co_stacksize = None
self.co_code = None
self.co_consts = None
self.co_names = None
self.co_varnames = None
self.co_filename = None
self.co_name = None
self.co_firstlineno = None
self.co_lnotab = None
self.ins_lst = []
self.version = None
class CanThreadPool(object):
def __init__(self) -> None:
self._break = None
self._raise = None
self._return = None
class CanState(object):
def __init__(self, code_obj) -> None:
self.code_obj = code_obj
self.ThreadState = ThreadState()
self.objs = []
CASE_ERROR = 0x0002
CASE_RAISE = 0x0004
CASE_RETURN = 0x0008
CASE_BREAK = 0x0010
def op_run(self, opname, arg):
op_func = getattr(self, opname, None)
if not op_func:
print("OpCode {} not defined".format(opname))
return
else:
return op_func(arg) if arg != None else op_func()
def parse(self):
co_code = self.code_obj.ins_lst[self.object.lasti]
self.object.lasti += 1
return co_code.get_opcode(), co_code.get_args()
def _run(self) -> None:
self.object = CanObject(thread_state = self.ThreadState,
_code = self.code_obj,
_globals = {"唔啱" : False, "啱" : True},
_locals = {})
self.object.lasti += 1
pool = CanThreadPool()
while True:
opname, arg = self.parse()
ret = self.op_run(opname, arg)
if ret == "0":
print("return value:{}\n".format(ret))
break
if isinstance(ret, int) and ret == self.CASE_BREAK:
pool._break = ""
break
if isinstance(ret, list) and ret[0] == self.CASE_ERROR:
raise ret[1]
def get_const(self, index : int):
return self.object._code.co_consts[index]
def get_name(self, index : int):
return self.object._code.co_names[index]
def get_top(self):
return self.object.stack[-1]
def set_top(self, value) -> None:
self.object.stack[-1] = value
def push(self, value) -> None:
self.object.stack.append(value)
def push_object(self, obj) -> None:
self.objects.append(self.object)
self.object = obj
def pop(self):
return self.object.stack.pop()
def popn(self, n):
if n:
ret = self.object.stack[-n : ]
self.object.stack[-n : ] = []
return ret
else:
return []
def jumpto(self, value):
self.object.lasti = value
def jumpby(self, value):
self.object.lasti += value
def stack_level(self):
return len(self.object.stack)
def set_block(self, object, b_type, b_handler, b_level):
block = CanBlock(b_type, b_handler, b_level)
object.block_stack.append(block)
def pop_block(self, object):
return object.block_stack.pop()
def unaryOperator(self, op):
val = self.top()
self.set_top(UNARY_OPERATORS[op](val))
def binaryOperator(self, op):
x, y = self.popn(2)
self.push(BINARY_OPERATORS[op](x, y))
def inplaceOperator(self, op):
y = self.pop()
x = self.top()
self.set_top(self.BINARY_OPERATORS[op](x, y))
def OP_POP_TOP(self):
self.pop()
def OP_NOP(self):
pass
def OP_PUSH_TOP(self):
self.push(self.get_top())
def OP_LOAD_CONST(self, val):
self.push(eval(val[1], self.object._globals, self.object._locals))
def OP_LOAD_NAME(self, name):
obj = self.object
if name in obj._locals:
val = obj._locals[name]
elif name in obj._globals:
val = obj._globals[name]
elif name in obj._builtins:
val = obj._builtins[name]
else:
raise NameError("name %s is not defined.".foramt(name))
self.push(val)
def OP_LOAD_BUITIN_FUNC(self, _func):
self.push(_func)
def OP_NEW_NAME(self, name):
val = self.pop()
self.object._locals[name] = val
def OP_PRINT_ITEM(self):
val = self.pop()
print(val)
def OP_RETURN(self):
return "0"
def OP_POP_JMP_IF_FALSE(self, idx):
val = self.pop()
if not val:
self.jumpto(idx)
def OP_POP_JMP_IF_TRUE(self, idx):
val = self.pop()
if val:
self.jumpto(idx)
def OP_END(self):
pass
def OP_JMP_FORWARD(self, addr):
self.jumpby(addr)
def OP_SETUP_LOOP(self, dest):
self.set_block(self.object, 'loop', self.object.lasti + dest, self.stack_level())
def OP_GET_ITER(self):
val = self.get_top()
val_iter = iter(val)
if val_iter:
self.set_top(val_iter)
else:
self.pop()
def OP_FOR_ITER(self, dest):
it = self.top()
try:
val = next(it)
self.push(val)
except StopIteration:
self.pop()
self.jumpby(dest)
def OP_JMP_ABSOLUTE(self, dest):
self.jumpto(dest)
def OP_SETUP_LIST(self, num):
ret = []
for i in range(num):
ret.insert(0, self.pop())
self.push(ret)
def OP_SETUP_LOOP(self, dest) -> None:
self.set_block(self.object, 'loop', self.object.lasti + dest, self.stack_level)
def OP_SETUP_FINALLY(self, dest) -> None:
self.set_block(self.object, 'finally', self.object.lasti + dest, self.stack_level)
def OP_SETUP_EXCEPT(self, dest) -> None:
self.set_block(self.object, 'except', self.object.lasti + dest, self.stack_level)
def OP_POP_BLOCK(self):
block = self.pop_block(self.object)
while self.stack_level() > block.b_level:
self.pop()
def OP_BREAK_LOOP(self):
return self.CASE_BREAK
def OP_CALL_FUNC(self, func):
arg = self.popn(src.env.Env.Env._env[func][1])
x = src.env.Env.Env._env[func][0](arg)
self.push(x)
def OP_FOR_LOOP(self, _iter, _from, _to, _code):
for _iter[1] in range(_from, _to):
self.eval_object(_code)
def OP_RAISE(self, Error):
return [self.CASE_ERROR, Error]
class CanObject(object):
def __init__(self, thread_state, _code, _globals, _locals) -> None:
self.last_stack = thread_state.stack
self._code = _code
self._globals = _globals
self._locals = _locals
self._builtins = None
self.stack = []
self.lasti = -1
self.block_stack = []
if self.last_stack == None:
self._builtins = __builtins__
else:
self._builtins = self.last_stack._builtins
class Function(object):
def __init__(self, code, arg_default):
self.func_code = code
self.globals = globals
self.arg_default = arg_default
# self.closure = closure
# self.vm = vm
# TODO: 支持闭包
# if closure:
# pass
class ThreadState(object):
def __init__(self):
self.stack = None
import re, sys, traceback
class 层信息:
def __init__(self, 行号, 有啲咩, 文件名):
self.行号, self.有啲咩, self.文件名 = 行号, 有啲咩, 文件名
def 提取(各层):
各行 = []
for 层号 in range(len(各层) - 1, -1, -1):
层 = 各层[层号]
文件名 = 层.filename
各行.append(层信息(层.lineno, 层.line, 文件名))
return 各行
def 濑啲咩嘢(错误):
exc_type, exc_value, 回溯信息 = sys.exc_info()
各层 = traceback.extract_tb(回溯信息)
各行 = []
行信息 = 提取(各层)
类型 = 错误.__class__.__name__
咩回事 = str(错误)
if len(行信息) > 0:
各行.append(话畀你知(类型, 咩回事))
return 各行
def 话畀你知(类型, 咩回事):
if 类型 == 'NameError':
return re.sub(r"name '(.*)' is not defined", r"唔知‘\1’係咩", 咩回事)
return 类型 + ":" + 咩回事
class Compile(object):
def __init__(self, ast, target, path) -> None:
self.ast = ast
self.target = target
self.path = path
self.TO_JS_CODE = ""
self.TO_C_CODE = ""
self.TO_ASM_CODE = ""
if self.target == "js":
self.run_js(self.ast)
if self.target == "c":
self.run_c(self.ast)
if self.target == "asm":
self.run_asm(self.ast)
def ret(self):
if self.target == "js":
return self.TO_JS_CODE, self.path[ : len(self.path) - len('cantonese')] + 'js'
if self.target == "c":
return self.TO_C_CODE, self.path[ : len(self.path) - len('cantonese')] + 'c'
if self.target == "asm":
return self.TO_ASM_CODE, self.path[ : len(self.path) - len('cantonese')] + 'S'
# TODO
def eval_expr(self, expr):
return expr
def run_asm(self, Nodes : list, label = '', path = '') -> None:
for node in Nodes:
pass
def run_c(self, Nodes : list, label = '', path = '') -> None:
for node in Nodes:
if node[0] == "node_print":
pass
def run_js(self, Nodes : list, label = '', path = '') -> None:
for node in Nodes:
if node[0] == "node_print":
self.TO_JS_CODE += "console.log(" + self.eval_expr(node[1][1]) + ");\n"
if node[0] == "node_exit":
self.TO_JS_CODE += "process.exit();\n"
if node[0] == "node_let":
self.TO_JS_CODE += node[1][1] + " = " + self.eval_expr(node[2][1]) + ";\n"
if node[0] == "node_if":
self.TO_JS_CODE += "if (" + self.eval_expr(node[1][1]) + ") {\n"
self.run_js(node[2])
self.TO_JS_CODE += "}"
if node[0] == "node_elif":
self.TO_JS_CODE += "else if (" + self.eval_expr(node[1][1]) + ") {\n"
self.run_js(node[2])
self.TO_JS_CODE += "}"
if node[0] == "node_else":
self.TO_JS_CODE += "else{"
self.run_js(node[1])
self.TO_JS_CODE += "}"
if node[0] == "node_call":
self.TO_JS_CODE += node[1][1] + ";\n"
if node[0] == "node_fundef":
if node[2] == 'None':
self.TO_JS_CODE += "function " + node[1][1] + "() {\n"
self.run_js(node[3])
self.TO_JS_CODE += "}\n"
else:
self.TO_JS_CODE += "function " + node[1][1] + "(" + node[2][1] + ") {\n"
self.run_js(node[3])
self.TO_JS_CODE += "}\n"
"""
Get the Cantonese Token List
"""
class lexer(object):
def __init__(self, code, keywords):
self.code = code
self.keywords = keywords
self.line = 1
self.re_new_line = re.compile(r"\r\n|\n\r|\n|\r")
self.re_number = r"^0[xX][0-9a-fA-F]*(\.[0-9a-fA-F]*)?([pP][+\-]?[0-9]+)?|^[0-9]*(\.[0-9]*)?([eE][+\-]?[0-9]+)?"
self.re_id = r"^[_\d\w]+|^[\u4e00-\u9fa5]+"
self.re_str = r"(?s)(^'(\\\\|\\'|\\\n|\\z\s*|[^'\n])*')|(^\"(\\\\|\\\"|\\\n|\\z\s*|[^\"\n])*\")"
self.re_expr = r"[|](.*?)[|]"
self.re_callfunc = r"[&](.*?)[)]"
self.op = r'(?P<op>(相加){1}|(加){1}|(减){1}|(乘){1}|(整除){1}|(除){1}|(余){1}|(异或){1}|(取反){1}|(左移){1}|(右移){1}'\
r'(与){1}(或者){1}|(或){1}|(系){1})|(同埋){1}|(自己嘅){1}|(比唔上){1}|(喺){1}'
self.op_get_code = re.findall(re.compile(r'[(](.*?)[)]', re.S), self.op[5 : ])
self.op_gen_code = ["矩阵.matrix_addition", "+", "-", "*", "//", "/", "%", "^", "~", "<<", ">>",
"&", "or", "|", "==", "and", "self.", '<', 'in']
self.build_in_funcs = r'(?P<build_in_funcs>(瞓){1}|(加啲){1}|(摞走){1}|(嘅长度){1}|(阵先){1}|' \
r'(畀你){1}|(散水){1})'
self.bif_get_code = re.findall(re.compile(r'[(](.*?)[)]', re.S), self.build_in_funcs[19 :])
self.bif_gen_code = ["sleep", "append", "remove", ".__len__()", "2", "input", "clear"]
def make_rep(self, list1 : list, list2 : list) -> list:
assert len(list1) == len(list2)
ret = []
for i in range(len(list1)):
ret.append([list1[i], list2[i]])
return ret
def trans(self, code : str, rep : str) -> str:
p = re.match(r'\|(.*)同(.*)有几衬\|', code, re.M|re.I)
if p:
code = " corr(" + p.group(1) +", " + p.group(2) + ") "
for r in rep:
code = code.replace(r[0], r[1])
return code
def next(self, n):
self.code = self.code[n:]
def check(self, s):
return self.code.startswith(s)
@staticmethod
def is_white_space(c):
return c in ('\t', '\n', '\v', '\f', '\r', ' ')
@staticmethod
def is_new_line(c):
return c in ('\r', '\n')
@staticmethod
def isChinese(word):
for ch in word:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
def skip_space(self):
while len(self.code) > 0:
if self.check('\r\n') or self.check('\n\r'):
self.next(2)
self.line += 1
elif self.is_new_line(self.code[0]):
self.next(1)
self.line += 1
elif self.check('?') or self.check(':') or self.check(':') or self.check('?'):
self.next(1)
elif self.is_white_space(self.code[0]):
self.next(1)
else:
break
def scan(self, pattern):
m = re.match(pattern, self.code)
if m:
token = m.group()
self.next(len(token))
return token
def scan_identifier(self):
return self.scan(self.re_id)
def scan_expr(self):
return self.scan(self.re_expr)
def scan_number(self):
return self.scan(self.re_number)
def scan_callfunc(self):
return self.scan(self.re_callfunc)
def scan_short_string(self):
m = re.match(self.re_str, self.code)
if m:
s = m.group()
self.next(len(s))
return s
self.error('unfinished string')
return ''
def error(self, f, *args):
err = f.format(*args)
err = '{0}: {1}'.format(self.line, err)
raise Exception(err)
def get_token(self):
self.skip_space()
if len(self.code) == 0:
return [self.line, ['EOF', 'EOF']]
c = self.code[0]
if c == '&':
token = self.scan_callfunc() + ')'
token = self.trans(token, self.make_rep(self.bif_get_code, self.bif_gen_code))
return [self.line, ['expr', token]]
if c == '|':
token = self.scan_expr()
token = self.trans(token, self.make_rep(self.bif_get_code, self.bif_gen_code))
token = self.trans(token, self.make_rep(self.op_get_code, self.op_gen_code))
return [self.line, ['expr', token]]
if c == '-':
if self.check('->'):
self.next(2)
return [self.line, ['keyword', '->']]
if c == '$':
self.next(1)
return [self.line, ['keyword', '$']]
if c == '@':
self.next(1)
return [self.line, ['keyword', '@']]
if c == '{':
self.next(1)
return [self.line, ['keyword', '{']]
if c == '}':
self.next(1)
return [self.line, ['keyword', '}']]
if self.isChinese(c) or c == '_' or c.isalpha():
token = self.scan_identifier()
if token in self.keywords:
return [self.line, ['keywords', token]]
return [self.line, ['identifier', token]]
if c in ('\'', '"'):
return [self.line, ['string', self.scan_short_string()]]
if c == '.' or c.isdigit():
token = self.scan_number()
return [self.line, ['num', token]]
self.error("睇唔明嘅Token: " + c)
def escape(self, s):
ret = ''
while len(s) > 0:
if s[0] != '\\':
ret += s[0]
s = s[1:]
continue
if len(s) == 1:
self.error('unfinished string')
if s[1] == 'a':
ret += '\a'
s = s[2:]
continue
elif s[1] == 'b':
ret += '\b'
s = s[2:]
continue
elif s[1] == 'f':
ret += '\f'
s = s[2:]
continue
elif s[1] == 'n' or s[1] == '\n':
ret += '\n'
s = s[2:]
continue
elif s[1] == 'r':
ret += '\r'
s = s[2:]
continue
elif s[1] == 't':
ret += '\t'
s = s[2:]
continue
elif s[1] == 'v':
ret += '\v'
s = s[2:]
continue
elif s[1] == '"':
ret += '"'
s = s[2:]
continue
elif s[1] == '\'':
ret += '\''
s = s[2:]
continue
elif s[1] == '\\':
ret += '\\'
s = s[2:]
continue
def cantonese_token(code : str, keywords : str) -> list:
lex = lexer(code, keywords)
tokens = []
while True:
token = lex.get_token()
tokens.append(token)
if token[1] == ['EOF', 'EOF']:
break
return tokens
"""
AST node for the Token List
"""
def node_print_new(Node : list, arg) -> None:
"""
Node_print
|
arg
"""
Node.append(["node_print", arg])
def node_sleep_new(Node : list, arg) -> None:
"""
Node_sleep
|
arg
"""
Node.append(["node_sleep", arg])
def node_break_new(Node : list) -> None:
Node.append(["node_break"])
def node_exit_new(Node : list) -> None:
"""
Node_exit
|
arg
"""
Node.append(["node_exit"])
def node_let_new(Node : list, key ,value) -> None:
"""
Node_let
/ \
key value
"""
Node.append(["node_let", key, value])
def node_if_new(Node : list, cond, stmt) -> None:
"""
Node_if
/ \
cond stmt
"""
Node.append(["node_if", cond, stmt])
def node_elif_new(Node : list, cond, stmt) -> None:
"""
Node_elif
/ \
cond stmt
"""
Node.append(["node_elif", cond, stmt])
def node_else_new(Node : list, stmt) -> None:
"""
Node_else
|
stmt
"""
Node.append(["node_else", stmt])
def node_loop_new(Node : list, cond, stmt) -> None:
"""
Node_loop
/ \
cond stmt
"""
Node.append(["node_loop", cond, stmt])
def node_func_new(Node : list, func_name, args, body) -> None:
"""
Node_fundef
/ | \
name args body
"""
Node.append(["node_fundef", func_name, args, body])
def node_call_new(Node : list, func_name) -> None:
"""
Node_call
|
name
"""
Node.append(["node_call", func_name])
def node_build_in_func_call_new(Node : list, var, func_name, args) -> None:
"""
Node_bcall
/ \
name args
"""
Node.append(["node_bcall", var, func_name, args])
def node_import_new(Node : list, name) -> None:
"""
Node_import
|
name
"""
Node.append(["node_import", name])
def node_return_new(Node : list, v) -> None:
"""
Node_return
|
value
"""
Node.append(["node_return", v])
def node_try_new(Node : list, try_part) -> None:
"""
Node_try
|
stmt
"""
Node.append(["node_try", try_part])
def node_except_new(Node : list, _except, except_part) -> None:
"""
Node_except
/ \
exception stmt
"""
Node.append(["node_except", _except, except_part])
def node_finally_new(Node : list, finally_part) -> None:
"""
Node_finally
|
stmt
"""
Node.append(["node_finally", finally_part])
def node_raise_new(Node : list, execption) -> None:
"""
Node_raise
|
exception
"""
Node.append(["node_raise", execption])
def node_for_new(Node : list, iterating_var, sequence, stmt_part) -> None:
"""
Node_for
/ | \
iter seq stmt
"""
Node.append(["node_for", iterating_var, sequence, stmt_part])
def node_turtle_new(Node : list, instruction) -> None:
Node.append(["node_turtle", instruction])
def node_assert_new(Node : list, args) -> None:
Node.append(["node_assert", args])
def node_model_new(Node : list, model, datatest) -> None:
"""
Node_model
/ \
model dataset
"""
Node.append(["node_model", model, datatest])
def node_gettype_new(Node : list, value) -> None:
Node.append(["node_gettype", value])
def node_class_new(Node : list, name, extend, method) -> None:
"""
Node_class
/ | \
name extend method
"""
Node.append(["node_class", name, extend, method])
def node_attribute_new(Node : list, attr_list) -> None:
Node.append(["node_attr", attr_list])
def node_method_new(Node : list, name, args, stmt) -> None:
"""
Node_method
/ | \
name args stmt
"""
Node.append(["node_method", name, args, stmt])
def node_cmd_new(Node : list, cmd) -> None:
"""
Node_cmd
|
conmmand
"""
Node.append(["node_cmd", cmd])
def node_list_new(Node : list, name, list) -> None:
"""
Node_list
/ \
name list
"""
Node.append(["node_list", name, list])
def node_stack_new(Node : list, name) -> None:
"""
Node_stack
|
name
"""
Node.append(["node_stack", name])
"""
Parser for cantonese Token List
"""
class Parser(object):
def __init__(self, tokens, Node):
self.tokens = tokens
self.pos = 0
self.Node = Node
def syntax_check(self, token, tag):
if tag == "value" and self.get(0)[1] == token:
return
elif tag == "type" and self.get(0)[0] == token:
return
else:
raise "Syntax error!"
def get(self, offset, get_line = False):
if self.pos + offset >= len(self.tokens):
return ["", ""]
if get_line:
return self.tokens[self.pos + offset][0]
return self.tokens[self.pos + offset][1]
def get_value(self, token):
if token[0] == 'expr':
# If is expr, Remove the "|"
token[1] = token[1][1 : -1]
if token[0] == 'callfunc':
# If is call func, Remove the '&'
token[1] = token[1][1 :]
return token
def last(self, offset):
return self.tokens[self.pos - offset][1]
def skip(self, offset):
self.pos += offset
def match(self, name):
if self.get(0)[1] == name:
self.pos += 1