forked from gython/Gython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_to_pythonjs.py
More file actions
executable file
·4518 lines (3694 loc) · 150 KB
/
python_to_pythonjs.py
File metadata and controls
executable file
·4518 lines (3694 loc) · 150 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 python
# _*_ coding: utf-8 _*_
# Python to PythonJS Translator
# by Amirouche Boubekki and Brett Hartshorn - copyright 2013
# License: "New BSD"
import os, sys, copy
from types import GeneratorType
import ast
from ast import Str
from ast import Call
from ast import Name
from ast import Tuple
from ast import Assign
from ast import keyword
from ast import Subscript
from ast import Attribute
from ast import FunctionDef
from ast import BinOp
from ast import Pass
from ast import Global
from ast import With
from ast import parse
from ast import NodeVisitor
import typedpython
import ministdlib
import inline_function
import code_writer
from ast_utils import *
## TODO
def log(txt):
pass
POWER_OF_TWO = [ 2**i for i in range(32) ]
writer = writer_main = code_writer.Writer()
__webworker_writers = dict()
def get_webworker_writer( jsfile ):
if jsfile not in __webworker_writers:
__webworker_writers[ jsfile ] = code_writer.Writer()
return __webworker_writers[ jsfile ]
class Typedef(object):
# http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types
_opmap = dict(
__add__ = '+',
__iadd__ = '+=',
__sub__ = '-',
__isub__ = '-=',
__mul__ = '*',
__imul__ = '*=',
__div__ = '/',
__idiv__ = '/=',
__mod__ = '%',
__imod__ = '%=',
__lshift__ = '<<',
__ilshift__ = '<<=',
__rshift__ = '>>',
__irshift__ = '>>=',
__and__ = '&',
__iand__ = '&=',
__xor__ = '^',
__ixor__ = '^=',
__or__ = '|',
__ior__ = '|=',
)
def __init__(self, **kwargs):
for name in kwargs.keys(): ## name, methods, properties, attributes, class_attributes, parents
setattr( self, name, kwargs[name] )
self.operators = dict()
for name in self.methods:
if name in self._opmap:
op = self._opmap[ name ]
self.operators[ op ] = self.get_pythonjs_function_name( name )
def get_pythonjs_function_name(self, name):
assert name in self.methods
return '__%s_%s' %(self.name, name) ## class name
def check_for_parent_with(self, method=None, property=None, operator=None, class_attribute=None):
for parent_name in self.parents:
if not self.compiler.is_known_class_name( parent_name ):
continue
typedef = self.compiler.get_typedef( class_name=parent_name )
if method and method in typedef.methods:
return typedef
elif property and property in typedef.properties:
return typedef
elif operator and typedef.operators:
return typedef
elif class_attribute in typedef.class_attributes:
return typedef
elif typedef.parents:
res = typedef.check_for_parent_with(
method=method,
property=property,
operator=operator,
class_attribute=class_attribute
)
if res:
return res
class NodeVisitorBase( ast.NodeVisitor ):
def __init__(self):
self._line = None
self._line_number = 0
self._stack = [] ## current path to the root
def visit(self, node):
"""Visit a node."""
## modified code of visit() method from Python 2.7 stdlib
self._stack.append(node)
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
res = visitor(node)
self._stack.pop()
return res
def format_error(self, node):
lines = []
if self._line_number > 0:
lines.append( self._source[self._line_number-1] )
lines.append( self._source[self._line_number] )
if self._line_number+1 < len(self._source):
lines.append( self._source[self._line_number+1] )
msg = 'line %s\n%s\n%s\n' %(self._line_number, '\n'.join(lines), node)
msg += 'Depth Stack:\n'
for l, n in enumerate(self._stack):
#msg += str(dir(n))
msg += '%s%s line:%s col:%s\n' % (' '*(l+1)*2, n.__class__.__name__, n.lineno, n.col_offset)
return msg
class PythonToPythonJS(NodeVisitorBase, inline_function.Inliner):
identifier = 0
_func_typedefs = ()
def __init__(self, source=None, modules=False, module_path=None, dart=False, coffee=False, lua=False, go=False, fast_javascript=False, pure_javascript=False):
#super(PythonToPythonJS, self).__init__()
NodeVisitorBase.__init__(self)
self._modules = modules ## split into mutiple files by class
self._module_path = module_path ## used for user `from xxx import *` to load .py files in the same directory.
self._with_lua = lua
self._with_coffee = coffee
self._with_dart = dart
self._with_go = go
self._with_gojs = False
self._fast_js = fast_javascript
self._strict_mode = pure_javascript
self._html_tail = []; script = False
if source.strip().startswith('<html'):
lines = source.splitlines()
for line in lines:
if line.strip().startswith('<script'):
if 'type="text/python"' in line:
writer.write( '<script type="text/python">')
script = list()
elif 'src=' in line and '~/' in line: ## external javascripts installed in users home folder
x = line.split('src="')[-1].split('"')[0]
if os.path.isfile(os.path.expanduser(x)):
o = []
o.append( '<script type="text/javascript">' )
if x.lower().endswith('.coffee'):
import subprocess
proc = subprocess.Popen(
['coffee','--bare', '--print', os.path.expanduser(x)],
stdout=subprocess.PIPE
)
o.append( proc.stdout.read() )
else:
o.append( open(os.path.expanduser(x), 'rb').read() )
o.append( '</script>')
if script is True:
self._html_tail.extend( o )
else:
for y in o:
writer.write(y)
else:
writer.write(line)
elif line.strip() == '</script>':
if type(script) is list and len(script):
source = '\n'.join(script)
script = True
self._html_tail.append( '</script>')
else:
writer.write( line )
elif isinstance( script, list ):
script.append( line )
elif script is True:
self._html_tail.append( line )
else:
writer.write( line )
source = typedpython.transform_source( source )
self.setup_inliner( writer )
self._in_catch_exception = False
## optimize "+" and "*" operator
if fast_javascript:
self._direct_operators = set( ['+', '*'] )
else:
self._direct_operators = set()
self._with_ll = False ## lowlevel
self._with_js = True
self._in_lambda = False
self._in_while_test = False
self._use_threading = False
self._use_sleep = False
self._use_array = False
self._webworker_functions = dict()
self._with_webworker = False
self._with_rpc = None
self._with_rpc_name = None
self._with_direct_keys = fast_javascript
self._with_glsl = False
self._in_gpu_main = False
self._gpu_return_types = set() ## 'array' or float32, or array of 'vec4' float32's.
self._source = source.splitlines()
self._class_stack = list()
self._classes = dict() ## class name : [method names]
self._class_parents = dict() ## class name : parents
self._instance_attributes = dict() ## class name : [attribute names]
self._class_attributes = dict()
self._catch_attributes = None
self._typedef_vars = dict()
#self._names = set() ## not used?
## inferred class instances, TODO regtests to confirm that this never breaks ##
self._instances = dict() ## instance name : class name
self._decorator_properties = dict()
self._decorator_class_props = dict()
self._function_return_types = dict()
self._return_type = None
self._typedefs = dict() ## class name : typedef (deprecated - part of the old static type finder)
self._globals = dict()
self._global_nodes = dict()
self._with_static_type = None
self._global_typed_lists = dict() ## global name : set (if len(set)==1 then we know it is a typed list)
self._global_typed_dicts = dict()
self._global_typed_tuples = dict()
self._global_functions = dict()
self._js_classes = dict()
self._in_js_class = False
self._in_assign_target = False
self._with_runtime_exceptions = True ## this is only used in full python mode.
self._iter_ids = 0
self._addop_ids = 0
self._cache_for_body_calls = False
self._cache_while_body_calls = False
self._comprehensions = []
self._generator_functions = set()
self._in_loop_with_else = False
self._introspective_functions = False
self._custom_operators = {}
self._injector = [] ## advanced meta-programming hacks
self._in_class = None
self._with_fastdef = False
self.setup_builtins()
source = self.preprocess_custom_operators( source )
## check for special imports - TODO clean this up ##
for line in source.splitlines():
if line.strip().startswith('import tornado'):
dirname = os.path.dirname(os.path.abspath(__file__))
header = open( os.path.join(dirname, os.path.join('fakelibs', 'tornado.py')) ).read()
source = header + '\n' + source
self._source = source.splitlines()
elif line.strip().startswith('import os'):
dirname = os.path.dirname(os.path.abspath(__file__))
header = open( os.path.join(dirname, os.path.join('fakelibs', 'os.py')) ).read()
source = header + '\n' + source
self._source = source.splitlines()
elif line.strip().startswith('import tempfile'):
dirname = os.path.dirname(os.path.abspath(__file__))
header = open( os.path.join(dirname, os.path.join('fakelibs', 'tempfile.py')) ).read()
source = header + '\n' + source
self._source = source.splitlines()
elif line.strip().startswith('import sys'):
dirname = os.path.dirname(os.path.abspath(__file__))
header = open( os.path.join(dirname, os.path.join('fakelibs', 'sys.py')) ).read()
source = header + '\n' + source
self._source = source.splitlines()
elif line.strip().startswith('import subprocess'):
dirname = os.path.dirname(os.path.abspath(__file__))
header = open( os.path.join(dirname, os.path.join('fakelibs', 'subprocess.py')) ).read()
source = header + '\n' + source
self._source = source.splitlines()
if '--debug--' in sys.argv:
try:
tree = ast.parse( source )
except SyntaxError:
raise SyntaxError(source)
else:
tree = ast.parse( source )
self._generator_function_nodes = collect_generator_functions( tree )
for node in tree.body:
## skip module level doc strings ##
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
pass
else:
self.visit(node)
if self._html_tail:
for line in self._html_tail:
writer.write(line)
def has_webworkers(self):
return len(self._webworker_functions.keys())
def get_webworker_file_names(self):
return set(self._webworker_functions.values())
def preprocess_custom_operators(self, data):
'''
custom operators must be defined before they are used
'''
code = []
for line in data.splitlines():
if line.strip().startswith('@custom_operator'):
l = line.replace('"', "'")
a,b,c = l.split("'")
op = b.decode('utf-8')
self._custom_operators[ op ] = None
else:
for op in self._custom_operators:
op = op.encode('utf-8')
line = line.replace(op, '|"%s"|'%op)
code.append( line )
data = '\n'.join( code )
return data
def setup_builtins(self):
self._classes['dict'] = set(['__getitem__', '__setitem__'])
self._classes['list'] = set() #['__getitem__', '__setitem__'])
self._classes['tuple'] = set() #['__getitem__', '__setitem__'])
self._builtin_classes = set(['dict', 'list', 'tuple'])
self._builtin_functions = {
'ord':'%s.charCodeAt(0)',
'chr':'String.fromCharCode(%s)',
'abs':'Math.abs(%s)',
'cos':'Math.cos(%s)',
'sin':'Math.sin(%s)',
'sqrt':'Math.sqrt(%s)'
}
self._builtin_functions_dart = {
'ord':'%s.codeUnitAt(0)',
'chr':'new(String.fromCharCode(%s))',
}
def is_known_class_name(self, name):
return name in self._classes
def get_typedef(self, instance=None, class_name=None):
assert instance or class_name
if isinstance(instance, Name) and instance.id in self._instances:
class_name = self._instances[ instance.id ]
if class_name:
#assert class_name in self._classes
if class_name not in self._classes:
#log('ERROR: class name not in self._classes: %s'%class_name)
#log('self._classes: %s'%self._classes)
#raise RuntimeError('class name: %s - not found in self._classes - node:%s '%(class_name, instance))
return None ## TODO hook into self._typedef_vars
if class_name not in self._typedefs:
self._typedefs[ class_name ] = Typedef(
name = class_name,
methods = self._classes[ class_name ],
#properties = self._decorator_class_props[ class_name ],
#attributes = self._instance_attributes[ class_name ],
#class_attributes = self._class_attributes[ class_name ],
#parents = self._class_parents[ class_name ],
properties = self._decorator_class_props.get( class_name, set()),
attributes = self._instance_attributes.get( class_name, set()),
class_attributes = self._class_attributes.get( class_name, set()),
parents = self._class_parents.get( class_name, set()),
compiler = self,
)
return self._typedefs[ class_name ]
def visit_Import(self, node):
'''
fallback to requirejs or if in webworker importScripts.
some special modules from pythons stdlib can be faked here like:
. threading
nodejs only:
. tornado
. os
'''
tornado = ['tornado', 'tornado.web', 'tornado.ioloop']
for alias in node.names:
if self._with_go:
writer.write('import %s' %alias.name)
elif alias.name in tornado:
pass ## pythonjs/fakelibs/tornado.py
elif alias.name == 'tempfile':
pass ## pythonjs/fakelibs/tempfile.py
elif alias.name == 'sys':
pass ## pythonjs/fakelibs/sys.py
elif alias.name == 'subprocess':
pass ## pythonjs/fakelibs/subprocess.py
elif alias.name == 'numpy':
pass
elif alias.name == 'json' or alias.name == 'os':
pass ## part of builtins.py
elif alias.name == 'threading':
self._use_threading = True
#writer.write( 'Worker = require("/usr/local/lib/node_modules/workerjs")')
## note: nodewebkit includes Worker, but only from the main script context,
## there might be a bug in requirejs or nodewebkit where Worker gets lost
## when code is loaded into main as a module using requirejs, as a workaround
## allow "workerjs" to be loaded as a fallback, however this appears to not work in nodewebkit.
writer.write( 'if __NODEJS__==True and typeof(Worker)=="undefined": Worker = require("workerjs")')
elif alias.asname:
#writer.write( '''inline("var %s = requirejs('%s')")''' %(alias.asname, alias.name) )
writer.write( '''inline("var %s = require('%s')")''' %(alias.asname, alias.name.replace('__DASH__', '-')) )
elif '.' in alias.name:
raise NotImplementedError('import with dot not yet supported: line %s' % node.lineno)
else:
#writer.write( '''inline("var %s = requirejs('%s')")''' %(alias.name, alias.name) )
writer.write( '''inline("var %s = require('%s')")''' %(alias.name, alias.name) )
def visit_ImportFrom(self, node):
if self._with_dart:
lib = ministdlib.DART
elif self._with_lua:
lib = ministdlib.LUA
elif self._with_go:
lib = ministdlib.GO
else:
lib = ministdlib.JS
if self._module_path:
path = os.path.join( self._module_path, node.module+'.py')
else:
path = os.path.join( './', node.module+'.py')
if node.module == 'time' and node.names[0].name == 'sleep':
self._use_sleep = True
elif node.module == 'array' and node.names[0].name == 'array':
self._use_array = True ## this is just a hint that calls to array call the builtin array
elif node.module == 'bisect' and node.names[0].name == 'bisect':
## bisect library is part of the stdlib,
## in pythonjs it is a builtin function defined in builtins.py
pass
elif node.module in lib:
imported = False
for n in node.names:
if n.name in lib[ node.module ]:
if not imported:
imported = True
if ministdlib.REQUIRES in lib[node.module]:
writer.write('import %s' %','.join(lib[node.module][ministdlib.REQUIRES]))
writer.write( 'JS("%s")' %lib[node.module][n.name] )
if n.name not in self._builtin_functions:
self._builtin_functions[ n.name ] = n.name + '()'
elif os.path.isfile(path):
## user import `from mymodule import *` TODO support files from other folders
## this creates a sub-translator, because they share the same `writer` object (a global),
## there is no need to call `writer.write` here.
## note: the current pythonjs.configure mode here maybe different from the subcontext.
data = open(path, 'rb').read()
subtrans = PythonToPythonJS(
data,
module_path = self._module_path,
fast_javascript = self._fast_js,
modules = self._modules,
pure_javascript = self._strict_mode,
)
self._js_classes.update( subtrans._js_classes ) ## TODO - what other typedef info needs to be copied here?
else:
msg = 'invalid import - file not found: %s'%path
raise SyntaxError( self.format_error(msg) )
def visit_Assert(self, node):
## hijacking "assert isinstance(a,A)" as a type system ##
if isinstance( node.test, Call ) and isinstance(node.test.func, Name) and node.test.func.id == 'isinstance':
a,b = node.test.args
if b.id in self._classes:
self._instances[ a.id ] = b.id
def visit_Dict(self, node):
node.returns_type = 'dict'
a = []
for i in range( len(node.keys) ):
k = self.visit( node.keys[ i ] )
v = node.values[i]
if isinstance(v, ast.Lambda):
v.keep_as_lambda = True
v = self.visit( v )
if self._with_dart or self._with_ll or self._with_go or self._fast_js:
a.append( '%s:%s'%(k,v) )
#if isinstance(node.keys[i], ast.Str):
# a.append( '%s:%s'%(k,v) )
#else:
# a.append( '"%s":%s'%(k,v) )
elif self._with_js:
a.append( '[%s,%s]'%(k,v) )
else:
a.append( 'JSObject(key=%s, value=%s)'%(k,v) ) ## this allows non-string keys
if self._with_dart or self._with_ll or self._with_go or self._fast_js:
b = ','.join( a )
return '{%s}' %b
elif self._with_js:
b = ','.join( a )
return '__jsdict( [%s] )' %b
else:
b = '[%s]' %', '.join(a)
return '__get__(dict, "__call__")([], {"js_object":%s})' %b
def visit_Tuple(self, node):
node.returns_type = 'tuple'
#a = '[%s]' % ', '.join(map(self.visit, node.elts))
a = []
for e in node.elts:
if isinstance(e, ast.Lambda):
e.keep_as_lambda = True
v = self.visit(e)
assert v is not None
a.append( v )
a = '[%s]' % ', '.join(a)
if self._with_dart:
return 'tuple(%s)' %a
else:
return a
def visit_List(self, node):
node.returns_type = 'list'
a = []
for e in node.elts:
if isinstance(e, ast.Lambda): ## inlined and called lambda "(lambda x: x)(y)"
e.keep_as_lambda = True
v = self.visit(e)
assert v is not None
a.append( v )
a = '[%s]' % ', '.join(a)
if self._with_ll:
pass
elif self._with_lua:
a = '__get__(list, "__call__")({}, {pointer:%s, length:%s})'%(a, len(node.elts))
return a
def visit_GeneratorExp(self, node):
return self.visit_ListComp(node)
_comp_id = 0
def visit_DictComp(self, node):
'''
node.key is key name
node.value is value
'''
#raise SyntaxError(self.visit(node.key)) ## key, value, generators
node.returns_type = 'dict'
if len(self._comprehensions) == 0:
comps = collect_dict_comprehensions( node )
for i,cnode in enumerate(comps):
cname = '__comp__%s' % self._comp_id
cnode._comp_name = cname
self._comprehensions.append( cnode )
self._comp_id += 1
cname = node._comp_name
writer.write('var(%s)'%cname)
length = len( node.generators )
a = ['idx%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
a = ['iter%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
a = ['get%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
if self._with_go:
assert node.go_dictcomp_type
k,v = node.go_dictcomp_type
writer.write('%s = __go__map__(%s, %s)<<{}' %(cname, k,v))
else:
writer.write('%s = {}'%cname)
generators = list( node.generators )
generators.reverse()
self._gen_comp( generators, node )
self._comprehensions.remove( node )
return cname
def visit_ListComp(self, node):
node.returns_type = 'list'
if len(self._comprehensions) == 0 or True:
comps = collect_comprehensions( node )
assert comps
for i,cnode in enumerate(comps):
cname = '__comp__%s' % self._comp_id
cnode._comp_name = cname
self._comprehensions.append( cnode )
self._comp_id += 1
cname = node._comp_name
writer.write('var(%s)'%cname)
#writer.write('var(__comp__%s)'%self._comp_id)
length = len( node.generators ) + (len(self._comprehensions)-1)
a = ['idx%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
a = ['iter%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
a = ['get%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
if self._with_go:
assert node.go_listcomp_type
#writer.write('__comp__%s = __go__array__(%s)' %(self._comp_id, node.go_listcomp_type))
writer.write('%s = __go__array__(%s)' %(cname, node.go_listcomp_type))
else:
writer.write('%s = JSArray()'%cname)
generators = list( node.generators )
generators.reverse()
self._gen_comp( generators, node )
#if node in self._comprehensions:
# self._comprehensions.remove( node )
if self._with_go:
#return '__go__addr__(__comp__%s)' %self._comp_id
return '__go__addr__(%s)' %cname
else:
#return '__comp__%s' %self._comp_id
return cname
def _gen_comp(self, generators, node):
#self._comp_id += 1
#id = self._comp_id
gen = generators.pop()
id = len(generators) + self._comprehensions.index( node )
assert isinstance(gen.target, Name)
writer.write('idx%s = 0'%id)
is_range = False
if isinstance(gen.iter, ast.Call) and isinstance(gen.iter.func, ast.Name) and gen.iter.func.id in ('range', 'xrange'):
is_range = True
writer.write('iter%s = %s' %(id, self.visit(gen.iter.args[0])) )
writer.write('while idx%s < iter%s:' %(id,id) )
writer.push()
writer.write('var(%s)'%gen.target.id)
writer.write('%s=idx%s' %(gen.target.id, id) )
elif self._with_js: ## only works with arrays in javascript mode
writer.write('iter%s = %s' %(id, self.visit(gen.iter)) )
writer.write('while idx%s < iter%s.length:' %(id,id) )
writer.push()
writer.write('var(%s)'%gen.target.id)
writer.write('%s=iter%s[idx%s]' %(gen.target.id, id,id) )
else:
writer.write('iter%s = %s' %(id, self.visit(gen.iter)) )
writer.write('get%s = __get__(iter%s, "__getitem__")'%(id,id) )
writer.write('while idx%s < __get__(len, "__call__")([iter%s], JSObject()):' %(id,id) ) ## TODO optimize
writer.push()
writer.write('var(%s)'%gen.target.id)
writer.write('%s=get%s( [idx%s], JSObject() )' %(gen.target.id, id,id) )
if generators:
self._gen_comp( generators, node )
else:
cname = node._comp_name #self._comprehensions[-1]
#cname = '__comp__%s' % self._comp_id
if len(gen.ifs):
test = []
for compare in gen.ifs:
test.append( self.visit(compare) )
writer.write('if %s:' %' and '.join(test))
writer.push()
self._gen_comp_helper(cname, node)
writer.pull()
else:
self._gen_comp_helper(cname, node)
if self._with_lua:
writer.write('idx%s = idx%s + 1' %(id,id) )
else:
writer.write('idx%s+=1' %id )
writer.pull()
if self._with_lua: ## convert to list
writer.write('%s = list.__call__({},{pointer:%s, length:idx%s})' %(cname, cname, id))
def _gen_comp_helper(self, cname, node):
if isinstance(node, ast.DictComp):
key = self.visit(node.key)
val = self.visit(node.value)
if self._with_go:
writer.write('%s[ %s ] = %s' %(cname, key, val) )
else:
writer.write('%s[ %s ] = %s' %(cname, key, val) )
else:
if self._with_dart:
writer.write('%s.add( %s )' %(cname,self.visit(node.elt)) )
elif self._with_lua:
writer.write('table.insert(%s, %s )' %(cname,self.visit(node.elt)) )
elif self._with_go:
writer.write('%s = append(%s, %s )' %(cname, cname,self.visit(node.elt)) )
else:
writer.write('%s.push( %s )' %(cname,self.visit(node.elt)) )
def visit_In(self, node):
return ' in '
def visit_NotIn(self, node):
#return ' not in '
raise RuntimeError('"not in" is only allowed in if-test: see method - visit_Compare')
## TODO check if the default visit_Compare always works ##
#def visit_Compare(self, node):
# raise NotImplementedError( node )
def visit_AugAssign(self, node):
self._in_assign_target = True
target = self.visit( node.target )
self._in_assign_target = False
op = '%s=' %self.visit( node.op )
typedef = self.get_typedef( node.target )
if self._with_lua:
if isinstance(node.target, ast.Subscript):
name = self.visit(node.target.value)
slice = self.visit(node.target.slice)
op = self.visit(node.op)
a = '__get__(%s, "__setitem__")( [%s, __get__(%s, "__getitem__")([%s], {}) %s (%s)], {} )'
a = a %(name, slice, name, slice, op, self.visit(node.value))
writer.write( a )
return
elif op == '+=':
a = '__add_op(%s,%s)' %(target, self.visit(node.value))
elif op == '-=':
a = '(%s - %s)' %(target, self.visit(node.value))
elif op == '*=':
a = '(%s * %s)' %(target, self.visit(node.value))
elif op == '/=' or op == '//=':
a = '(%s / %s)' %(target, self.visit(node.value))
elif op == '%=':
a = '__mod__(%s,%s)' %(target, self.visit(node.value))
elif op == '&=':
a = '__and__(%s,%s)' %(target, self.visit(node.value))
elif op == '|=':
a = '__or__(%s,%s)' %(target, self.visit(node.value))
elif op == '^=':
a = '__xor__(%s,%s)' %(target, self.visit(node.value))
elif op == '<<=':
a = '__lshift__(%s,%s)' %(target, self.visit(node.value))
elif op == '>>=':
a = '__rshift__(%s,%s)' %(target, self.visit(node.value))
else:
raise NotImplementedError(op)
writer.write('%s=%s' %(target,a))
elif typedef and op in typedef.operators:
func = typedef.operators[ op ]
a = '%s( [%s, %s] )' %(func, target, self.visit(node.value))
writer.write( a )
elif op == '//=':
if isinstance(node.target, ast.Attribute):
name = self.visit(node.target.value)
attr = node.target.attr
target = '%s.%s' %(name, attr)
if self._with_go:
a = '%s /= %s' %(target, self.visit(node.value))
elif self._with_dart:
a = '%s = (%s/%s).floor()' %(target, target, self.visit(node.value))
else:
a = '%s = Math.floor(%s/%s)' %(target, target, self.visit(node.value))
writer.write(a)
elif self._with_dart:
if op == '+=':
a = '%s.__iadd__(%s)' %(target, self.visit(node.value))
elif op == '-=':
a = '%s.__isub__(%s)' %(target, self.visit(node.value))
elif op == '*=':
a = '%s.__imul__(%s)' %(target, self.visit(node.value))
elif op == '/=':
a = '%s.__idiv__(%s)' %(target, self.visit(node.value))
elif op == '%=':
a = '%s.__imod__(%s)' %(target, self.visit(node.value))
elif op == '&=':
a = '%s.__iand__(%s)' %(target, self.visit(node.value))
elif op == '|=':
a = '%s.__ior__(%s)' %(target, self.visit(node.value))
elif op == '^=':
a = '%s.__ixor__(%s)' %(target, self.visit(node.value))
elif op == '<<=':
a = '%s.__ilshift__(%s)' %(target, self.visit(node.value))
elif op == '>>=':
a = '%s.__irshift__(%s)' %(target, self.visit(node.value))
else:
raise NotImplementedError
b = '%s %s %s' %(target, op, self.visit(node.value))
if isinstance( node.target, ast.Name ) and node.target.id in self._typedef_vars and self._typedef_vars[node.target.id] in typedpython.native_number_types+typedpython.vector_types:
writer.write(b)
else:
## dart2js is smart enough to optimize this if/else away ##
writer.write('if instanceof(%s, Number) or instanceof(%s, String): %s' %(target,target,b) )
writer.write('else: %s' %a)
elif self._with_js: ## no operator overloading in with-js mode
a = '%s %s %s' %(target, op, self.visit(node.value))
writer.write(a)
elif isinstance(node.target, ast.Attribute):
name = self.visit(node.target.value)
attr = node.target.attr
a = '%s.%s %s %s' %(name, attr, op, self.visit(node.value))
writer.write(a)
elif isinstance(node.target, ast.Subscript):
name = self.visit(node.target.value)
slice = self.visit(node.target.slice)
#if self._with_js:
# a = '%s[ %s ] %s %s'
# writer.write(a %(name, slice, op, self.visit(node.value)))
#else:
op = self.visit(node.op)
value = self.visit(node.value)
#a = '__get__(%s, "__setitem__")( [%s, __get__(%s, "__getitem__")([%s], {}) %s (%s)], {} )'
fallback = '__get__(%s, "__setitem__")( [%s, __get__(%s, "__getitem__")([%s], {}) %s (%s)], {} )'%(name, slice, name, slice, op, value)
if isinstance(node.target.value, ast.Name):
## TODO also check for arr.remote (RPC) if defined then __setitem__ can not be bypassed
## the overhead of checking if target is an array,
## and calling __setitem__ directly bypassing a single __get__,
## is greather than simply calling the fallback
#writer.write('if instanceof(%s, Array): %s.__setitem__([%s, %s[%s] %s (%s) ], __NULL_OBJECT__)' %(name, name, slice, name,slice, op, value))
writer.write('if instanceof(%s, Array): %s[%s] %s= %s' %(name, name,slice, op, value))
writer.write('else: %s' %fallback)
else:
writer.write(fallback)
else:
## TODO extra checks to make sure the operator type is valid in this context
a = '%s %s %s' %(target, op, self.visit(node.value))
writer.write(a)
def visit_Yield(self, node):
return 'yield %s' % self.visit(node.value)
def _get_js_class_base_init(self, node ):
for base in node.bases:
if base.id == 'object':
continue
n = self._js_classes[ base.id ]
if hasattr(n, '_cached_init'):
return n._cached_init
else:
return self._get_js_class_base_init( n ) ## TODO fixme
def _visit_dart_classdef(self, node):
name = node.name
node._struct_vars = dict()
self._js_classes[ name ] = node
self._class_stack.append( node )
methods = {}
method_list = [] ## getter/setters can have the same name
props = set()
struct_types = dict()
for item in node.body:
if isinstance(item, FunctionDef):
methods[ item.name ] = item
finfo = inspect_method( item )
props.update( finfo['properties'] )
if item.name != '__init__':
method_list.append( item )
#if item.name == '__init__': continue
continue
item.args.args = item.args.args[1:] ## remove self
for n in finfo['name_nodes']:
if n.id == 'self':
n.id = 'this'
elif isinstance(item, ast.Expr) and isinstance(item.value, ast.Dict):
sdef = []
for i in range( len(item.value.keys) ):
k = self.visit( item.value.keys[ i ] )
v = self.visit( item.value.values[i] )
sdef.append( '%s=%s'%(k,v) )
writer.write('@__struct__(%s)' %','.join(sdef))
if self._with_go:
pass
elif props:
writer.write('@properties(%s)'%','.join(props))
for dec in node.decorator_list:
writer.write('@%s'%self.visit(dec))
bases = []
for base in node.bases:
bases.append( self.visit(base) )