-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtpc
More file actions
executable file
·2696 lines (2398 loc) · 65.6 KB
/
tpc
File metadata and controls
executable file
·2696 lines (2398 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
## tinpy.compiler is DEPRECATED, everything is moved into this file for easy embedding ##
#from tinypy.compiler.__main__ import main
#main()
import os, sys, random
DEBUG_PARSER = True
DEBUG_ENCODER = True
NEXT = 169
## from encode.py ##
try:
## scrambled interp codes ##
from tpython_interpreter_codes_gen import *
print('using external interp codes imported from tpython_interpreter_codes_gen.py')
except ImportError:
## default interp code order ##
print('using default interp codes')
EOF,REGS,NAME,INTEGER,NUMBER,STRING,MOVE,IF,EQ,LE,LT,GGET,GSET,ADD,SUB,MUL,DIV,CMP,MGET,GET,SET,NE,NOT,IFN,ITER,HAS,IGET,DEL,IFACE,DICT,LIST,PARAMS,LEN,JUMP,SETJMP,CALL,DEF,RETURN,RAISE,NONE,MOD,LSH,RSH,POW,BITAND,BITOR,BITNOT,BITXOR,PASS,FILE,DEBUG,LINE = range(52)
class DState:
def __init__(self,code,fname):
self.imports = []
self.function_stack = []
self.class_stack = []
self.classes = {}
self.fast_meth_defs = {}
self.in_return = False
self.strings256 = [
'__name__',
'__file__',
'__dict__',
'__call__',
'__new__',
'__init__',
'object',
'update',
'keys',
'values',
'version',
'modules',
'argv',
'sys',
]
print( blue('number of internal tiny atomic strings: '), len(self.strings256) )
self.globals256_funcs = {} ## func name : args names
self.globals256 = [] ## max size is 256
self.const_numbers = [] ## max size is 256
self.header = []
if '--debug' in sys.argv:
self.nopos = False
else:
self.nopos = True
self.code = code
self.fname = fname
self.lines = self.code.split('\n')
self.stack = []
self.out = [('tag','EOF')]
self._scopei = 0
self.tstack = []
self._tagi = 0
self.data = {}
self.error = False
def begin(self,gbl=False):
if len(self.stack):
self.stack.append((self.vars,self.r2n,self.n2r,self._tmpi,self.mreg,self.snum,self._globals,self.lineno,self.globals,self.rglobals,self.cregs,self.tmpc))
else:
self.stack.append(None)
self.vars = []
self.r2n = {}
self.n2r = {}
self._tmpi = 0
self.mreg = 0
self.snum = str(self._scopei)
self._globals = gbl
self.lineno = -1
self.globals = []
self.rglobals = []
self.cregs = ['regs']
self.tmpc = 0
self._scopei += 1
insert(self.cregs)
def end(self):
self.cregs.append(self.mreg)
code(EOF)
# This next line forces the encoder to
# throw an exception if any tmp regs
# were leaked within the frame
# assert(self.tmpc == 0) #REG
if self.tmpc != 0:
print("Warning:\nencode.py contains a register leak\n")
if len(self.stack) > 1:
self.vars,self.r2n,self.n2r,self._tmpi,self.mreg,self.snum,self._globals,self.lineno,self.globals,self.rglobals,self.cregs,self.tmpc = self.stack.pop()
else: self.stack.pop()
def const_number(self, n):
## returns the address of the constant number
if len(self.const_numbers) == 256:
return -1
elif n in self.const_numbers:
return self.const_numbers.index(n)
else:
self.const_numbers.append(n)
const_addr = len(self.const_numbers)-1
code(NUMBER,a=0,b=2,c=const_addr, head=True) ## b=2 means do not set a register
write(fpack(number(n)), head=True)
return const_addr
def insert(v): D.out.append(v)
def write(v, head=False):
if istype(v,'list'):
if head:
D.header.append( v )
else:
insert(v)
return
for n in range(0,len(v),4):
if head:
D.header.append(('data',v[n:n+4]))
else:
insert(('data',v[n:n+4]))
def setpos(v):
if D.nopos: return
line,x = v
if line == D.lineno: return
text = D.lines[line-1]
D.lineno = line
val = text + "\0"*(4-len(text)%4)
code_16(LINE,int(len(val)/4),line)
write(val)
def code(i,a=0,b=0,c=0, head=False):
if not istype(i,'number'):
raise RuntimeError('code.i is not a number')
if not istype(a,'number'):
if a is None:
## probably should print a warning here
a = 0
else:
raise RuntimeError('code.a is not a number: %s' %a)
if not istype(b,'number'):
raise RuntimeError('code.b is not a number: %s' %b)
if not istype(c,'number'):
raise RuntimeError('code.c is not a number: %s' %c)
write(('code',i,a,b,c), head=head)
def code_16(i,a,b):
if b < 0: b += 0x8000
code(i,a,(b&0xff00)>>8,(b&0xff)>>0)
def get_code16(i,a,b):
return ('code',i,a,(b&0xff00)>>8,(b&0xff)>>0)
STRINGS_EX = ('print', 'compile')
def _do_string(v,r=None, no_intern=False):
r = get_tmp(r)
val = v + "\0"*(4-len(v)%4)
## for the string to use the precomputed 8bit hash is must be less than 10 bytes,
## because the 8bit hash is shoved into the last byte, and second to last is the null terminator.
if len(v) <= 10 and len(D.strings256) < 256 and not no_intern and v not in STRINGS_EX:
if v not in D.strings256:
D.strings256.append(v)
code(179, r, len(v), D.strings256.index(v) )
else:
code_16(STRING,r,len(v))
write(val)
return r
def do_string(t,r=None):
if len(t.val)==1:
r = get_tmp(r)
code(178, a=r, b=ord(t.val))
return r
elif hasattr(t, 'no_intern'):
return _do_string(t.val,r, no_intern=True)
else:
return _do_string(t.val,r)
def _do_number(v,r=None):
r = get_tmp(r)
const_addr = D.const_number(v)
if const_addr != -1:
## TODO do not write number twice, this is needed until the rest of the code is refactored
code(NUMBER,a=r,b=1,c=const_addr)
else:
code(NUMBER,a=r,b=0,c=0)
write(fpack(number(v)))
return r
def _do_integer(v,r=None):
r = get_tmp(r)
#code(INTEGER,r,0,0)
#write(fpack(number(v))) ## not packed or unpacked properly? TODO FIXME
code(INTEGER, a=r, b=int(v), c=0) ## just small integers for now
return r
def do_number(t,r=None):
if '--int-type' in sys.argv and '.' not in t.val and int(t.val) >= 0 and int(t.val) <= 255:
return _do_integer(t.val,r)
else:
return _do_number(t.val,r)
def get_tag():
k = str(D._tagi)
D._tagi += 1
return k
def stack_tag():
k = get_tag()
D.tstack.append(k)
return k
def pop_tag():
D.tstack.pop()
def tag(*t):
t = D.snum+':'+':'.join([str(v) for v in t])
insert(('tag',t))
def jump(*t):
t = D.snum+':'+':'.join([str(v) for v in t])
insert(('jump',t))
def setjmp(*t):
t = D.snum+':'+':'.join([str(v) for v in t])
insert(('setjmp',t))
def fnc(*t):
t = D.snum+':'+':'.join([str(v) for v in t])
r = get_reg(t)
insert(('fnc',r,t))
return r
def map_tags():
tags = {}
out = []
n = 0
for item in D.header + D.out:
if item[0] == 'tag':
tags[item[1]] = n
continue
if item[0] == 'regs':
out.append(get_code16(REGS,item[1],0))
n += 1
continue
out.append(item)
n += 1
for n in range(0,len(out)):
item = out[n]
if item[0] == 'jump':
out[n] = get_code16(JUMP,0,tags[item[1]]-n)
elif item[0] == 'setjmp':
out[n] = get_code16(SETJMP,0,tags[item[1]]-n)
elif item[0] == 'fnc':
out[n] = get_code16(DEF,item[1],tags[item[2]]-n)
for n in range(0,len(out)):
item = out[n]
if item[0] == 'data':
out[n] = item[1]
elif item[0] == 'code':
i,a,b,c = item[1:]
out[n] = chr(i)+chr(a)+chr(b)+chr(c)
else:
raise str(('huh?',item))
if len(out[n]) != 4:
raise ('code '+str(n)+' is wrong length '+str(len(out[n])))
D.out = out
def get_tmp(r=None):
if r != None: return r
return get_tmps(1)[0]
def get_tmps(t):
rs = alloc(t)
regs = range(rs,rs+t)
for r in regs:
set_reg(r,"$"+str(D._tmpi))
D._tmpi += 1
D.tmpc += t #REG
return regs
def alloc(t):
s = ''.join(["01"[r in D.r2n] for r in range(0,min(256,D.mreg+t))])
return s.index('0'*t)
def is_tmp(r):
if r is None: return False
return (D.r2n[r][0] == '$')
def un_tmp(r):
n = D.r2n[r]
free_reg(r)
set_reg(r,'*'+n)
def free_tmp(r):
if is_tmp(r): free_reg(r)
return r
def free_tmps(r):
for k in r: free_tmp(k)
def get_reg(n):
if n not in D.n2r:
set_reg(alloc(1),n)
return D.n2r[n]
#def get_clean_reg(n):
#if n in D.n2r: raise
#set_reg(D.mreg,n)
#return D.n2r[n]
def set_reg(r,n):
D.n2r[n] = r; D.r2n[r] = n
D.mreg = max(D.mreg,r+1)
def free_reg(r):
if is_tmp(r): D.tmpc -= 1
n = D.r2n[r]; del D.r2n[r]; del D.n2r[n]
def imanage(orig,fnc):
if orig.val in ('+=', '-=', '*=', '/=') and '--beta' in sys.argv:
print(orig)
dest = orig.items[0]
expr = orig.items[1] ## may contain sub expressions
assert len(orig.items)==2
assert isinstance( dest, Token )
if dest.type == 'name' and len(dest.val)==1:
if expr.type == 'number' and expr.val.isdigit():
b = int(expr.val)
if b > 0 and b < 256:
if orig.val == '+=':
if dest.val in D.globals:
code(92, a=ord(dest.val), b=b)
else:
if b == 1:
code(90, a=get_reg(dest.val))
else:
code(91, a=get_reg(dest.val), b=b)
return None
if dest.val in D.globals:
a = ord(dest.val)
if expr.type == 'name' and len(expr.val)==1 and expr.val in D.globals:
b = ord(expr.val)
if orig.val == '+=':
code(101, a=a, b=b)
elif orig.val == '-=':
code(102, a=a, b=b)
elif orig.val == '*=':
code(103, a=a, b=b)
elif orig.val == '/=':
code(104, a=a, b=b)
return None
elif expr.type == 'symbol':
opb, opc = expr.items
if opb.type=='name' and len(opb.val)==1 and opb.val in D.globals:
if opc.type=='name' and len(opc.val)==1 and opc.val in D.globals:
b = ord(opb.val)
c = ord(opc.val)
if orig.val == '+=':
if expr.val == '+':
code(105, a=a, b=b, c=c)
elif expr.val == '-':
code(106, a=a, b=b, c=c)
elif expr.val == '*':
code(107, a=a, b=b, c=c)
elif expr.val == '/':
code(108, a=a, b=b, c=c)
return None
items = orig.items
orig.val = orig.val[:-1]
t = Token(orig.pos,'symbol','=',[items[0],orig])
return fnc(t)
def unary(i,tb,r=None):
r = get_tmp(r)
b = do(tb)
code(i,r,b)
if r != b: free_tmp(b)
return r
def infix(i,tb,tc,r=None):
r = get_tmp(r)
b = do(tb,r)
c = do(tc)
code(i,r,b,c)
if r != b:
free_tmp(b)
free_tmp(c)
return r
def logic_infix(op, tb, tc, _r=None):
t = get_tag()
r = do(tb, _r)
if _r != r: free_tmp(_r) #REG
if op == 'and': code(IF, r)
elif op == 'or': code(IFN, r)
jump(t, 'end')
_r = r
r = do(tc, _r)
if _r != r: free_tmp(_r) #REG
tag(t, 'end')
return r
def _do_none(r=None):
r = get_tmp(r)
code(NONE,r)
return r
def do_symbol(t,r=None):
sets = ['=']
isets = ['+=','-=','*=','/=', '|=', '&=', '^=']
cmps = ['<','>','<=','>=','==','!=']
metas = {
'+':ADD,'*':MUL,'/':DIV,'**':POW,
'-':SUB,
'%':MOD,'>>':RSH,'<<':LSH,
'&':BITAND,'|':BITOR,'^':BITXOR,
}
if t.val == 'None': return _do_none(r)
if t.val == 'True':
return _do_number('1',r)
if t.val == 'False':
return _do_number('0',r)
items = t.items
if t.val in ['and','or']:
return logic_infix(t.val, items[0], items[1], r)
if t.val in isets:
return imanage(t,do_symbol)
if t.val == 'is':
if items[1].type == 'symbol' and items[1].val == 'None':
r = get_tmp(r)
b = do(items[0], r)
code(159, r, b)
if r != b:
free_tmp(b)
return r
else:
return infix(EQ,items[0],items[1],r)
if t.val == 'isnot':
if items[1].type == 'symbol' and items[1].val == 'None':
r = get_tmp(r)
b = do(items[0], r)
code(158, r, b)
if r != b:
free_tmp(b)
return r
else:
return infix(CMP,items[0],items[1],r)
if t.val == 'not':
return unary(NOT, items[0], r)
if t.val == 'in':
return infix(HAS,items[1],items[0],r)
if t.val == 'notin':
r = infix(HAS,items[1],items[0],r)
zero = _do_number('0')
code(EQ,r,r,free_tmp(zero))
return r
if t.val in sets:
if items[0].type == 'name' and items[0].val in D.globals and len(items[0].val)==1:
a = items[0]
expr = items[1]
if expr.type == 'symbol' and expr.val in '+-/*':
b = expr.items[0]
c = expr.items[1]
if b.type == 'name' and c.type == 'name' and len(b.val)==1 and len(c.val)==1:
if b.val in D.globals and c.val in D.globals:
if expr.val == '+':
code(68, a=ord(a.val), b=ord(b.val), c=ord(c.val))
elif expr.val == '-':
code(69, a=ord(a.val), b=ord(b.val), c=ord(c.val))
elif expr.val == '*':
code(70, a=ord(a.val), b=ord(b.val), c=ord(c.val))
elif expr.val == '/':
code(71, a=ord(a.val), b=ord(b.val), c=ord(c.val))
return None
if D.function_stack and t.val == '=' and r is None:
if items[0].type == 'name' and items[0].val not in D.globals:
a = items[0]
expr = items[1]
if expr.type == 'symbol' and expr.val == '+':
b = expr.items[0]
c = expr.items[1]
## is this really safe? not really any speed up
if b.type=='name' and b.val not in D.globals and c.type=='number' and c.val.isdigit():
num = int(c.val)
if num > 0 and num < 256:
#r = get_reg(a) ## crashes
r = do_local(a,r)
if D.function_stack and b.val in D.function_stack[-1]['args']:
code(190, a=r, b=D.function_stack[-1]['args'].index(b.val), c=num)
else:
code(190, a=r, b=get_reg(b.val), c=num)
return r
return do_set_ctx(items[0],items[1]);
elif t.val in cmps:
b,c = items[0],items[1]
v = t.val
if v[0] in ('>','>='):
b,c,v = c,b,'<'+v[1:]
cd = EQ
if v == '<': cd = LT
if v == '<=': cd = LE
if v == '!=': cd = NE
return infix(cd,b,c,r)
else:
# if t.val in D.vars:
#return do_local(t,r)
a = items[0]
b = items[1]
if a.type == 'name' and a.val in D.globals and len(a.val)==1:
if b.type == 'name' and b.val in D.globals and len(b.val)==1:
print('global fast op return reg=', r)
if r is None:
r = 0
if t.val == '+':
code(64, a=r, b=ord(a.val), c=ord(b.val))
return r
elif t.val == '-':
code(65, a=r, b=ord(a.val), c=ord(b.val))
return r
elif t.val == '*':
code(66, a=r, b=ord(a.val), c=ord(b.val))
return r
elif t.val == '/':
code(67, a=r, b=ord(a.val), c=ord(b.val))
return r
if a.type=='name' and a.val not in D.globals and r:
if b.type=='number' and str(b.val).isdigit():
num = int(b.val)
if num > 0 and num < 256:
if t.val == '+':
## is this really safe? not really any speed up
if D.function_stack and a.val in D.function_stack[-1]['args']:
code(190, a=r, b=D.function_stack[-1]['args'].index(a.val), c=num)
else:
code(190, a=r, b=get_reg(a.val), c=num)
return r
return infix(metas[t.val],items[0],items[1],r)
def do_set_ctx(k,v):
if k.type == 'name':
if (D._globals and k.val not in D.vars) or (k.val in D.globals) or (k.val in D.globals256):
if k.val in D.globals256:
#print("Global256: ", k.val, " index=", D.globals256.index(k.val), ' stack-level=', len(D.stack))
b = do(v)
code(156, D.globals256.index(k.val), b )
free_tmp(b)
elif len(D.stack)==1 and len(D.globals256)<256:
D.globals256.append(k.val)
print("New Global256: ", k.val, " index=", D.globals256.index(k.val), ' stack-level=', len(D.stack))
print(v)
print(v.type)
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
if v.type=='dict':
## global dicts are not garbage collected
b = do_dict(v, is_global=True)
elif v.type=='list':
## global lists are not garbage collected
b = do_list(v, is_global=True)
elif v.type=='comp':
## global lists are not garbage collected
b = do_comp(v, is_global=True)
else:
b = do(v)
code(156, D.globals256.index(k.val), b )
free_tmp(b)
else:
#print("Global: ", k.val, ' stack-level=', len(D.stack))
c = do_string(k)
b = do(v)
code(GSET,c,b)
free_tmp(c)
free_tmp(b)
return
#print("Local: ", k.val, ' stack-level=', len(D.stack))
a = do_local(k)
b = do(v)
code(MOVE,a,b)
free_tmp(b)
return a
elif k.type in ('tuple','list'):
if v.type in ('tuple','list'):
n,tmps = 0,[]
for kk in k.items:
vv = v.items[n]
tmp = get_tmp(); tmps.append(tmp)
r = do(vv)
code(MOVE,tmp,r)
free_tmp(r) #REG
n+=1
n = 0
for kk in k.items:
vv = v.items[n]
tmp = tmps[n]
free_tmp(do_set_ctx(kk,Token(vv.pos,'reg',tmp))) #REG
n += 1
return
r = do(v); un_tmp(r)
n, tmp = 0, Token(v.pos,'reg',r)
for tt in k.items:
free_tmp(do_set_ctx(tt,Token(tmp.pos,'get',None,[tmp,Token(tmp.pos,'number',str(n))]))) #REG
n += 1
free_reg(r)
return
r = do(k.items[0])
rr = do(v)
tmp = do(k.items[1])
code(SET,r,tmp,rr)
free_tmp(r) #REG
free_tmp(tmp) #REG
return rr
def manage_seq(i,a,items,sav=0):
l = max(sav,len(items))
n = 0
tmps = get_tmps(l)
for tt in items:
r = tmps[n]
b = do(tt,r)
if r != b:
code(MOVE,r,b)
free_tmp(b)
n +=1
if not len(tmps):
code(i,a,0,0)
return 0
code(i,a,tmps[0],len(items))
free_tmps(tmps[sav:])
return tmps[0]
def p_filter(items):
a,b,c,d = [],[],None,None
for t in items:
if t.type == 'symbol' and t.val == '=': b.append(t)
elif t.type == 'args': c = t
elif t.type == 'nargs': d = t
else: a.append(t)
return a,b,c,d
def do_import(t):
if len(t.items) == 1:
mod = t.items[0]
name = mod
else:
mod, name = t.items
if mod.val not in D.imports:
D.imports.append(mod.val)
mod.type = 'string'
mod.no_intern = True
v = do_call(Token(t.pos,'call',None,[
Token(t.pos,'name','__import__'),
mod,
Token(t.pos, 'symbol', 'None')]
))
name.type = 'name'
do_set_ctx(name,Token(t.pos,'reg',v))
def do_from(t):
mod = t.items[0]
items = t.items[1]
mod.type = 'string'
if items.type == 'args':
# it really shouldn't be args -- need to fix the parser.
if items.val == '*':
items.type = 'string'
elif items.type == 'name':
items.type = 'string'
items = Token(items.pos, 'tuple', None, [items])
elif items.type == 'tuple':
for item in items.items:
item.type = 'string'
else:
u_error('SyntaxError', D.code, t.pos)
v = do(Token(t.pos,'call',None,[
Token(t.pos,'name','__import__'),
mod,
items,
]))
un_tmp(v)
free_tmp(do(Token(t.pos, 'call', None, [
Token(t.pos, 'name', '__merge__'),
Token(t.pos, 'name', '__dict__'),
Token(t.pos, 'reg', v) #REG
]
)))
free_reg(v)
def do_globals(t):
for t in t.items:
if t.val not in D.globals:
D.globals.append(t.val)
if len(t.val)>1 and t.val not in D.globals256 and len(D.globals256) < 256:
D.globals256.append(t.val)
def do_del(tt):
for t in tt.items:
if t.type=='name':
r = do(t)
code(DEL, r)
free_tmp(r)
else: ## assume dictionary `del foo['bar']`
r = do(t.items[0])
r2 = do(t.items[1])
code(DEL,r,r2)
free_tmp(r)
free_tmp(r2)
def do_call(t,r=None):
assert t.type == 'call'
if DEBUG_ENCODER:
print(t)
## fast printing optimization
if t.items[0].type == 'name' and t.items[0].val == 'print':
if len(t.items[1:]) >= 2 and t.items[-1].type == 'symbol' and t.items[-1].val == '=':
kwargs = t.items[-1]
if kwargs.items[0].type=='name' and kwargs.items[0].val == 'end':
if kwargs.items[1].type=='string' and kwargs.items[1].val == '':
if t.items[1].type == 'string':
if len(t.items[1].val)==1:
code(60, a=ord(t.items[1].val))
return None
## TODO fix unicode bugs, and test compiler with Python3
elif len(t.items[1].val)==2 and t.items[1].val == '·': ## middle dot with bad encoding
#code(60, a=ord(u'·')) ## code 183, is printed as `�`
code(60, a=ord('.')) ## workaround change to a regular dot
return None
r = get_tmp(r)
items = t.items
a,b,c,d = p_filter(t.items[1:])
## special case for directly calling `MyClass.__init__(self, ...)` from a subclass
if t.items[0].type == 'mget' and t.items[0].items[0].type=='name' and t.items[0].items[0].val in D.classes:
if t.items[0].items[1].type=='string' and t.items[0].items[1].val=='__init__':
#func_name = t.items[0].items[1].val ## this is __init__ but actually we are cheating and calling the class like a regular function call
func_name = t.items[0].items[0].val
if not b and c is None and d is None:
if func_name in D.globals256_funcs:
## global fast call - bypasses paramlist ##
if DEBUG_ENCODER:
print(orange('doing fast call MyClass.__init__(self,...)'))
args = D.globals256_funcs[func_name]
assert len(args)==len(a)
assert len(args) >= 1 ## because `self` must be passed as the first arg in this case
tmpargs = get_tmps( len(a) )
for i, tmpreg in enumerate(tmpargs):
bb = do(a[i], tmpreg)
if bb != tmpreg:
code(MOVE,tmpreg, bb)
free_tmp(bb)
## this trick shoves the arg count into the byte code type header itself (200+numargs)
## the last register (RC) is set to the first reg addr, because get_tmps is a range, this hack works.
code( 200+len(args), r, D.globals256.index(func_name), tmpargs[0] )
for tmp in tmpargs:
assert tmp != 0
free_tmp(tmp)
return r
elif t.items[0].type == 'mget' and t.items[0].items[0].type=='name' and not b and not c and not d:
#ALWAYS SAFE#if t.items[0].items[1].type=='string' and t.items[0].items[0].val !='self':
if t.items[0].items[1].type=='string' and t.items[0].items[0].val:
## some variable.foo(...), check if this is a fast callable method
methname = t.items[0].items[1].val
classinfo = None
methinfo = None
hits = 0
can_fast_call = 0
for cname in D.classes:
cinfo = D.classes[cname]
if methname in cinfo['methods'] and cinfo['methods'][methname]:
classinfo = cinfo
methinfo = cinfo['methods'][methname]
hits += 1
if methinfo['can_fast_call']:
can_fast_call += 1
if hits == 1 and methinfo['can_fast_call'] and not D.in_return:
fast_meth_name = '%s::%s' % (classinfo['name'], methinfo['name'])
#fast_meth_name = '__%s__' % methinfo['name']
if len(D.globals256) < 256 and len(D.globals256_funcs) < 256 and methinfo['global256'] is None:
assert fast_meth_name not in D.globals256
assert fast_meth_name not in D.globals256_funcs
D.globals256.append(fast_meth_name)
D.globals256_funcs[fast_meth_name] = methinfo['args']
methinfo['global256'] = D.globals256.index(fast_meth_name)
D.fast_meth_defs[ fast_meth_name ] = methinfo['token']
if methinfo['global256']:
if DEBUG_ENCODER:
print(orange('doing fast method call of type %s and %s(...)' %(classinfo['name'], methinfo['name'])))
func_name = fast_meth_name
args = D.globals256_funcs[func_name]
assert len(args)-1 == len(a)
## need to insert the mget named var here, because it is `self`
a.insert(0, t.items[0].items[0])
tmpargs = get_tmps( len(a) )
for i, tmpreg in enumerate(tmpargs):
bb = do(a[i], tmpreg)
if bb != tmpreg:
code(MOVE,tmpreg, bb)
free_tmp(bb)
code( 200+len(args), r, D.globals256.index(func_name), tmpargs[0] )
for tmp in tmpargs:
assert tmp != 0
free_tmp(tmp)
return r
elif hits and hits==can_fast_call and False: ## not safe yet
if DEBUG_ENCODER:
print(yellow('doing method call of unknown class type %s(...)' %methinfo['name']))
fnc = do(items[0])
## need to insert the mget named var here, because it is `self`
a.insert(0, t.items[0].items[0])
tmpargs = get_tmps( len(a) )
for i, tmpreg in enumerate(tmpargs):
bb = do(a[i], tmpreg)
if bb != tmpreg:
code(MOVE,tmpreg, bb)
free_tmp(bb)
code( 180+len(a), r, fnc, tmpargs[0] )
for tmp in tmpargs:
assert tmp != 0
free_tmp(tmp)
free_tmp(fnc) #REG
return r
elif t.items[0].type == 'name' and t.items[0].val in D.globals256:
if t.items[0].val in D.classes:
class_name = t.items[0].val
if DEBUG_ENCODER:
print(orange('class `%s` in globals256 and in D.classes' %class_name))
if not b and c is None and d is None:
if class_name in D.globals256_funcs:
## global fast call - bypasses paramlist ##
args = D.globals256_funcs[class_name]
if DEBUG_ENCODER:
print(orange('class name in globals256_funcs'))
print(a)
print(args)
assert len(args)-1==len(a) ## because the first item of `args` is `self`
if not len(a):
code( 232, r, D.globals256.index(class_name) )
else:
tmpargs = get_tmps( len(a) )
if DEBUG_ENCODER:
print(orange('temp regs:'), tmpargs)
for i, tmpreg in enumerate(tmpargs):
bb = do(a[i], tmpreg)
if bb != tmpreg:
code(MOVE,tmpreg, bb)
free_tmp(bb)
## this trick shoves the arg count into the byte code type header itself (200+numargs)
## the last register (RC) is set to the first reg addr, because get_tmps is a range, this hack works.
code( 232+len(args), r, D.globals256.index(class_name), tmpargs[0] )
for tmp in tmpargs:
assert tmp != 0
free_tmp(tmp)
return r
else:
func_name = t.items[0].val
if DEBUG_ENCODER:
print(orange('calling function `%s` in globals256' %func_name))
if not b and c is None and d is None:
if func_name in D.globals256_funcs:
## global fast call - bypasses paramlist ##
if DEBUG_ENCODER:
print(orange('doing fast call'))
print(red(func_name))
args = D.globals256_funcs[func_name]
assert len(args)==len(a)
if len(args) <= 1:
if not args:
code(200, r, D.globals256.index(t.items[0].val) )
else:
t1 = do(a[0])
code(201, r, D.globals256.index(t.items[0].val), t1 )
free_tmp(t1)
return r
else:
tmpargs = get_tmps( len(a) )
for i, tmpreg in enumerate(tmpargs):
bb = do(a[i], tmpreg)
if bb != tmpreg:
code(MOVE,tmpreg, bb)
free_tmp(bb)
## this trick shoves the arg count into the byte code type header itself (200+numargs)
## the last register (RC) is set to the first reg addr, because get_tmps is a range, this hack works.
code( 200+len(args), r, D.globals256.index(t.items[0].val), tmpargs[0] )
for tmp in tmpargs:
assert tmp != 0
free_tmp(tmp)
return r
### this is not safe and a very rare case like `foo=getattr(ob,'bar')`
#else:
# ## global fast call ##
# if len(a)==1:
# t1 = do(a[0])
# code(200, r, D.globals256.index(t.items[0].val), t1 )
# free_tmp(t1)
# return r
if DEBUG_ENCODER:
print(yellow('---doing regular call---'))
print( items[0] )
print(yellow('------------------------'))
fnc = do(items[0])
e = None
if len(b) != 0 or d != None:
e = do(Token(t.pos,'dict',None,[])); un_tmp(e);
for p in b:
p.items[0].type = 'string'
t1 = do(p.items[0])
t2 = do(p.items[1])
code(SET,e,t1,t2)
free_tmp(t1)
free_tmp(t2)
if d: free_tmp(do(
Token(t.pos,'call',None,
[ Token(t.pos,'name', '__merge__'),
Token(t.pos,'reg',e),
d.items[0]
]))) #REG
manage_seq(PARAMS,r,a)
if c != None:
t1 = _do_string('*')
t2 = do(c.items[0])
code(SET,r,t1,t2)
free_tmp(t1); free_tmp(t2) #REG
if e != None:
t1 = _do_none()
code(SET,r,t1,e)
free_tmp(t1) #REG
code(CALL,r,fnc,r)
free_tmp(fnc) #REG
return r
def do_name(t,r=None):
if t.val in D.vars:
return do_local(t,r)
if t.val not in D.rglobals:
D.rglobals.append(t.val)
r = get_tmp(r)
if t.val in D.globals256:
code(157, r, D.globals256.index(t.val) )
else:
c = do_string(t)
code(GGET,r,c)
free_tmp(c)
return r
def do_local(t,r=None):
if t.val in D.rglobals:
D.error = True
u_error('UnboundLocalError',D.code,t.pos)
if t.val not in D.vars:
D.vars.append(t.val)
return get_reg(t.val)
def do_fast_meth_def(tok, meth_name):
items = tok.items
t = get_tag()
rf = fnc(t,'end')
D.begin()