Skip to content

Commit 843f74e

Browse files
author
hartsantler
committed
Dart backend: support for __getslice__, ** (Math.pow), // (Math.floor), updated nbody_fast.html so it also works with Dart.
1 parent b404723 commit 843f74e

7 files changed

Lines changed: 99 additions & 33 deletions

File tree

pythonjs/python_to_pythonjs.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,7 +1148,9 @@ def visit_Subscript(self, node):
11481148
)
11491149

11501150
def visit_Slice(self, node):
1151-
if self._with_js:
1151+
if self._with_dart:
1152+
lower = upper = step = 'null'
1153+
elif self._with_js:
11521154
lower = upper = step = 'undefined'
11531155
else:
11541156
lower = upper = step = None
@@ -1310,7 +1312,7 @@ def _visit_assign_helper(self, node, target):
13101312
writer.write('%s = %s' % (self.visit(target), node_value))
13111313

13121314
elif self._with_dart and writer.is_at_global_level():
1313-
writer.write('var %s = %s' % (self.visit(target), node_value))
1315+
writer.write('JS("var %s = %s")' % (self.visit(target), node_value))
13141316
else:
13151317
writer.write('%s = %s' % (self.visit(target), node_value))
13161318

@@ -1723,15 +1725,34 @@ def visit_FunctionDef(self, node):
17231725
else:
17241726
decorators.append( decorator )
17251727

1726-
if self._with_js or javascript or self._with_dart:
1728+
if self._with_dart:
1729+
if node.args.vararg:
1730+
raise SyntaxError( 'pure javascript functions can not take variable arguments (*args)' )
1731+
elif node.args.kwarg:
1732+
raise SyntaxError( 'pure javascript functions can not take variable keyword arguments (**kwargs)' )
1733+
1734+
for dec in with_dart_decorators: writer.write('@%s'%dec)
1735+
1736+
args = []
1737+
offset = len(node.args.args) - len(node.args.defaults)
1738+
for i, arg in enumerate(node.args.args):
1739+
a = arg.id
1740+
dindex = i - offset
1741+
if dindex >= 0 and node.args.defaults:
1742+
default_value = self.visit( node.args.defaults[dindex] )
1743+
args.append( '%s=%s' %(a, default_value) )
1744+
else:
1745+
args.append( a )
1746+
1747+
writer.write( 'def %s( %s ):' % (node.name, ','.join(args)) )
1748+
1749+
1750+
elif self._with_js or javascript:
17271751
if node.args.vararg:
17281752
raise SyntaxError( 'pure javascript functions can not take variable arguments (*args)' )
17291753
elif node.args.kwarg:
17301754
raise SyntaxError( 'pure javascript functions can not take variable keyword arguments (**kwargs)' )
17311755

1732-
if self._with_dart:
1733-
for dec in with_dart_decorators:
1734-
writer.write('@%s'%dec)
17351756
args = [ a.id for a in node.args.args ]
17361757
writer.write( 'def %s( %s ):' % (node.name, ','.join(args)) )
17371758

@@ -1748,7 +1769,11 @@ def visit_FunctionDef(self, node):
17481769
a = ','.join( local_vars-global_vars )
17491770
writer.write('var(%s)' %a)
17501771

1751-
if self._with_js or javascript or self._with_dart:
1772+
#####################################################################
1773+
if self._with_dart:
1774+
pass
1775+
1776+
elif self._with_js or javascript:
17521777
if node.args.defaults:
17531778
offset = len(node.args.args) - len(node.args.defaults)
17541779
for i, arg in enumerate(node.args.args):

pythonjs/pythonjs.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,13 @@ def visit_Call(self, node):
255255
return s
256256

257257
elif name == 'dart_import':
258-
return 'import "%s";' %node.args[0].s
258+
if len(node.args) == 1:
259+
return 'import "%s";' %node.args[0].s
260+
elif len(node.args) == 2:
261+
return 'import "%s" as %s;' %(node.args[0].s, node.args[1].s)
262+
else:
263+
raise SyntaxError
264+
259265

260266
else:
261267
if node.args:
@@ -467,7 +473,7 @@ def visit_For(self, node):
467473

468474
out = []
469475
out.append( self.indent() + 'var %s = %s;' % (iname, iter) )
470-
out.append( self.indent() + 'var %s = 0;' % index )
476+
#out.append( self.indent() + 'var %s = 0;' % index )
471477

472478
self._visit_for_prep_iter_helper(node, out, iname)
473479

pythonjs/pythonjs_to_dart.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,19 @@ def visit_ClassDef(self, node):
206206

207207
def _visit_for_prep_iter_helper(self, node, out, iter_name):
208208
out.append(
209-
self.indent() + 'if (%s is dict) { %s = %s.keys(); }' %(iter_name, iter_name, iter_name)
209+
#self.indent() + 'if (%s is dict) { %s = %s.keys(); }' %(iter_name, iter_name, iter_name)
210+
self.indent() + 'if (%s is dict) %s = %s.keys();' %(iter_name, iter_name, iter_name)
210211
)
211212

212213

213214
def visit_Expr(self, node):
214-
# XXX: this is UGLY
215215
s = self.visit(node.value)
216-
if not s.endswith(';'):
216+
if isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) and node.value.func.id == 'JS':
217+
if s.endswith('}') and 'return' in s.split(' '):
218+
pass
219+
elif not s.endswith(';'):
220+
s += ';'
221+
elif not s.endswith(';'):
217222
s += ';'
218223
return s
219224

@@ -253,7 +258,21 @@ def _visit_function(self, node):
253258
else:
254259
raise SyntaxError
255260

256-
args = self.visit(node.args)
261+
args = [] #self.visit(node.args)
262+
oargs = []
263+
offset = len(node.args.args) - len(node.args.defaults)
264+
for i, arg in enumerate(node.args.args):
265+
a = arg.id
266+
dindex = i - offset
267+
if dindex >= 0 and node.args.defaults:
268+
default_value = self.visit( node.args.defaults[dindex] )
269+
oargs.append( '%s=%s' %(a, default_value) )
270+
else:
271+
args.append( a )
272+
273+
if oargs:
274+
args.append( '[%s]' % ','.join(oargs) )
275+
257276
buffer = self.indent()
258277
if hasattr(node,'_prefix'): buffer += node._prefix + ' '
259278

runtime/dart_builtins.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# License: "New BSD"
44

55
dart_import('dart:collection')
6+
dart_import('dart:math', 'Math')
67

78
@dart.extends
89
class list( ListBase ):
@@ -31,6 +32,13 @@ def __getitem__(self, index):
3132
def __setitem__(self, index, value):
3233
self[...][index] = value
3334

35+
def __getslice__(self, start, stop, step):
36+
if stop == null and step == null:
37+
return self[...].sublist( start )
38+
elif stop < 0:
39+
stop = self[...].length + stop
40+
return self[...].sublist(start, stop)
41+
3442
def append(self, item):
3543
self[...].add( item )
3644

@@ -39,7 +47,7 @@ def index(self, obj):
3947

4048

4149
#@dart.extends
42-
class dict( HashMap ):
50+
class dict: #( HashMap ):
4351
'''
4452
HashMap can not be extended anymore:
4553
https://groups.google.com/a/dartlang.org/forum/#!msg/announce/Sj3guf3es24/YsPCdT_vb2gJ
@@ -77,3 +85,5 @@ def range(n):
7785
i += 1
7886
return r
7987

88+
def len(a):
89+
return a.length

tests/nbody_fast.html

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,10 @@
6262
5.15138902046611451e-05 * SOLAR_MASS) }
6363

6464

65-
SYSTEM = []
66-
for key in BODIES:
67-
print key
68-
SYSTEM.append( BODIES[key] )
6965

70-
PAIRS = combinations(SYSTEM)
7166

7267

73-
def advance(dt, n, bodies=SYSTEM, pairs=PAIRS):
68+
def advance(dt, n, bodies, pairs):
7469
for i in xrange(n):
7570
for pair in pairs:
7671
p1,p2 = pair
@@ -99,7 +94,7 @@
9994
r[2] += dt * v[2]
10095

10196

102-
def report_energy(bodies=SYSTEM, pairs=PAIRS, e=0.0):
97+
def report_energy(bodies, pairs, e=0.0):
10398
for pair in pairs:
10499
p1,p2 = pair
105100
vec1, v1, m1 = p1
@@ -119,7 +114,7 @@
119114
return e
120115

121116

122-
def offset_momentum(ref, bodies=SYSTEM, px=0.0, py=0.0, pz=0.0):
117+
def offset_momentum(ref, bodies, px=0.0, py=0.0, pz=0.0):
123118
for w in bodies:
124119
r, v, m = w
125120
vx, vy, vz = v
@@ -134,24 +129,28 @@
134129

135130

136131
def test_nbody(iterations):
132+
SYSTEM = []
133+
for key in BODIES: SYSTEM.append( BODIES[key] )
134+
PAIRS = combinations(SYSTEM)
135+
137136
# Warm-up runs.
138-
report_energy()
139-
advance(0.01, 20000)
140-
report_energy()
137+
report_energy( SYSTEM, PAIRS )
138+
advance(0.01, 20000, SYSTEM, PAIRS )
139+
report_energy( SYSTEM, PAIRS )
141140

142141
times = []
143142
for _ in xrange(iterations):
144143
t0 = time()
145-
report_energy()
146-
advance(0.01, 20000)
147-
report_energy()
144+
report_energy( SYSTEM, PAIRS )
145+
advance(0.01, 20000, SYSTEM, PAIRS)
146+
report_energy( SYSTEM, PAIRS )
148147
t1 = time()
149148
times.append(t1 - t0)
150149
return times
151150

152151

153152

154-
def test():
153+
def main():
155154
times = test_nbody( 3 )
156155
for t in times:
157156
print 'time', t
@@ -161,6 +160,6 @@
161160

162161
</head>
163162
<body>
164-
<button id="mybutton" onclick="test()">click me</button>
163+
<button id="mybutton" onclick="main()">click me</button>
165164
</body>
166165
</html>

tests/server.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
runtime_dart = os.path.abspath('../runtime/dart_builtins.py'),
2929

3030
dart2js = os.path.expanduser( '~/dart/dart-sdk/bin/dart2js'),
31+
dartanalyzer = os.path.expanduser( '~/dart/dart-sdk/bin/dartanalyzer'),
3132

3233
)
3334

@@ -62,14 +63,18 @@ def pythonjs_to_dart(src):
6263
stdin = subprocess.PIPE,
6364
stdout = subprocess.PIPE
6465
)
66+
dart_input = '/tmp/dart2js-input.dart'
6567
stdout, stderr = p.communicate( src.encode('utf-8') )
66-
open( '/tmp/dart2js-input.js', 'wb').write( stdout )
68+
open( dart_input, 'wb').write( stdout )
69+
ecode = subprocess.call( [PATHS['dartanalyzer'], dart_input] )
70+
if ecode == 2:
71+
raise SyntaxError
6772

6873
cmd = [
6974
PATHS['dart2js'],
7075
#'-c', ## insert runtime checks
7176
'-o', '/tmp/dart2js-output.js',
72-
'/tmp/dart2js-input.js'
77+
dart_input
7378
]
7479
subprocess.call( cmd )
7580
return open('/tmp/dart2js-output.js', 'rb').read().decode('utf-8')

tests/test_for_loop.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
<script type="text/python">
66

7-
87
def main():
8+
'''
9+
basic for loop tests
10+
'''
911

1012
a = [1,2,3]
1113
for x in a:

0 commit comments

Comments
 (0)