-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinypy.py
1622 lines (1419 loc) · 36.3 KB
/
tinypy.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 sys
# see C++ addBuiltIn
if not "tinypy" in sys.version:
# merge
def merge(a,b):
if isinstance(a,dict):
for k in b: a[k] = b[k]
else:
for k in b: setattr(a,k,b[k])
# number
def number(v):
if type(v) is str and v[0:2] == '0x':
v = int(v[2:],16)
return float(v)
# istype
def istype(v,t):
if t == 'string': return isinstance(v,str)
elif t == 'list': return (isinstance(v,list) or isinstance(v,tuple))
elif t == 'dict': return isinstance(v,dict)
elif t == 'number': return (isinstance(v,float) or isinstance(v,int))
raise '?'
# fpack
def fpack(v):
import struct
return struct.pack('d',v)
# loadFile
def loadFile(filename):
f = open(filename,'rb')
r = f.read()
f.close()
return r
# saveFile
def saveFile(filename,v):
f = open(filename,'wb')
f.write(v)
f.close()
OP_EOF=0
OP_ADD=1
OP_SUB=2
OP_MUL=3
OP_DIV=4
OP_POW=5
OP_BITAND=6
OP_BITOR=7
OP_CMP=8
OP_GET=9
OP_SET=10
OP_NUMBER=11
OP_STRING=12
OP_GGET=13
OP_GSET=14
OP_MOVE=15
OP_DEF=16
OP_PASS=17
OP_JUMP=18
OP_CALL=19
OP_RETURN=20
OP_IF=21
OP_DEBUG=22
OP_EQ=23
OP_LE=24
OP_LT=25
OP_DICT=26
OP_LIST=27
OP_NONE=28
OP_LEN=29
OP_POS=30
OP_PARAMS=31
OP_IGET=32
OP_FILE=33
OP_NAME=34
OP_NE=35
OP_HAS=36
OP_RAISE=37
OP_SETJMP=38
OP_MOD=39
OP_LSH=40
OP_RSH=41
OP_ITER=42
OP_DEL=43
OP_REGS=44
OP_BITXOR=45
OP_IFN=46
OP_NOT=47
OP_BITNOT = 48
# /////////////////////////////////////////////////////
def raiseError(explanation,s,i):
y,x = i
line = s.split('\n')[y-1]
p = ''
if y < 10: p += ' '
if y < 100: p += ' '
r = p + str(y) + ": " + line + "\n"
r += " "+" "*x+"^" +'\n'
raise 'error raised: '+explanation+'\n'+r
# /////////////////////////////////////////////////////
class Token:
def __init__(self,pos=(0,0),type='symbol',val=None,items=None):
self.pos,self.type,self.val,self.items=pos,type,val,items
# /////////////////////////////////////////////////////
class Tokenizer:
# __init__
def __init__(self):
self.ISYMBOLS = '`-=[];,./~!@$%^&*()+{}:<>?|'
self.SYMBOLS = [
'def','class','yield','return','pass','and','or','not','in','import',
'is','while','break','for','continue','if','else','elif','try',
'except','raise','True','False','None','global','del','from',
'-','+','*','**','/','%','<<','>>',
'-=','+=','*=','/=','=','==','!=','<','>', '|=', '&=', '^=',
'<=','>=','[',']','{','}','(',')','.',':',',',';','&','|','!', '^']
# clean
def clean(self,s):
s = s.replace('\r\n','\n')
s = s.replace('\r','\n')
return s
# doTokenize
def doTokenize(self,s):
s = self.clean(s)
class TData:
# __init__
def __init__(self):
self.y,self.yi,self.nl = 1,0,True
self.res,self.indent,self.braces = [],[0],0
def add(self,t,v): self.res.append(Token(self.f,t,v))
self.T,i,l = TData(),0,len(s)
try:
return self.do_tokenize(s,i,l)
except:
raiseError('Tokenizer.doTokenize',s,self.T.f)
# do_tokenize
def do_tokenize(self,s,i,l):
self.T.f = (self.T.y,i-self.T.yi+1)
while i < l:
c = s[i]; self.T.f = (self.T.y,i-self.T.yi+1)
if self.T.nl: self.T.nl = False; i = self.do_indent(s,i,l)
elif c == '\n': i = self.do_nl(s,i,l)
elif c in self.ISYMBOLS: i = self.do_symbol(s,i,l)
elif c >= '0' and c <= '9': i = self.do_number(s,i,l)
elif (c >= 'a' and c <= 'z') or \
(c >= 'A' and c <= 'Z') or c == '_': i = self.do_name(s,i,l)
elif c=='"' or c=="'": i = self.do_string(s,i,l)
elif c=='#': i = self.do_comment(s,i,l)
elif c == '\\' and s[i+1] == '\n':
i += 2; self.T.y,self.T.yi = self.T.y+1,i
elif c == ' ' or c == '\t': i += 1
else:
raiseError('Tokenizer.do_tokenize',s,self.T.f)
self.indent(0)
r = self.T.res; self.T = None
#for t in r:
#print (t.pos,t.type,t.val)
return r
# do_nl
def do_nl(self,s,i,l):
if not self.T.braces:
self.T.add('nl',None)
i,self.T.nl = i+1,True
self.T.y,self.T.yi = self.T.y+1,i
return i
# do_indent
def do_indent(self,s,i,l):
v = 0
while i<l:
c = s[i]
if c != ' ' and c != '\t': break
i,v = i+1,v+1
if c != '\n' and c != '#' and not self.T.braces: self.indent(v)
return i
# indent
def indent(self,v):
if v == self.T.indent[-1]: pass
elif v > self.T.indent[-1]:
self.T.indent.append(v)
self.T.add('indent',v)
elif v < self.T.indent[-1]:
n = self.T.indent.index(v)
while len(self.T.indent) > n+1:
v = self.T.indent.pop()
self.T.add('dedent',v)
# do_symbol
def do_symbol(self,s,i,l):
symbols = []
v,f,i = s[i],i,i+1
if v in self.SYMBOLS: symbols.append(v)
while i<l:
c = s[i]
if not c in self.ISYMBOLS: break
v,i = v+c,i+1
if v in self.SYMBOLS: symbols.append(v)
v = symbols.pop(); n = len(v); i = f+n
self.T.add('symbol',v)
if v in ['[','(','{']: self.T.braces += 1
if v in [']',')','}']: self.T.braces -= 1
return i
# do_number
def do_number(self,s,i,l):
v,i,c =s[i],i+1,s[i]
while i<l:
c = s[i]
if (c < '0' or c > '9') and (c < 'a' or c > 'f') and c != 'x': break
v,i = v+c,i+1
if c == '.':
v,i = v+c,i+1
while i<l:
c = s[i]
if c < '0' or c > '9': break
v,i = v+c,i+1
self.T.add('number',v)
return i
# do_name
def do_name(self,s,i,l):
v,i =s[i],i+1
while i<l:
c = s[i]
if (c < 'a' or c > 'z') and (c < 'A' or c > 'Z') and (c < '0' or c > '9') and c != '_': break
v,i = v+c,i+1
if v in self.SYMBOLS: self.T.add('symbol',v)
else: self.T.add('name',v)
return i
# do_string
def do_string(self,s,i,l):
v,q,i = '',s[i],i+1
if (l-i) >= 5 and s[i] == q and s[i+1] == q: # """
i += 2
while i<l-2:
c = s[i]
if c == q and s[i+1] == q and s[i+2] == q:
i += 3
self.T.add('string',v)
break
else:
v,i = v+c,i+1
if c == '\n': self.T.y,self.T.yi = self.T.y+1,i
else:
while i<l:
c = s[i]
if c == "\\":
i = i+1; c = s[i]
if c == "n": c = '\n'
if c == "r": c = chr(13)
if c == "t": c = "\t"
if c == "0": c = "\0"
v,i = v+c,i+1
elif c == q:
i += 1
self.T.add('string',v)
break
else:
v,i = v+c,i+1
return i
# do_comment
def do_comment(self,s,i,l):
i += 1
while i<l:
c = s[i]
if c == '\n': break
i += 1
return i
# ///////////////////////////////////////////////
class Parser:
# __init__
def __init__(self):
self.base_dmap = {
',':{'lbp':20,'bp':20,'led':self.infix_tuple},
'+':{'lbp':50,'bp':50,'led':self.infix_led},
'-':{'lbp':50,'nud':self.prefix_neg,'bp':50,'led':self.infix_led},
'not':{'lbp':35,'nud':self.prefix_nud,'bp':35,'bp':35,'led':self.infix_not },
'%':{'lbp':60,'bp':60,'led':self.infix_led},
'*':{'lbp':60,'nud':self.vargs_nud,'bp':60,'led':self.infix_led,},
'**': {'lbp':65,'nud':self.nargs_nud,'bp':65,'led':self.infix_led,},
'/':{'lbp':60,'bp':60,'led':self.infix_led},
'(':{'lbp':70,'nud':self.paren_nud,'bp':80,'led':self.call_led,},
'[':{'lbp':70,'nud':self.list_nud,'bp':80,'led':self.get_led,},
'{':{'lbp':0,'nud':self.dict_nud,},
'.':{'lbp':80,'bp':80,'led':self.dot_led,'type':'get',},
'break':{'lbp':0,'nud':self.itself,'type':'break'},
'pass':{'lbp':0,'nud':self.itself,'type':'pass'},
'continue':{'lbp':0,'nud':self.itself,'type':'continue'},
'eof':{'lbp':0,'type':'eof','val':'eof'},
'def':{'lbp':0,'nud':self.def_nud,'type':'def',},
'while':{'lbp':0,'nud':self.while_nud,'type':'while',},
'for':{'lbp':0,'nud':self.for_nud,'type':'for',},
'try':{'lbp':0,'nud':self.try_nud,'type':'try',},
'if':{'lbp':0,'nud':self.if_nud,'type':'if',},
'class':{'lbp':0,'nud':self.class_nud,'type':'class',},
'raise':{'lbp':0,'nud':self.prefix_nud0,'type':'raise','bp':20,},
'return':{'lbp':0,'nud':self.prefix_nud0,'type':'return','bp':10,},
'import':{'lbp':0,'nud':self.prefix_nuds,'type':'import','bp':20,},
'from':{'lbp':0,'nud':self.from_nud,'type':'from','bp':20,},
'del':{'lbp':0,'nud':self.prefix_nuds,'type':'del','bp':10,},
'global':{'lbp':0,'nud':self.prefix_nuds,'type':'globals','bp':20,},
'=':{'lbp':10,'bp':9,'led':self.infix_led,},
}
self.i_infix(40,self.infix_led,'<','>','<=','>=','!=','==')
self.i_infix(40,self.infix_is,'is','in')
self.i_infix(10,self.infix_led,'+=','-=','*=','/=', '&=', '|=', '^=')
self.i_infix(32,self.infix_led,'and','&')
self.i_infix(31,self.infix_led,'^')
self.i_infix(30,self.infix_led,'or','|')
self.i_infix(36,self.infix_led,'<<','>>')
self.i_terms(')','}',']',';',':','nl','elif','else','True','False','None','name','string','number','indent','dedent','except')
self.base_dmap['nl']['val'] = 'nl'
# check
def check(self,t,*vs):
if vs[0] == None: return True
if t.type in vs: return True
if t.type == 'symbol' and t.val in vs: return True
return False
# tweak
def tweak(self,k,v):
self.stack.append((k,self.dmap[k]))
if v:
self.dmap[k] = self.omap[k]
else:
self.dmap[k] = {'lbp':0,'nud':self.itself}
# restore
def restore(self):
k,v = self.stack.pop()
self.dmap[k] = v
# raiseError
def raiseError(self,ctx,t):
raiseError("Parse.raiseError " + ctx,self.s,t.pos)
# nud
def nud(self,t):
return t.nud(t)
# led
def led(self,t,left):
return t.led(t,left)
# get_lbp
def get_lbp(self,t):
return t.lbp
# get_items
def get_items(self,t):
return t.items
# terminal
def terminal(self):
if self._terminal > 1:
self.raiseError('invalid statement',self.token)
# self.expression
def expression(self,rbp):
t = self.token
self.advance()
left = self.nud(t)
while rbp < self.get_lbp(self.token):
t = self.token
self.advance()
left = self.led(t,left)
return left
# infix_led
def infix_led(self,t,left):
t.items = [left,self.expression(t.bp)]
return t
# infix_is
def infix_is(self,t,left):
if self.check(self.token,'not'):
t.val = 'isnot'
self.advance('not')
t.items = [left,self.expression(t.bp)]
return t
# infix_not
def infix_not(self,t,left):
self.advance('in')
t.val = 'notin'
t.items = [left,self.expression(t.bp)]
return t
# infix_tuple
def infix_tuple(self,t,left):
r = self.expression(t.bp)
if left.val == ',':
left.items.append(r)
return left
t.items = [left,r]
t.type = 'tuple'
return t
# lst
def lst(self,t):
if t == None: return []
if self.check(t,',','tuple','statements'):
return self.get_items(t)
return [t]
# ilst
def ilst(self,typ,t):
return Token(t.pos,typ,typ,self.lst(t))
# call_led
def call_led(self,t,left):
r = Token(t.pos,'call','$',[left])
while not self.check(self.token,')'):
self.tweak(',',0)
r.items.append(self.expression(0))
if self.token.val == ',': self.advance(',')
self.restore()
self.advance(")")
return r
# get_led
def get_led(self,t,left):
r = Token(t.pos,'get','.',[left])
items = [left]
more = False
while not self.check(self.token,']'):
more = False
if self.check(self.token,':'):
items.append(Token(self.token.pos,'symbol','None'))
else:
items.append(self.expression(0))
if self.check(self.token,':'):
self.advance(':')
more = True
if more:
items.append(Token(self.token.pos,'symbol','None'))
if len(items) > 2:
items = [left,Token(t.pos,'slice',':',items[1:])]
r.items = items
self.advance("]")
return r
# dot_led
def dot_led(self,t,left):
r = self.expression(t.bp)
r.type = 'string'
t.items = [left,r]
return t
# itself
def itself(self,t):
return t
# paren_nud
def paren_nud(self,t):
self.tweak(',',1)
r = self.expression(0)
self.restore()
self.advance(')')
return r
# list_nud
def list_nud(self,t):
t.type = 'list'
t.val = '[]'
t.items = []
next = self.token
self.tweak(',',0)
while not self.check(self.token,'for',']'):
r = self.expression(0)
t.items.append(r)
if self.token.val == ',': self.advance(',')
if self.check(self.token,'for'):
t.type = 'comp'
self.advance('for')
self.tweak('in',0)
t.items.append(self.expression(0))
self.advance('in')
t.items.append(self.expression(0))
self.restore()
self.restore()
self.advance(']')
return t
# dict_nud
def dict_nud(self,t):
t.type='dict'
t.val = '{}'
t.items = []
self.tweak(',',0)
while not self.check(self.token,'}'):
t.items.append(self.expression(0))
if self.check(self.token,':',','): self.advance()
self.restore()
self.advance('}')
return t
# advance
def advance(self,val=None):
if not self.check(self.token,val):
self.raiseError('expected '+val,self.token)
if self.pos < len(self.tokens):
t = self.tokens[self.pos]
self.pos += 1
else:
t = Token((0,0),'eof','eof')
self.token = self.do(t)
self._terminal += 1
if self.check(self.token,'nl','eof',';','dedent'):
self._terminal = 0
return t
# iblock
def iblock(self,items):
while self.check(self.token,'nl',';'): self.advance()
while True:
items.append(self.expression(0))
self.terminal()
while self.check(self.token,'nl',';'): self.advance()
if self.check(self.token,'dedent','eof'): break
# block
def block(self):
items = []
tok = self.token
if self.check(self.token,'nl'):
while self.check(self.token,'nl'): self.advance()
self.advance('indent')
self.iblock(items)
self.advance('dedent')
else:
items.append(self.expression(0))
while self.check(self.token,';'):
self.advance(';')
items.append(self.expression(0))
self.terminal()
while self.check(self.token,'nl'): self.advance()
if len(items) > 1:
return Token(tok.pos,'statements',';',items)
return items.pop()
# def_nud
def def_nud(self,t):
items = t.items = []
items.append(self.token); self.advance()
self.advance('(')
r = Token(t.pos,'symbol','():',[])
items.append(r)
while not self.check(self.token,')'):
self.tweak(',',0)
r.items.append(self.expression(0))
if self.check(self.token,','): self.advance(',')
self.restore()
self.advance(')')
self.advance(':')
items.append(self.block())
return t
# while_nud
def while_nud(self,t):
items = t.items = []
items.append(self.expression(0))
self.advance(':')
items.append(self.block())
return t
# class_nud
def class_nud(self,t):
items = t.items = []
items.append(self.expression(0))
self.advance(':')
items.append(self.ilst('methods',self.block()))
return t
# from_nud
def from_nud(self,t):
items = t.items = []
items.append(self.expression(0))
self.advance('import')
items.append(self.expression(0))
return t
# for_nud
def for_nud(self,t):
items = t.items = []
self.tweak('in',0)
items.append(self.expression(0))
self.advance('in')
items.append(self.expression(0))
self.restore()
self.advance(':')
items.append(self.block())
return t
# if_nud
def if_nud(self,t):
items = t.items = []
a = self.expression(0)
self.advance(':')
b = self.block()
items.append(Token(t.pos,'elif','elif',[a,b]))
while self.check(self.token,'elif'):
tok = self.token
self.advance('elif')
a = self.expression(0)
self.advance(':')
b = self.block()
items.append(Token(tok.pos,'elif','elif',[a,b]))
if self.check(self.token,'else'):
tok = self.token
self.advance('else')
self.advance(':')
b = self.block()
items.append(Token(tok.pos,'else','else',[b]))
return t
# try_nud
def try_nud(self,t):
items = t.items = []
self.advance(':')
b = self.block()
items.append(b)
while self.check(self.token,'except'):
tok = self.token
self.advance('except')
if not self.check(self.token,':'): a = self.expression(0)
else: a = Token(tok.pos,'symbol','None')
self.advance(':')
b = self.block()
items.append(Token(tok.pos,'except','except',[a,b]))
return t
# prefix_nud
def prefix_nud(self,t):
bp = t.bp
t.items = [self.expression(bp)]
return t
# prefix_nud0
def prefix_nud0(self,t):
if self.check(self.token,'nl',';','eof','dedent'): return t
return self.prefix_nud(t)
# prefix_nuds
def prefix_nuds(self,t):
r = self.expression(0)
return self.ilst(t.type,r)
# prefix_neg
def prefix_neg(self,t):
r = self.expression(50)
if r.type == 'number':
r.val = str(-float(r.val))
return r
t.items = [Token(t.pos,'number','0'),r]
return t
# vargs_nud
def vargs_nud(self,t):
r = self.prefix_nud(t)
t.type = 'args'
t.val = '*'
return t
# nargs_nud
def nargs_nud(self,t):
r = self.prefix_nud(t)
t.type = 'nargs'
t.val = '**'
return t
# i_infix
def i_infix(self,bp,led,*vs):
for v in vs:
self.base_dmap[v] = {'lbp':bp,'bp':bp,'led':led}
# i_terms
def i_terms(self,*vs):
for v in vs:
self.base_dmap[v] = {'lbp':0,'nud':self.itself}
# gmap
def gmap(self,t,v):
if v not in self.dmap:
self.raiseError('unknown "%s"'%v,t)
return self.dmap[v]
# do
def do(self,t):
if t.type == 'symbol': r = self.gmap(t,t.val)
else: r = self.gmap(t,t.type)
merge(t,r)
return t
# do_module
def do_module(self):
tok = self.token
items = []
self.iblock(items)
self.advance('eof')
if len(items) > 1:
return Token(tok.pos,'statements',';',items)
return items.pop()
# cpy
def cpy(self,d):
r = {}
for k in d: r[k] = d[k]
return r
# doParse
def doParse(self,s,tokens):
tokenizer=Tokenizer()
s = tokenizer.clean(s)
self.s = s
self.tokens = tokens
self.pos = 0
self.token = None
self.stack = []
self._terminal = 0
self.omap = self.cpy(self.base_dmap)
self.dmap = self.cpy(self.base_dmap)
self.advance()
r = self.do_module()
return r
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Encoder:
# __init__
def __init__(self):
self.fmap = {
'module':self.do_module,
'statements':self.do_statements,
'def':self.do_def,
'return':self.do_return,
'while':self.do_while,
'if':self.do_if,
'break':self.do_break,
'pass':self.do_pass,
'continue':self.do_continue,
'for':self.do_for,
'class':self.do_class,
'raise':self.do_raise,
'try':self.do_try,
'import':self.do_import,
'globals':self.do_globals,
'del':self.do_del,
'from':self.do_from,
}
self.rmap = {
'list':self.do_list,
'tuple':self.do_list,
'dict':self.do_dict,
'slice':self.do_list,
'comp':self.do_comp,
'name':self.do_name,
'symbol':self.do_symbol,
'number':self.do_number,
'string':self.do_string,
'get':self.do_get,
'call':self.do_call,
'reg':self.do_reg,
}
# insert
def insert(self,v):
D.out.append(v)
# begin
def begin(self,gbl=False):
if len(D.stack):
D.stack.append((D.vars,D.r2n,D.n2r,D._tmpi,D.mreg,D.snum,D._globals,D.lineno,D.globals,D.rglobals,D.cregs,D.tmpc))
else:
D.stack.append(None)
D.vars= []
D.r2n= {}
D.n2r= {}
D._tmpi= 0
D.mreg= 0
D.snum= str(D._scopei)
D._globals= gbl
D.lineno= -1
D.globals= []
D.rglobals= []
D.cregs = ['regs']
D.tmpc = 0
D._scopei += 1
self.insert(D.cregs)
# end
def end(self):
D.cregs.append(D.mreg)
self.do_code(OP_EOF)
if D.tmpc != 0:
print("Warning:\nencode.py contains a register leak\n")
if len(D.stack) > 1:
D.vars,D.r2n,D.n2r,D._tmpi,D.mreg,D.snum,D._globals,D.lineno,D.globals,D.rglobals,D.cregs,D.tmpc = D.stack.pop()
else: D.stack.pop()
# write
def write(self,v):
if istype(v,'list'):
self.insert(v)
return
for n in range(0,len(v),4):
self.insert(('data',v[n:n+4]))
# setpos
def setpos(self,v):
line,x = v
if line == D.lineno: return
text = D.lines[line-1]
D.lineno = line
val = text + "\0"*(4-len(text)%4)
self.code_16(OP_POS,len(val)/4,line)
self.write(val)
# do_code
def do_code(self,i,a=0,b=0,c=0):
if not istype(i,'number'): raise
if not istype(a,'number'): raise
if not istype(b,'number'): raise
if not istype(c,'number'): raise
self.write(('code',i,a,b,c))
# code_16
def code_16(self,i,a,b):
if b < 0: b += 0x8000
self.do_code(i,a,(b&0xff00)>>8,(b&0xff)>>0)
# get_code16
def get_code16(self,i,a,b):
return ('code',i,a,(b&0xff00)>>8,(b&0xff)>>0)
# _do_string
def _do_string(self,v,r=None):
r = self.get_tmp(r)
val = v + "\0"*(4-len(v)%4)
self.code_16(OP_STRING,r,len(v))
self.write(val)
return r
# do_import
def do_import(self,t):
for mod in t.items:
mod.type = 'string'
v = self.do_call(Token(t.pos,'call',None,[Token(t.pos,'name','import'),mod]))
mod.type = 'name'
self.do_set_ctx(mod,Token(t.pos,'reg',v))
# do_from
def do_from(self,t):
mod = t.items[0]
mod.type = 'string'
v = self.do(Token(t.pos,'call',None,[
Token(t.pos,'name','import'),
mod]))
item = t.items[1]
if item.val == '*':
self.free_tmp(self.do(Token(t.pos,'call',None,[
Token(t.pos,'name','merge'),
Token(t.pos,'name','__dict__'),
Token(t.pos,'reg',v)]))) #REG
else:
item.type = 'string'
self.free_tmp(self.do_set_ctx(
Token(t.pos,'get',None,[ Token(t.pos,'name','__dict__'),item]),
Token(t.pos,'get',None,[ Token(t.pos,'reg',v),item])
)) #REG
# do_globals
def do_globals(self,t):
for t in t.items:
if t.val not in D.globals:
D.globals.append(t.val)
# do_del
def do_del(self,tt):
for t in tt.items:
r = self.do(t.items[0])
r2 = self.do(t.items[1])
self.do_code(OP_DEL,r,r2)
self.free_tmp(r); self.free_tmp(r2) #REG
# do_call
def do_call(self,t,r=None):
r = self.get_tmp(r)
items = t.items
fnc = self.do(items[0])
a,b,c,d = self.p_filter(t.items[1:])
e = None
if len(b) != 0 or d != None:
e = self.do(Token(t.pos,'dict',None,[])); self.un_tmp(e);
for p in b:
p.items[0].type = 'string'
t1,t2 = self.do(p.items[0]),self.do(p.items[1])
self.do_code(OP_SET,e,t1,t2)
self.free_tmp(t1); self.free_tmp(t2) #REG
if d: self.free_tmp(self.do(Token(t.pos,'call',None,[Token(t.pos,'name','merge'),Token(t.pos,'reg',e),d.items[0]]))) #REG
self.manage_seq(OP_PARAMS,r,a)
if c != None:
t1,t2 = self._do_string('*'),self.do(c.items[0])
self.do_code(OP_SET,r,t1,t2)
self.free_tmp(t1); self.free_tmp(t2) #REG
if e != None:
t1 = self._do_none()
self.do_code(OP_SET,r,t1,e)
self.free_tmp(t1) #REG
self.do_code(OP_CALL,r,fnc,r)
self.free_tmp(fnc) #REG
return r
# do_name
def do_name(self,t,r=None):
if t.val in D.vars:
return self.do_local(t,r)
if t.val not in D.rglobals:
D.rglobals.append(t.val)
r = self.get_tmp(r)
c = self.do_string(t)
self.do_code(OP_GGET,r,c)
self.free_tmp(c)
return r
# do_local
def do_local(self,t,r=None):
if t.val in D.rglobals:
D.error = True
raiseError('Encoder.do_local',D.source_code,t.pos)
if t.val not in D.vars:
D.vars.append(t.val)
return self.get_reg(t.val)
# do_def
def do_def(self,tok,kls=None):
items = tok.items
t = self.get_tag()
rf = self.do_function(t,'end')
self.begin()
self.setpos(tok.pos)
r = self.do_local(Token(tok.pos,'name','__params'))
self.do_info(items[0].val)
a,b,c,d = self.p_filter(items[1].items)
for p in a:
v = self.do_local(p)
tmp = self._do_none()
self.do_code(OP_GET,v,r,tmp)
self.free_tmp(tmp) #REG
for p in b:
v = self.do_local(p.items[0])
self.do(p.items[1],v)
tmp = self._do_none()
self.do_code(OP_IGET,v,r,tmp)
self.free_tmp(tmp) #REG
if c != None: