author | Andrey Skvortsov <andrej.skvortzov@gmail.com> |
Wed, 16 Aug 2017 12:57:52 +0300 | |
changeset 1751 | c28db6f7616b |
parent 1749 | d73b64672238 |
child 1752 | d14ff9d7eb76 |
permissions | -rw-r--r-- |
371 | 1 |
#!/usr/bin/env python |
2 |
# Copyright 2006 James Tauber and contributors |
|
3 |
# |
|
4 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
|
5 |
# you may not use this file except in compliance with the License. |
|
6 |
# You may obtain a copy of the License at |
|
7 |
# |
|
8 |
# http://www.apache.org/licenses/LICENSE-2.0 |
|
9 |
# |
|
10 |
# Unless required by applicable law or agreed to in writing, software |
|
11 |
# distributed under the License is distributed on an "AS IS" BASIS, |
|
12 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
13 |
# See the License for the specific language governing permissions and |
|
14 |
# limitations under the License. |
|
15 |
||
16 |
||
17 |
import sys |
|
18 |
from types import StringType |
|
19 |
import compiler |
|
20 |
from compiler import ast |
|
21 |
import os |
|
22 |
import copy |
|
23 |
||
24 |
# the standard location for builtins (e.g. pyjslib) can be |
|
25 |
# over-ridden by changing this. it defaults to sys.prefix |
|
26 |
# so that on a system-wide install of pyjamas the builtins |
|
27 |
# can be found in e.g. {sys.prefix}/share/pyjamas |
|
28 |
# |
|
29 |
# over-rides can be done by either explicitly modifying |
|
30 |
# pyjs.prefix or by setting an environment variable, PYJSPREFIX. |
|
31 |
||
32 |
prefix = sys.prefix |
|
33 |
||
34 |
if os.environ.has_key('PYJSPREFIX'): |
|
35 |
prefix = os.environ['PYJSPREFIX'] |
|
36 |
||
37 |
# pyjs.path is the list of paths, just like sys.path, from which |
|
38 |
# library modules will be searched for, for compile purposes. |
|
39 |
# obviously we don't want to use sys.path because that would result |
|
40 |
# in compiling standard python modules into javascript! |
|
41 |
||
42 |
path = [os.path.abspath('')] |
|
43 |
||
44 |
if os.environ.has_key('PYJSPATH'): |
|
45 |
for p in os.environ['PYJSPATH'].split(os.pathsep): |
|
46 |
p = os.path.abspath(p) |
|
47 |
if os.path.isdir(p): |
|
48 |
path.append(p) |
|
49 |
||
50 |
# this is the python function used to wrap native javascript |
|
51 |
NATIVE_JS_FUNC_NAME = "JS" |
|
52 |
||
53 |
UU = "" |
|
54 |
||
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
55 |
PYJSLIB_BUILTIN_FUNCTIONS = ("cmp", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
56 |
"map", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
57 |
"filter", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
58 |
"dir", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
59 |
"getattr", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
60 |
"setattr", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
61 |
"hasattr", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
62 |
"int", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
63 |
"float", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
64 |
"str", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
65 |
"repr", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
66 |
"range", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
67 |
"len", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
68 |
"hash", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
69 |
"abs", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
70 |
"ord", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
71 |
"chr", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
72 |
"enumerate", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
73 |
"min", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
74 |
"max", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
75 |
"bool", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
76 |
"type", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
77 |
"isinstance") |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
78 |
|
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
79 |
PYJSLIB_BUILTIN_CLASSES = ("BaseException", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
80 |
"Exception", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
81 |
"StandardError", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
82 |
"StopIteration", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
83 |
"AttributeError", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
84 |
"TypeError", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
85 |
"KeyError", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
86 |
"LookupError", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
87 |
"list", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
88 |
"dict", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
89 |
"object", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
90 |
"tuple", |
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
91 |
) |
371 | 92 |
|
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
93 |
|
371 | 94 |
def pyjs_builtin_remap(name): |
95 |
# XXX HACK! |
|
96 |
if name == 'list': |
|
97 |
name = 'List' |
|
98 |
if name == 'object': |
|
99 |
name = '__Object' |
|
100 |
if name == 'dict': |
|
101 |
name = 'Dict' |
|
102 |
if name == 'tuple': |
|
103 |
name = 'Tuple' |
|
104 |
return name |
|
105 |
||
1749
d73b64672238
clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1746
diff
changeset
|
106 |
|
371 | 107 |
# XXX: this is a hack: these should be dealt with another way |
108 |
# however, console is currently the only global name which is causing |
|
109 |
# problems. |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
110 |
PYJS_GLOBAL_VARS = ("console") |
371 | 111 |
|
112 |
# This is taken from the django project. |
|
113 |
# Escape every ASCII character with a value less than 32. |
|
114 |
JS_ESCAPES = ( |
|
115 |
('\\', r'\x5C'), |
|
116 |
('\'', r'\x27'), |
|
117 |
('"', r'\x22'), |
|
118 |
('>', r'\x3E'), |
|
119 |
('<', r'\x3C'), |
|
120 |
('&', r'\x26'), |
|
121 |
(';', r'\x3B') |
|
122 |
) + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]) |
|
123 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
124 |
|
371 | 125 |
def escapejs(value): |
126 |
"""Hex encodes characters for use in JavaScript strings.""" |
|
127 |
for bad, good in JS_ESCAPES: |
|
128 |
value = value.replace(bad, good) |
|
129 |
return value |
|
130 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
131 |
|
371 | 132 |
def uuprefix(name, leave_alone=0): |
133 |
name = name.split(".") |
|
134 |
name = name[:leave_alone] + map(lambda x: "__%s" % x, name[leave_alone:]) |
|
135 |
return '.'.join(name) |
|
136 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
137 |
|
371 | 138 |
class Klass: |
139 |
||
140 |
klasses = {} |
|
141 |
||
142 |
def __init__(self, name, name_): |
|
143 |
self.name = name |
|
144 |
self.name_ = name_ |
|
145 |
self.klasses[name] = self |
|
146 |
self.functions = set() |
|
147 |
||
148 |
def set_base(self, base_name): |
|
149 |
self.base = self.klasses.get(base_name) |
|
150 |
||
151 |
def add_function(self, function_name): |
|
152 |
self.functions.add(function_name) |
|
153 |
||
154 |
||
155 |
class TranslationError(Exception): |
|
156 |
def __init__(self, message, node): |
|
157 |
self.message = "line %s:\n%s\n%s" % (node.lineno, message, node) |
|
158 |
||
159 |
def __str__(self): |
|
160 |
return self.message |
|
161 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
162 |
|
371 | 163 |
def strip_py(name): |
164 |
return name |
|
165 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
166 |
|
371 | 167 |
def mod_var_name_decl(raw_module_name): |
168 |
""" function to get the last component of the module e.g. |
|
169 |
pyjamas.ui.DOM into the "namespace". i.e. doing |
|
170 |
"import pyjamas.ui.DOM" actually ends up with _two_ |
|
171 |
variables - one pyjamas.ui.DOM, the other just "DOM". |
|
172 |
but "DOM" is actually local, hence the "var" prefix. |
|
173 |
||
174 |
for PyV8, this might end up causing problems - we'll have |
|
175 |
to see: gen_mod_import and mod_var_name_decl might have |
|
176 |
to end up in a library-specific module, somewhere. |
|
177 |
""" |
|
178 |
name = raw_module_name.split(".") |
|
179 |
if len(name) == 1: |
|
180 |
return '' |
|
181 |
child_name = name[-1] |
|
182 |
return "var %s = %s;\n" % (child_name, raw_module_name) |
|
183 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
184 |
|
371 | 185 |
def gen_mod_import(parentName, importName, dynamic=1): |
186 |
#pyjs_ajax_eval("%(n)s.cache.js", null, true); |
|
187 |
return """ |
|
188 |
pyjslib.import_module(sys.loadpath, '%(p)s', '%(n)s', %(d)d, false); |
|
189 |
""" % ({'p': parentName, 'd': dynamic, 'n': importName}) + \ |
|
190 |
mod_var_name_decl(importName) |
|
191 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
192 |
|
371 | 193 |
class Translator: |
194 |
||
195 |
def __init__(self, mn, module_name, raw_module_name, src, debug, mod, output, |
|
196 |
dynamic=0, optimize=False, |
|
197 |
findFile=None): |
|
198 |
||
199 |
if module_name: |
|
200 |
self.module_prefix = module_name + "." |
|
201 |
else: |
|
202 |
self.module_prefix = "" |
|
203 |
self.raw_module_name = raw_module_name |
|
204 |
src = src.replace("\r\n", "\n") |
|
205 |
src = src.replace("\n\r", "\n") |
|
206 |
src = src.replace("\r", "\n") |
|
207 |
self.src = src.split("\n") |
|
208 |
self.debug = debug |
|
209 |
self.imported_modules = [] |
|
210 |
self.imported_modules_as = [] |
|
211 |
self.imported_js = set() |
|
212 |
self.top_level_functions = set() |
|
213 |
self.top_level_classes = set() |
|
214 |
self.top_level_vars = set() |
|
215 |
self.local_arg_stack = [[]] |
|
216 |
self.output = output |
|
217 |
self.imported_classes = {} |
|
218 |
self.method_imported_globals = set() |
|
219 |
self.method_self = None |
|
220 |
self.nextTupleAssignID = 1 |
|
221 |
self.dynamic = dynamic |
|
222 |
self.optimize = optimize |
|
223 |
self.findFile = findFile |
|
224 |
||
225 |
if module_name.find(".") >= 0: |
|
226 |
vdec = '' |
|
227 |
else: |
|
228 |
vdec = 'var ' |
|
229 |
print >>self.output, UU+"%s%s = function (__mod_name__) {" % (vdec, module_name) |
|
230 |
||
231 |
print >>self.output, " if("+module_name+".__was_initialized__) return;" |
|
232 |
print >>self.output, " "+UU+module_name+".__was_initialized__ = true;" |
|
233 |
print >>self.output, UU+"if (__mod_name__ == null) __mod_name__ = '%s';" % (mn) |
|
234 |
print >>self.output, UU+"%s.__name__ = __mod_name__;" % (raw_module_name) |
|
235 |
||
236 |
decl = mod_var_name_decl(raw_module_name) |
|
237 |
if decl: |
|
238 |
print >>self.output, decl |
|
239 |
||
240 |
if self.debug: |
|
241 |
haltException = self.module_prefix + "HaltException" |
|
242 |
print >>self.output, haltException + ' = function () {' |
|
243 |
print >>self.output, ' this.message = "Program Halted";' |
|
244 |
print >>self.output, ' this.name = "' + haltException + '";' |
|
245 |
print >>self.output, '}' |
|
246 |
print >>self.output, '' |
|
247 |
print >>self.output, haltException + ".prototype.__str__ = function()" |
|
248 |
print >>self.output, '{' |
|
249 |
print >>self.output, 'return this.message ;' |
|
250 |
print >>self.output, '}' |
|
251 |
||
252 |
print >>self.output, haltException + ".prototype.toString = function()" |
|
253 |
print >>self.output, '{' |
|
254 |
print >>self.output, 'return this.name + ": \\"" + this.message + "\\"";' |
|
255 |
print >>self.output, '}' |
|
256 |
||
257 |
isHaltFunction = self.module_prefix + "IsHaltException" |
|
258 |
print >>self.output, """ |
|
259 |
%s = function (s) { |
|
260 |
var suffix="HaltException"; |
|
261 |
if (s.length < suffix.length) { |
|
262 |
//alert(s + " " + suffix); |
|
263 |
return false; |
|
264 |
} else { |
|
265 |
var ss = s.substring(s.length, (s.length - suffix.length)); |
|
266 |
//alert(s + " " + suffix + " " + ss); |
|
267 |
return ss == suffix; |
|
268 |
} |
|
269 |
} |
|
270 |
""" % isHaltFunction |
|
271 |
for child in mod.node: |
|
272 |
if isinstance(child, ast.Function): |
|
273 |
self.top_level_functions.add(child.name) |
|
274 |
elif isinstance(child, ast.Class): |
|
275 |
self.top_level_classes.add(child.name) |
|
276 |
||
277 |
for child in mod.node: |
|
278 |
if isinstance(child, ast.Function): |
|
279 |
self._function(child, False) |
|
280 |
elif isinstance(child, ast.Class): |
|
281 |
self._class(child) |
|
282 |
elif isinstance(child, ast.Import): |
|
283 |
importName = child.names[0][0] |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
284 |
if importName == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter |
371 | 285 |
pass |
286 |
elif importName.endswith('.js'): |
|
287 |
self.imported_js.add(importName) |
|
288 |
else: |
|
289 |
self.add_imported_module(strip_py(importName)) |
|
290 |
elif isinstance(child, ast.From): |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
291 |
if child.modname == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter |
371 | 292 |
pass |
293 |
else: |
|
294 |
self.add_imported_module(child.modname) |
|
295 |
self._from(child) |
|
296 |
elif isinstance(child, ast.Discard): |
|
297 |
self._discard(child, None) |
|
298 |
elif isinstance(child, ast.Assign): |
|
299 |
self._assign(child, None, True) |
|
300 |
elif isinstance(child, ast.AugAssign): |
|
301 |
self._augassign(child, None) |
|
302 |
elif isinstance(child, ast.If): |
|
303 |
self._if(child, None) |
|
304 |
elif isinstance(child, ast.For): |
|
305 |
self._for(child, None) |
|
306 |
elif isinstance(child, ast.While): |
|
307 |
self._while(child, None) |
|
308 |
elif isinstance(child, ast.Subscript): |
|
309 |
self._subscript_stmt(child, None) |
|
310 |
elif isinstance(child, ast.Global): |
|
311 |
self._global(child, None) |
|
312 |
elif isinstance(child, ast.Printnl): |
|
313 |
self._print(child, None) |
|
314 |
elif isinstance(child, ast.Print): |
|
315 |
self._print(child, None) |
|
316 |
elif isinstance(child, ast.TryExcept): |
|
317 |
self._tryExcept(child, None) |
|
318 |
elif isinstance(child, ast.Raise): |
|
319 |
self._raise(child, None) |
|
320 |
elif isinstance(child, ast.Stmt): |
|
321 |
self._stmt(child, None) |
|
322 |
else: |
|
323 |
raise TranslationError("unsupported type (in __init__)", child) |
|
324 |
||
325 |
# Initialize all classes for this module |
|
326 |
#print >> self.output, "__"+self.modpfx()+\ |
|
327 |
# "classes_initialize = function() {\n" |
|
328 |
#for className in self.top_level_classes: |
|
329 |
# print >> self.output, "\t"+UU+self.modpfx()+"__"+className+"_initialize();" |
|
330 |
#print >> self.output, "};\n" |
|
331 |
||
332 |
print >> self.output, "return this;\n" |
|
333 |
print >> self.output, "}; /* end %s */ \n" % module_name |
|
334 |
||
335 |
def module_imports(self): |
|
336 |
return self.imported_modules + self.imported_modules_as |
|
337 |
||
338 |
def add_local_arg(self, varname): |
|
339 |
local_vars = self.local_arg_stack[-1] |
|
340 |
if varname not in local_vars: |
|
341 |
local_vars.append(varname) |
|
342 |
||
343 |
def add_imported_module(self, importName): |
|
344 |
||
345 |
if importName in self.imported_modules: |
|
346 |
return |
|
347 |
self.imported_modules.append(importName) |
|
348 |
name = importName.split(".") |
|
349 |
if len(name) != 1: |
|
350 |
# add the name of the module to the namespace, |
|
351 |
# but don't add the short name to imported_modules |
|
352 |
# because then the short name would be attempted to be |
|
353 |
# added to the dependencies, and it's half way up the |
|
354 |
# module import directory structure! |
|
355 |
child_name = name[-1] |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
356 |
self.imported_modules_as.append(child_name) |
371 | 357 |
print >> self.output, gen_mod_import(self.raw_module_name, |
358 |
strip_py(importName), |
|
359 |
self.dynamic) |
|
360 |
||
361 |
def _default_args_handler(self, node, arg_names, current_klass, |
|
362 |
output=None): |
|
363 |
if len(node.defaults): |
|
364 |
output = output or self.output |
|
365 |
default_pos = len(arg_names) - len(node.defaults) |
|
366 |
if arg_names and arg_names[0] == self.method_self: |
|
367 |
default_pos -= 1 |
|
368 |
for default_node in node.defaults: |
|
369 |
if isinstance(default_node, ast.Const): |
|
370 |
default_value = self._const(default_node) |
|
371 |
elif isinstance(default_node, ast.Name): |
|
372 |
default_value = self._name(default_node, current_klass) |
|
373 |
elif isinstance(default_node, ast.UnarySub): |
|
374 |
default_value = self._unarysub(default_node, current_klass) |
|
375 |
else: |
|
376 |
raise TranslationError("unsupported type (in _method)", default_node) |
|
377 |
||
378 |
default_name = arg_names[default_pos] |
|
379 |
default_pos += 1 |
|
380 |
print >> output, " if (typeof %s == 'undefined') %s=%s;" % (default_name, default_name, default_value) |
|
381 |
||
382 |
def _varargs_handler(self, node, varargname, arg_names, current_klass): |
|
383 |
print >>self.output, " var", varargname, '= new pyjslib.Tuple();' |
|
384 |
print >>self.output, " for(var __va_arg="+str(len(arg_names))+"; __va_arg < arguments.length; __va_arg++) {" |
|
385 |
print >>self.output, " var __arg = arguments[__va_arg];" |
|
386 |
print >>self.output, " "+varargname+".append(__arg);" |
|
387 |
print >>self.output, " }" |
|
388 |
||
389 |
def _kwargs_parser(self, node, function_name, arg_names, current_klass): |
|
390 |
if len(node.defaults) or node.kwargs: |
|
391 |
default_pos = len(arg_names) - len(node.defaults) |
|
392 |
if arg_names and arg_names[0] == self.method_self: |
|
393 |
default_pos -= 1 |
|
394 |
print >>self.output, function_name+'.parse_kwargs = function (', ", ".join(["__kwargs"]+arg_names), ") {" |
|
395 |
for default_node in node.defaults: |
|
396 |
default_value = self.expr(default_node, current_klass) |
|
397 |
# if isinstance(default_node, ast.Const): |
|
398 |
# default_value = self._const(default_node) |
|
399 |
# elif isinstance(default_node, ast.Name): |
|
400 |
# default_value = self._name(default_node) |
|
401 |
# elif isinstance(default_node, ast.UnarySub): |
|
402 |
# default_value = self._unarysub(default_node, current_klass) |
|
403 |
# else: |
|
404 |
# raise TranslationError("unsupported type (in _method)", default_node) |
|
405 |
||
406 |
default_name = arg_names[default_pos] |
|
1734
750eeb7230a1
clean-up: fix some PEP8 E228 missing whitespace around modulo operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
407 |
print >>self.output, " if (typeof %s == 'undefined')" % (default_name) |
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
408 |
print >>self.output, " %s=__kwargs.%s;" % (default_name, default_name) |
371 | 409 |
default_pos += 1 |
410 |
||
411 |
#self._default_args_handler(node, arg_names, current_klass) |
|
412 |
if node.kwargs: arg_names += ["pyjslib.Dict(__kwargs)"] |
|
413 |
print >>self.output, " var __r = "+"".join(["[", ", ".join(arg_names), "]"])+";" |
|
414 |
if node.varargs: |
|
415 |
self._varargs_handler(node, "__args", arg_names, current_klass) |
|
416 |
print >>self.output, " __r.push.apply(__r, __args.getArray())" |
|
417 |
print >>self.output, " return __r;" |
|
418 |
print >>self.output, "};" |
|
419 |
||
420 |
def _function(self, node, local=False): |
|
421 |
if local: |
|
422 |
function_name = node.name |
|
423 |
self.add_local_arg(function_name) |
|
424 |
else: |
|
425 |
function_name = UU + self.modpfx() + node.name |
|
426 |
||
427 |
arg_names = list(node.argnames) |
|
428 |
normal_arg_names = list(arg_names) |
|
429 |
if node.kwargs: kwargname = normal_arg_names.pop() |
|
430 |
if node.varargs: varargname = normal_arg_names.pop() |
|
431 |
declared_arg_names = list(normal_arg_names) |
|
432 |
if node.kwargs: declared_arg_names.append(kwargname) |
|
433 |
||
434 |
function_args = "(" + ", ".join(declared_arg_names) + ")" |
|
435 |
print >>self.output, "%s = function%s {" % (function_name, function_args) |
|
436 |
self._default_args_handler(node, normal_arg_names, None) |
|
437 |
||
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
438 |
local_arg_names = normal_arg_names + declared_arg_names |
371 | 439 |
|
440 |
if node.varargs: |
|
441 |
self._varargs_handler(node, varargname, declared_arg_names, None) |
|
442 |
local_arg_names.append(varargname) |
|
443 |
||
444 |
# stack of local variable names for this function call |
|
445 |
self.local_arg_stack.append(local_arg_names) |
|
446 |
||
447 |
for child in node.code: |
|
448 |
self._stmt(child, None) |
|
449 |
||
450 |
# remove the top local arg names |
|
451 |
self.local_arg_stack.pop() |
|
452 |
||
453 |
# we need to return null always, so it is not undefined |
|
454 |
lastStmt = [p for p in node.code][-1] |
|
455 |
if not isinstance(lastStmt, ast.Return): |
|
456 |
if not self._isNativeFunc(lastStmt): |
|
457 |
print >>self.output, " return null;" |
|
458 |
||
459 |
print >>self.output, "};" |
|
460 |
print >>self.output, "%s.__name__ = '%s';\n" % (function_name, node.name) |
|
461 |
||
462 |
self._kwargs_parser(node, function_name, normal_arg_names, None) |
|
463 |
||
464 |
def _return(self, node, current_klass): |
|
465 |
expr = self.expr(node.value, current_klass) |
|
466 |
# in python a function call always returns None, so we do it |
|
467 |
# here too |
|
468 |
print >>self.output, " return " + expr + ";" |
|
469 |
||
470 |
def _break(self, node, current_klass): |
|
471 |
print >>self.output, " break;" |
|
472 |
||
473 |
def _continue(self, node, current_klass): |
|
474 |
print >>self.output, " continue;" |
|
475 |
||
476 |
def _callfunc(self, v, current_klass): |
|
477 |
||
478 |
if isinstance(v.node, ast.Name): |
|
479 |
if v.node.name in self.top_level_functions: |
|
480 |
call_name = self.modpfx() + v.node.name |
|
481 |
elif v.node.name in self.top_level_classes: |
|
482 |
call_name = self.modpfx() + v.node.name |
|
483 |
elif self.imported_classes.has_key(v.node.name): |
|
484 |
call_name = self.imported_classes[v.node.name] + '.' + v.node.name |
|
485 |
elif v.node.name in PYJSLIB_BUILTIN_FUNCTIONS: |
|
486 |
call_name = 'pyjslib.' + v.node.name |
|
487 |
elif v.node.name in PYJSLIB_BUILTIN_CLASSES: |
|
488 |
name = pyjs_builtin_remap(v.node.name) |
|
489 |
call_name = 'pyjslib.' + name |
|
490 |
elif v.node.name == "callable": |
|
491 |
call_name = "pyjslib.isFunction" |
|
492 |
else: |
|
493 |
call_name = v.node.name |
|
494 |
call_args = [] |
|
495 |
elif isinstance(v.node, ast.Getattr): |
|
496 |
attr_name = v.node.attrname |
|
497 |
||
498 |
if isinstance(v.node.expr, ast.Name): |
|
499 |
call_name = self._name2(v.node.expr, current_klass, attr_name) |
|
500 |
call_args = [] |
|
501 |
elif isinstance(v.node.expr, ast.Getattr): |
|
502 |
call_name = self._getattr2(v.node.expr, current_klass, attr_name) |
|
503 |
call_args = [] |
|
504 |
elif isinstance(v.node.expr, ast.CallFunc): |
|
505 |
call_name = self._callfunc(v.node.expr, current_klass) + "." + v.node.attrname |
|
506 |
call_args = [] |
|
507 |
elif isinstance(v.node.expr, ast.Subscript): |
|
508 |
call_name = self._subscript(v.node.expr, current_klass) + "." + v.node.attrname |
|
509 |
call_args = [] |
|
510 |
elif isinstance(v.node.expr, ast.Const): |
|
511 |
call_name = self.expr(v.node.expr, current_klass) + "." + v.node.attrname |
|
512 |
call_args = [] |
|
513 |
else: |
|
514 |
raise TranslationError("unsupported type (in _callfunc)", v.node.expr) |
|
515 |
else: |
|
516 |
raise TranslationError("unsupported type (in _callfunc)", v.node) |
|
517 |
||
518 |
call_name = strip_py(call_name) |
|
519 |
||
520 |
kwargs = [] |
|
521 |
star_arg_name = None |
|
522 |
if v.star_args: |
|
523 |
star_arg_name = self.expr(v.star_args, current_klass) |
|
524 |
||
525 |
for ch4 in v.args: |
|
526 |
if isinstance(ch4, ast.Keyword): |
|
527 |
kwarg = ch4.name + ":" + self.expr(ch4.expr, current_klass) |
|
528 |
kwargs.append(kwarg) |
|
529 |
else: |
|
530 |
arg = self.expr(ch4, current_klass) |
|
531 |
call_args.append(arg) |
|
532 |
||
533 |
if kwargs: |
|
534 |
fn_args = ", ".join(['{' + ', '.join(kwargs) + '}']+call_args) |
|
535 |
else: |
|
536 |
fn_args = ", ".join(call_args) |
|
537 |
||
538 |
if kwargs or star_arg_name: |
|
539 |
if not star_arg_name: |
|
540 |
star_arg_name = 'null' |
|
541 |
try: call_this, method_name = call_name.rsplit(".", 1) |
|
542 |
except ValueError: |
|
543 |
# Must be a function call ... |
|
544 |
return ("pyjs_kwargs_function_call("+call_name+", " |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
545 |
+ star_arg_name |
371 | 546 |
+ ", ["+fn_args+"]" |
1746
45d6f5fba016
clean-up: fix PEP8 E202 whitespace before ')'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1744
diff
changeset
|
547 |
+ ")") |
371 | 548 |
else: |
549 |
return ("pyjs_kwargs_method_call("+call_this+", '"+method_name+"', " |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
550 |
+ star_arg_name |
371 | 551 |
+ ", ["+fn_args+"]" |
552 |
+ ")") |
|
553 |
else: |
|
554 |
return call_name + "(" + ", ".join(call_args) + ")" |
|
555 |
||
556 |
def _print(self, node, current_klass): |
|
557 |
if self.optimize: |
|
558 |
return |
|
559 |
call_args = [] |
|
560 |
for ch4 in node.nodes: |
|
561 |
arg = self.expr(ch4, current_klass) |
|
562 |
call_args.append(arg) |
|
563 |
||
564 |
print >>self.output, "pyjslib.printFunc([", ', '.join(call_args), "],", int(isinstance(node, ast.Printnl)), ");" |
|
565 |
||
566 |
def _tryExcept(self, node, current_klass): |
|
567 |
if len(node.handlers) != 1: |
|
568 |
raise TranslationError("except statements in this form are" + |
|
569 |
" not supported", node) |
|
570 |
||
571 |
expr = node.handlers[0][0] |
|
572 |
as_ = node.handlers[0][1] |
|
573 |
if as_: |
|
574 |
errName = as_.name |
|
575 |
else: |
|
576 |
errName = 'err' |
|
577 |
||
578 |
# XXX TODO: check that this should instead be added as a _separate_ |
|
579 |
# local scope, temporary to the function. oh dearie me. |
|
580 |
self.add_local_arg(errName) |
|
581 |
||
582 |
print >>self.output, " try {" |
|
583 |
for stmt in node.body.nodes: |
|
584 |
self._stmt(stmt, current_klass) |
|
585 |
print >> self.output, " } catch(%s) {" % errName |
|
586 |
if expr: |
|
587 |
l = [] |
|
588 |
if isinstance(expr, ast.Tuple): |
|
589 |
for x in expr.nodes: |
|
590 |
l.append("(%(err)s.__name__ == %(expr)s.__name__)" % dict (err=errName, expr=self.expr(x, current_klass))) |
|
591 |
else: |
|
1746
45d6f5fba016
clean-up: fix PEP8 E202 whitespace before ')'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1744
diff
changeset
|
592 |
l = [" (%(err)s.__name__ == %(expr)s.__name__) " % dict (err=errName, expr=self.expr(expr, current_klass))] |
371 | 593 |
print >> self.output, " if(%s) {" % '||\n\t\t'.join(l) |
594 |
for stmt in node.handlers[0][2]: |
|
595 |
self._stmt(stmt, current_klass) |
|
596 |
if expr: |
|
597 |
#print >> self.output, "} else { throw(%s); } " % errName |
|
598 |
print >> self.output, "}" |
|
1743
c3c3d1318130
clean-up: fix PEP8 E711 comparison to None should be 'if cond is not None:'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1742
diff
changeset
|
599 |
if node.else_ is not None: |
371 | 600 |
print >>self.output, " } finally {" |
601 |
for stmt in node.else_: |
|
602 |
self._stmt(stmt, current_klass) |
|
603 |
print >>self.output, " }" |
|
604 |
||
605 |
# XXX: change use_getattr to True to enable "strict" compilation |
|
606 |
# but incurring a 100% performance penalty. oops. |
|
607 |
def _getattr(self, v, current_klass, use_getattr=False): |
|
608 |
attr_name = v.attrname |
|
609 |
if isinstance(v.expr, ast.Name): |
|
610 |
obj = self._name(v.expr, current_klass, return_none_for_module=True) |
|
1743
c3c3d1318130
clean-up: fix PEP8 E711 comparison to None should be 'if cond is not None:'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1742
diff
changeset
|
611 |
if obj is None and v.expr.name in self.module_imports(): |
371 | 612 |
# XXX TODO: distinguish between module import classes |
613 |
# and variables. right now, this is a hack to get |
|
614 |
# the sys module working. |
|
615 |
#if v.expr.name == 'sys': |
|
616 |
return v.expr.name+'.'+attr_name |
|
617 |
#return v.expr.name+'.__'+attr_name+'.prototype.__class__' |
|
618 |
if not use_getattr or attr_name == '__class__' or \ |
|
619 |
attr_name == '__name__': |
|
620 |
return obj + "." + attr_name |
|
621 |
return "pyjslib.getattr(%s, '%s')" % (obj, attr_name) |
|
622 |
elif isinstance(v.expr, ast.Getattr): |
|
623 |
return self._getattr(v.expr, current_klass) + "." + attr_name |
|
624 |
elif isinstance(v.expr, ast.Subscript): |
|
625 |
return self._subscript(v.expr, self.modpfx()) + "." + attr_name |
|
626 |
elif isinstance(v.expr, ast.CallFunc): |
|
627 |
return self._callfunc(v.expr, self.modpfx()) + "." + attr_name |
|
628 |
else: |
|
629 |
raise TranslationError("unsupported type (in _getattr)", v.expr) |
|
630 |
||
631 |
def modpfx(self): |
|
632 |
return strip_py(self.module_prefix) |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
633 |
|
371 | 634 |
def _name(self, v, current_klass, top_level=False, |
635 |
return_none_for_module=False): |
|
636 |
||
637 |
if v.name == 'ilikesillynamesfornicedebugcode': |
|
638 |
print top_level, current_klass, repr(v) |
|
639 |
print self.top_level_vars |
|
640 |
print self.top_level_functions |
|
641 |
print self.local_arg_stack |
|
642 |
print "error..." |
|
643 |
||
644 |
local_var_names = None |
|
645 |
las = len(self.local_arg_stack) |
|
646 |
if las > 0: |
|
647 |
local_var_names = self.local_arg_stack[-1] |
|
648 |
||
649 |
if v.name == "True": |
|
650 |
return "true" |
|
651 |
elif v.name == "False": |
|
652 |
return "false" |
|
653 |
elif v.name == "None": |
|
654 |
return "null" |
|
655 |
elif v.name == '__name__' and current_klass is None: |
|
656 |
return self.modpfx() + v.name |
|
657 |
elif v.name == self.method_self: |
|
658 |
return "this" |
|
659 |
elif v.name in self.top_level_functions: |
|
660 |
return UU+self.modpfx() + v.name |
|
661 |
elif v.name in self.method_imported_globals: |
|
662 |
return UU+self.modpfx() + v.name |
|
663 |
elif not current_klass and las == 1 and v.name in self.top_level_vars: |
|
664 |
return UU+self.modpfx() + v.name |
|
665 |
elif v.name in local_var_names: |
|
666 |
return v.name |
|
667 |
elif self.imported_classes.has_key(v.name): |
|
668 |
return UU+self.imported_classes[v.name] + '.__' + v.name + ".prototype.__class__" |
|
669 |
elif v.name in self.top_level_classes: |
|
670 |
return UU+self.modpfx() + "__" + v.name + ".prototype.__class__" |
|
671 |
elif v.name in self.module_imports() and return_none_for_module: |
|
672 |
return None |
|
673 |
elif v.name in PYJSLIB_BUILTIN_CLASSES: |
|
1746
45d6f5fba016
clean-up: fix PEP8 E202 whitespace before ')'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1744
diff
changeset
|
674 |
return "pyjslib." + pyjs_builtin_remap(v.name) |
371 | 675 |
elif current_klass: |
676 |
if v.name not in local_var_names and \ |
|
677 |
v.name not in self.top_level_vars and \ |
|
678 |
v.name not in PYJS_GLOBAL_VARS and \ |
|
679 |
v.name not in self.top_level_functions: |
|
680 |
||
681 |
cls_name = current_klass |
|
682 |
if hasattr(cls_name, "name"): |
|
683 |
cls_name_ = cls_name.name_ |
|
684 |
cls_name = cls_name.name |
|
685 |
else: |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
686 |
cls_name_ = current_klass + "_" # XXX ??? |
371 | 687 |
name = UU+cls_name_ + ".prototype.__class__." \ |
688 |
+ v.name |
|
689 |
if v.name == 'listener': |
|
690 |
name = 'listener+' + name |
|
691 |
return name |
|
692 |
||
693 |
return v.name |
|
694 |
||
695 |
def _name2(self, v, current_klass, attr_name): |
|
696 |
obj = v.name |
|
697 |
||
698 |
if obj in self.method_imported_globals: |
|
699 |
call_name = UU+self.modpfx() + obj + "." + attr_name |
|
700 |
elif self.imported_classes.has_key(obj): |
|
701 |
#attr_str = "" |
|
702 |
#if attr_name != "__init__": |
|
703 |
attr_str = ".prototype.__class__." + attr_name |
|
704 |
call_name = UU+self.imported_classes[obj] + '.__' + obj + attr_str |
|
705 |
elif obj in self.module_imports(): |
|
706 |
call_name = obj + "." + attr_name |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
707 |
elif obj[0] == obj[0].upper(): # XXX HACK ALERT |
371 | 708 |
call_name = UU + self.modpfx() + "__" + obj + ".prototype.__class__." + attr_name |
709 |
else: |
|
710 |
call_name = UU+self._name(v, current_klass) + "." + attr_name |
|
711 |
||
712 |
return call_name |
|
713 |
||
714 |
def _getattr2(self, v, current_klass, attr_name): |
|
715 |
if isinstance(v.expr, ast.Getattr): |
|
716 |
call_name = self._getattr2(v.expr, current_klass, v.attrname + "." + attr_name) |
|
717 |
elif isinstance(v.expr, ast.Name) and v.expr.name in self.module_imports(): |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
718 |
call_name = UU+v.expr.name + '.__' + v.attrname+".prototype.__class__."+attr_name |
371 | 719 |
else: |
720 |
obj = self.expr(v.expr, current_klass) |
|
721 |
call_name = obj + "." + v.attrname + "." + attr_name |
|
722 |
||
723 |
return call_name |
|
724 |
||
725 |
def _class(self, node): |
|
726 |
""" |
|
727 |
Handle a class definition. |
|
728 |
||
729 |
In order to translate python semantics reasonably well, the following |
|
730 |
structure is used: |
|
731 |
||
732 |
A special object is created for the class, which inherits attributes |
|
733 |
from the superclass, or Object if there's no superclass. This is the |
|
734 |
class object; the object which you refer to when specifying the |
|
735 |
class by name. Static, class, and unbound methods are copied |
|
736 |
from the superclass object. |
|
737 |
||
738 |
A special constructor function is created with the same name as the |
|
739 |
class, which is used to create instances of that class. |
|
740 |
||
741 |
A javascript class (e.g. a function with a prototype attribute) is |
|
742 |
created which is the javascript class of created instances, and |
|
743 |
which inherits attributes from the class object. Bound methods are |
|
744 |
copied from the superclass into this class rather than inherited, |
|
745 |
because the class object contains unbound, class, and static methods |
|
746 |
that we don't necessarily want to inherit. |
|
747 |
||
748 |
The type of a method can now be determined by inspecting its |
|
749 |
static_method, unbound_method, class_method, or instance_method |
|
750 |
attribute; only one of these should be true. |
|
751 |
||
752 |
Much of this work is done in pyjs_extend, is pyjslib.py |
|
753 |
""" |
|
754 |
class_name = self.modpfx() + uuprefix(node.name, 1) |
|
755 |
class_name_ = self.modpfx() + uuprefix(node.name) |
|
756 |
current_klass = Klass(class_name, class_name_) |
|
757 |
init_method = None |
|
758 |
for child in node.code: |
|
759 |
if isinstance(child, ast.Function): |
|
760 |
current_klass.add_function(child.name) |
|
761 |
if child.name == "__init__": |
|
762 |
init_method = child |
|
763 |
||
764 |
if len(node.bases) == 0: |
|
765 |
base_class = "pyjslib.__Object" |
|
766 |
elif len(node.bases) == 1: |
|
767 |
if isinstance(node.bases[0], ast.Name): |
|
768 |
if self.imported_classes.has_key(node.bases[0].name): |
|
769 |
base_class_ = self.imported_classes[node.bases[0].name] + '.__' + node.bases[0].name |
|
770 |
base_class = self.imported_classes[node.bases[0].name] + '.' + node.bases[0].name |
|
771 |
else: |
|
772 |
base_class_ = self.modpfx() + "__" + node.bases[0].name |
|
773 |
base_class = self.modpfx() + node.bases[0].name |
|
774 |
elif isinstance(node.bases[0], ast.Getattr): |
|
775 |
# the bases are not in scope of the class so do not |
|
776 |
# pass our class to self._name |
|
777 |
base_class_ = self._name(node.bases[0].expr, None) + \ |
|
778 |
".__" + node.bases[0].attrname |
|
779 |
base_class = self._name(node.bases[0].expr, None) + \ |
|
780 |
"." + node.bases[0].attrname |
|
781 |
else: |
|
782 |
raise TranslationError("unsupported type (in _class)", node.bases[0]) |
|
783 |
||
784 |
current_klass.set_base(base_class) |
|
785 |
else: |
|
786 |
raise TranslationError("more than one base (in _class)", node) |
|
787 |
||
788 |
print >>self.output, UU+class_name_ + " = function () {" |
|
789 |
# call superconstructor |
|
790 |
#if base_class: |
|
791 |
# print >>self.output, " __" + base_class + ".call(this);" |
|
792 |
print >>self.output, "}" |
|
793 |
||
794 |
if not init_method: |
|
795 |
init_method = ast.Function([], "__init__", ["self"], [], 0, None, []) |
|
796 |
#self._method(init_method, current_klass, class_name) |
|
797 |
||
798 |
# Generate a function which constructs the object |
|
799 |
clsfunc = ast.Function([], |
|
800 |
node.name, |
|
801 |
init_method.argnames[1:], |
|
802 |
init_method.defaults, |
|
803 |
init_method.flags, |
|
804 |
None, |
|
805 |
[ast.Discard(ast.CallFunc(ast.Name("JS"), [ast.Const( |
|
806 |
# I attempted lazy initialization, but then you can't access static class members |
|
807 |
# " if(!__"+base_class+".__was_initialized__)"+ |
|
808 |
# " __" + class_name + "_initialize();\n" + |
|
809 |
" var instance = new " + UU + class_name_ + "();\n" + |
|
810 |
" if(instance.__init__) instance.__init__.apply(instance, arguments);\n" + |
|
811 |
" return instance;" |
|
812 |
)]))]) |
|
813 |
||
814 |
self._function(clsfunc, False) |
|
815 |
print >>self.output, UU+class_name_ + ".__initialize__ = function () {" |
|
816 |
print >>self.output, " if("+UU+class_name_+".__was_initialized__) return;" |
|
817 |
print >>self.output, " "+UU+class_name_+".__was_initialized__ = true;" |
|
818 |
cls_obj = UU+class_name_ + '.prototype.__class__' |
|
819 |
||
820 |
if class_name == "pyjslib.__Object": |
|
821 |
print >>self.output, " "+cls_obj+" = {};" |
|
822 |
else: |
|
823 |
if base_class and base_class not in ("object", "pyjslib.__Object"): |
|
824 |
print >>self.output, " if(!"+UU+base_class_+".__was_initialized__)" |
|
825 |
print >>self.output, " "+UU+base_class_+".__initialize__();" |
|
826 |
print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+base_class_+");" |
|
827 |
else: |
|
828 |
print >>self.output, " pyjs_extend(" + UU+class_name_ + ", "+UU+"pyjslib.__Object);" |
|
829 |
||
830 |
print >>self.output, " "+cls_obj+".__new__ = "+UU+class_name+";" |
|
831 |
print >>self.output, " "+cls_obj+".__name__ = '"+UU+node.name+"';" |
|
832 |
||
833 |
for child in node.code: |
|
834 |
if isinstance(child, ast.Pass): |
|
835 |
pass |
|
836 |
elif isinstance(child, ast.Function): |
|
837 |
self._method(child, current_klass, class_name, class_name_) |
|
838 |
elif isinstance(child, ast.Assign): |
|
839 |
self.classattr(child, current_klass) |
|
840 |
elif isinstance(child, ast.Discard) and isinstance(child.expr, ast.Const): |
|
841 |
# Probably a docstring, turf it |
|
842 |
pass |
|
843 |
else: |
|
844 |
raise TranslationError("unsupported type (in _class)", child) |
|
845 |
print >>self.output, "}" |
|
846 |
||
847 |
print >> self.output, class_name_+".__initialize__();" |
|
848 |
||
849 |
def classattr(self, node, current_klass): |
|
850 |
self._assign(node, current_klass, True) |
|
851 |
||
852 |
def _raise(self, node, current_klass): |
|
853 |
if node.expr2: |
|
854 |
raise TranslationError("More than one expression unsupported", |
|
855 |
node) |
|
856 |
print >> self.output, "throw (%s);" % self.expr( |
|
857 |
node.expr1, current_klass) |
|
858 |
||
859 |
def _method(self, node, current_klass, class_name, class_name_): |
|
860 |
# reset global var scope |
|
861 |
self.method_imported_globals = set() |
|
862 |
||
863 |
arg_names = list(node.argnames) |
|
864 |
||
865 |
classmethod = False |
|
866 |
staticmethod = False |
|
867 |
if node.decorators: |
|
868 |
for d in node.decorators: |
|
869 |
if d.name == "classmethod": |
|
870 |
classmethod = True |
|
871 |
elif d.name == "staticmethod": |
|
872 |
staticmethod = True |
|
873 |
||
874 |
if staticmethod: |
|
875 |
staticfunc = ast.Function([], class_name_+"."+node.name, node.argnames, node.defaults, node.flags, node.doc, node.code, node.lineno) |
|
876 |
self._function(staticfunc, True) |
|
877 |
print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + " = " + class_name_+"."+node.name+";"; |
|
878 |
print >>self.output, " " + UU+class_name_ + ".prototype.__class__." + node.name + ".static_method = true;"; |
|
879 |
return |
|
880 |
else: |
|
881 |
if len(arg_names) == 0: |
|
882 |
raise TranslationError("methods must take an argument 'self' (in _method)", node) |
|
883 |
self.method_self = arg_names[0] |
|
884 |
||
885 |
#if not classmethod and arg_names[0] != "self": |
|
886 |
# raise TranslationError("first arg not 'self' (in _method)", node) |
|
887 |
||
888 |
normal_arg_names = arg_names[1:] |
|
889 |
if node.kwargs: kwargname = normal_arg_names.pop() |
|
890 |
if node.varargs: varargname = normal_arg_names.pop() |
|
891 |
declared_arg_names = list(normal_arg_names) |
|
892 |
if node.kwargs: declared_arg_names.append(kwargname) |
|
893 |
||
894 |
function_args = "(" + ", ".join(declared_arg_names) + ")" |
|
895 |
||
896 |
if classmethod: |
|
897 |
fexpr = UU + class_name_ + ".prototype.__class__." + node.name |
|
898 |
else: |
|
899 |
fexpr = UU + class_name_ + ".prototype." + node.name |
|
900 |
print >>self.output, " "+fexpr + " = function" + function_args + " {" |
|
901 |
||
902 |
# default arguments |
|
903 |
self._default_args_handler(node, normal_arg_names, current_klass) |
|
904 |
||
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
905 |
local_arg_names = normal_arg_names + declared_arg_names |
371 | 906 |
|
907 |
if node.varargs: |
|
908 |
self._varargs_handler(node, varargname, declared_arg_names, current_klass) |
|
909 |
local_arg_names.append(varargname) |
|
910 |
||
911 |
# stack of local variable names for this function call |
|
912 |
self.local_arg_stack.append(local_arg_names) |
|
913 |
||
914 |
for child in node.code: |
|
915 |
self._stmt(child, current_klass) |
|
916 |
||
917 |
# remove the top local arg names |
|
918 |
self.local_arg_stack.pop() |
|
919 |
||
920 |
print >>self.output, " };" |
|
921 |
||
922 |
self._kwargs_parser(node, fexpr, normal_arg_names, current_klass) |
|
923 |
||
924 |
if classmethod: |
|
925 |
# Have to create a version on the instances which automatically passes the |
|
926 |
# class as "self" |
|
927 |
altexpr = UU + class_name_ + ".prototype." + node.name |
|
928 |
print >>self.output, " "+altexpr + " = function() {" |
|
929 |
print >>self.output, " return " + fexpr + ".apply(this.__class__, arguments);" |
|
930 |
print >>self.output, " };" |
|
931 |
print >>self.output, " "+fexpr+".class_method = true;" |
|
932 |
print >>self.output, " "+altexpr+".instance_method = true;" |
|
933 |
else: |
|
934 |
# For instance methods, we need an unbound version in the class object |
|
935 |
altexpr = UU + class_name_ + ".prototype.__class__." + node.name |
|
936 |
print >>self.output, " "+altexpr + " = function() {" |
|
937 |
print >>self.output, " return " + fexpr + ".call.apply("+fexpr+", arguments);" |
|
938 |
print >>self.output, " };" |
|
939 |
print >>self.output, " "+altexpr+".unbound_method = true;" |
|
940 |
print >>self.output, " "+fexpr+".instance_method = true;" |
|
941 |
print >>self.output, " "+altexpr+".__name__ = '%s';" % node.name |
|
942 |
||
943 |
print >>self.output, UU + class_name_ + ".prototype.%s.__name__ = '%s';" % \ |
|
944 |
(node.name, node.name) |
|
945 |
||
946 |
if node.kwargs or len(node.defaults): |
|
947 |
print >>self.output, " "+altexpr + ".parse_kwargs = " + fexpr + ".parse_kwargs;" |
|
948 |
||
949 |
self.method_self = None |
|
950 |
self.method_imported_globals = set() |
|
951 |
||
952 |
def _isNativeFunc(self, node): |
|
953 |
if isinstance(node, ast.Discard): |
|
954 |
if isinstance(node.expr, ast.CallFunc): |
|
955 |
if isinstance(node.expr.node, ast.Name) and \ |
|
956 |
node.expr.node.name == NATIVE_JS_FUNC_NAME: |
|
957 |
return True |
|
958 |
return False |
|
959 |
||
960 |
def _stmt(self, node, current_klass): |
|
961 |
debugStmt = self.debug and not self._isNativeFunc(node) |
|
962 |
if debugStmt: |
|
963 |
print >>self.output, ' try {' |
|
964 |
||
965 |
if isinstance(node, ast.Return): |
|
966 |
self._return(node, current_klass) |
|
967 |
elif isinstance(node, ast.Break): |
|
968 |
self._break(node, current_klass) |
|
969 |
elif isinstance(node, ast.Continue): |
|
970 |
self._continue(node, current_klass) |
|
971 |
elif isinstance(node, ast.Assign): |
|
972 |
self._assign(node, current_klass) |
|
973 |
elif isinstance(node, ast.AugAssign): |
|
974 |
self._augassign(node, current_klass) |
|
975 |
elif isinstance(node, ast.Discard): |
|
976 |
self._discard(node, current_klass) |
|
977 |
elif isinstance(node, ast.If): |
|
978 |
self._if(node, current_klass) |
|
979 |
elif isinstance(node, ast.For): |
|
980 |
self._for(node, current_klass) |
|
981 |
elif isinstance(node, ast.While): |
|
982 |
self._while(node, current_klass) |
|
983 |
elif isinstance(node, ast.Subscript): |
|
984 |
self._subscript_stmt(node, current_klass) |
|
985 |
elif isinstance(node, ast.Global): |
|
986 |
self._global(node, current_klass) |
|
987 |
elif isinstance(node, ast.Pass): |
|
988 |
pass |
|
989 |
elif isinstance(node, ast.Function): |
|
990 |
self._function(node, True) |
|
991 |
elif isinstance(node, ast.Printnl): |
|
992 |
self._print(node, current_klass) |
|
993 |
elif isinstance(node, ast.Print): |
|
994 |
self._print(node, current_klass) |
|
995 |
elif isinstance(node, ast.TryExcept): |
|
996 |
self._tryExcept(node, current_klass) |
|
997 |
elif isinstance(node, ast.Raise): |
|
998 |
self._raise(node, current_klass) |
|
999 |
else: |
|
1000 |
raise TranslationError("unsupported type (in _stmt)", node) |
|
1001 |
||
1002 |
if debugStmt: |
|
1003 |
||
1004 |
lt = self.get_line_trace(node) |
|
1005 |
||
1006 |
haltException = self.module_prefix + "HaltException" |
|
1007 |
isHaltFunction = self.module_prefix + "IsHaltException" |
|
1008 |
||
1009 |
print >>self.output, ' } catch (__err) {' |
|
1010 |
print >>self.output, ' if (' + isHaltFunction + '(__err.name)) {' |
|
1011 |
print >>self.output, ' throw __err;' |
|
1012 |
print >>self.output, ' } else {' |
|
1013 |
print >>self.output, " st = sys.printstack() + "\ |
|
1014 |
+ '"%s"' % lt + "+ '\\n' ;" |
|
1015 |
print >>self.output, ' alert("' + "Error in " \ |
|
1016 |
+ lt + '"' \ |
|
1017 |
+ '+"\\n"+__err.name+": "+__err.message'\ |
|
1018 |
+ '+"\\n\\nStack trace:\\n"' \ |
|
1019 |
+ '+st' \ |
|
1020 |
+ ');' |
|
1021 |
print >>self.output, ' debugger;' |
|
1022 |
||
1023 |
print >>self.output, ' throw new ' + self.module_prefix + "HaltException();" |
|
1024 |
print >>self.output, ' }' |
|
1025 |
print >>self.output, ' }' |
|
1026 |
||
1027 |
def get_line_trace(self, node): |
|
1028 |
lineNum = "Unknown" |
|
1029 |
srcLine = "" |
|
1030 |
if hasattr(node, "lineno"): |
|
1743
c3c3d1318130
clean-up: fix PEP8 E711 comparison to None should be 'if cond is not None:'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1742
diff
changeset
|
1031 |
if node.lineno is not None: |
371 | 1032 |
lineNum = node.lineno |
1033 |
srcLine = self.src[min(lineNum, len(self.src))-1] |
|
1034 |
srcLine = srcLine.replace('\\', '\\\\') |
|
1035 |
srcLine = srcLine.replace('"', '\\"') |
|
1036 |
srcLine = srcLine.replace("'", "\\'") |
|
1037 |
||
1038 |
return self.raw_module_name + ".py, line " \ |
|
1039 |
+ str(lineNum) + ":"\ |
|
1040 |
+ "\\n" \ |
|
1041 |
+ " " + srcLine |
|
1042 |
||
1043 |
def _augassign(self, node, current_klass): |
|
1044 |
v = node.node |
|
1045 |
if isinstance(v, ast.Getattr): |
|
1046 |
# XXX HACK! don't allow += on return result of getattr. |
|
1047 |
# TODO: create a temporary variable or something. |
|
1048 |
lhs = self._getattr(v, current_klass, False) |
|
1049 |
else: |
|
1050 |
lhs = self._name(node.node, current_klass) |
|
1051 |
op = node.op |
|
1052 |
rhs = self.expr(node.expr, current_klass) |
|
1053 |
print >>self.output, " " + lhs + " " + op + " " + rhs + ";" |
|
1054 |
||
1744
69dfdb26f600
clean-up: fix PEP8 E251 unexpected spaces around keyword / parameter equals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1743
diff
changeset
|
1055 |
def _assign(self, node, current_klass, top_level=False): |
371 | 1056 |
if len(node.nodes) != 1: |
1057 |
tempvar = '__temp'+str(node.lineno) |
|
1058 |
tnode = ast.Assign([ast.AssName(tempvar, "OP_ASSIGN", node.lineno)], node.expr, node.lineno) |
|
1059 |
self._assign(tnode, current_klass, top_level) |
|
1060 |
for v in node.nodes: |
|
1061 |
tnode2 = ast.Assign([v], ast.Name(tempvar, node.lineno), node.lineno) |
|
1062 |
self._assign(tnode2, current_klass, top_level) |
|
1063 |
return |
|
1064 |
||
1065 |
local_var_names = None |
|
1066 |
if len(self.local_arg_stack) > 0: |
|
1067 |
local_var_names = self.local_arg_stack[-1] |
|
1068 |
||
1069 |
def _lhsFromAttr(v, current_klass): |
|
1070 |
attr_name = v.attrname |
|
1071 |
if isinstance(v.expr, ast.Name): |
|
1072 |
obj = v.expr.name |
|
1073 |
lhs = self._name(v.expr, current_klass) + "." + attr_name |
|
1074 |
elif isinstance(v.expr, ast.Getattr): |
|
1075 |
lhs = self._getattr(v, current_klass) |
|
1076 |
elif isinstance(v.expr, ast.Subscript): |
|
1077 |
lhs = self._subscript(v.expr, current_klass) + "." + attr_name |
|
1078 |
else: |
|
1079 |
raise TranslationError("unsupported type (in _assign)", v.expr) |
|
1080 |
return lhs |
|
1081 |
||
1082 |
def _lhsFromName(v, top_level, current_klass): |
|
1083 |
if top_level: |
|
1084 |
if current_klass: |
|
1085 |
lhs = UU+current_klass.name_ + ".prototype.__class__." \ |
|
1086 |
+ v.name |
|
1087 |
else: |
|
1088 |
self.top_level_vars.add(v.name) |
|
1089 |
vname = self.modpfx() + v.name |
|
1090 |
if not self.modpfx() and v.name not in\ |
|
1091 |
self.method_imported_globals: |
|
1092 |
lhs = "var " + vname |
|
1093 |
else: |
|
1094 |
lhs = UU + vname |
|
1095 |
self.add_local_arg(v.name) |
|
1096 |
else: |
|
1097 |
if v.name in local_var_names: |
|
1098 |
lhs = v.name |
|
1099 |
elif v.name in self.method_imported_globals: |
|
1100 |
lhs = self.modpfx() + v.name |
|
1101 |
else: |
|
1102 |
lhs = "var " + v.name |
|
1103 |
self.add_local_arg(v.name) |
|
1104 |
return lhs |
|
1105 |
||
1106 |
dbg = 0 |
|
1107 |
v = node.nodes[0] |
|
1108 |
if isinstance(v, ast.AssAttr): |
|
1109 |
lhs = _lhsFromAttr(v, current_klass) |
|
1110 |
if v.flags == "OP_ASSIGN": |
|
1111 |
op = "=" |
|
1112 |
else: |
|
1113 |
raise TranslationError("unsupported flag (in _assign)", v) |
|
1114 |
||
1115 |
elif isinstance(v, ast.AssName): |
|
1116 |
lhs = _lhsFromName(v, top_level, current_klass) |
|
1117 |
if v.flags == "OP_ASSIGN": |
|
1118 |
op = "=" |
|
1119 |
else: |
|
1120 |
raise TranslationError("unsupported flag (in _assign)", v) |
|
1121 |
elif isinstance(v, ast.Subscript): |
|
1122 |
if v.flags == "OP_ASSIGN": |
|
1123 |
obj = self.expr(v.expr, current_klass) |
|
1124 |
if len(v.subs) != 1: |
|
1125 |
raise TranslationError("must have one sub (in _assign)", v) |
|
1126 |
idx = self.expr(v.subs[0], current_klass) |
|
1127 |
value = self.expr(node.expr, current_klass) |
|
1128 |
print >>self.output, " " + obj + ".__setitem__(" + idx + ", " + value + ");" |
|
1129 |
return |
|
1130 |
else: |
|
1131 |
raise TranslationError("unsupported flag (in _assign)", v) |
|
1132 |
elif isinstance(v, (ast.AssList, ast.AssTuple)): |
|
1133 |
uniqueID = self.nextTupleAssignID |
|
1134 |
self.nextTupleAssignID += 1 |
|
1135 |
tempName = "__tupleassign" + str(uniqueID) + "__" |
|
1136 |
print >>self.output, " var " + tempName + " = " + \ |
|
1137 |
self.expr(node.expr, current_klass) + ";" |
|
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1738
diff
changeset
|
1138 |
for index, child in enumerate(v.getChildNodes()): |
371 | 1139 |
rhs = tempName + ".__getitem__(" + str(index) + ")" |
1140 |
||
1141 |
if isinstance(child, ast.AssAttr): |
|
1142 |
lhs = _lhsFromAttr(child, current_klass) |
|
1143 |
elif isinstance(child, ast.AssName): |
|
1144 |
lhs = _lhsFromName(child, top_level, current_klass) |
|
1145 |
elif isinstance(child, ast.Subscript): |
|
1146 |
if child.flags == "OP_ASSIGN": |
|
1147 |
obj = self.expr(child.expr, current_klass) |
|
1148 |
if len(child.subs) != 1: |
|
1149 |
raise TranslationError("must have one sub " + |
|
1150 |
"(in _assign)", child) |
|
1151 |
idx = self.expr(child.subs[0], current_klass) |
|
1152 |
value = self.expr(node.expr, current_klass) |
|
1153 |
print >>self.output, " " + obj + ".__setitem__(" \ |
|
1154 |
+ idx + ", " + rhs + ");" |
|
1155 |
continue |
|
1156 |
print >>self.output, " " + lhs + " = " + rhs + ";" |
|
1157 |
return |
|
1158 |
else: |
|
1159 |
raise TranslationError("unsupported type (in _assign)", v) |
|
1160 |
||
1161 |
rhs = self.expr(node.expr, current_klass) |
|
1162 |
if dbg: |
|
1163 |
print "b", repr(node.expr), rhs |
|
1164 |
print >>self.output, " " + lhs + " " + op + " " + rhs + ";" |
|
1165 |
||
1166 |
def _discard(self, node, current_klass): |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
1167 |
|
371 | 1168 |
if isinstance(node.expr, ast.CallFunc): |
1169 |
debugStmt = self.debug and not self._isNativeFunc(node) |
|
1170 |
if debugStmt and isinstance(node.expr.node, ast.Name) and \ |
|
1171 |
node.expr.node.name == 'import_wait': |
|
1172 |
debugStmt = False |
|
1173 |
if debugStmt: |
|
1174 |
st = self.get_line_trace(node) |
|
1175 |
print >>self.output, "sys.addstack('%s');\n" % st |
|
1176 |
if isinstance(node.expr.node, ast.Name) and node.expr.node.name == NATIVE_JS_FUNC_NAME: |
|
1177 |
if len(node.expr.args) != 1: |
|
1178 |
raise TranslationError("native javascript function %s must have one arg" % NATIVE_JS_FUNC_NAME, node.expr) |
|
1179 |
if not isinstance(node.expr.args[0], ast.Const): |
|
1180 |
raise TranslationError("native javascript function %s must have constant arg" % NATIVE_JS_FUNC_NAME, node.expr) |
|
1181 |
raw_js = node.expr.args[0].value |
|
1182 |
print >>self.output, raw_js |
|
1183 |
else: |
|
1184 |
expr = self._callfunc(node.expr, current_klass) |
|
1185 |
print >>self.output, " " + expr + ";" |
|
1186 |
||
1187 |
if debugStmt: |
|
1188 |
print >>self.output, "sys.popstack();\n" |
|
1189 |
||
1190 |
elif isinstance(node.expr, ast.Const): |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
1191 |
if node.expr.value is not None: # Empty statements generate ignore None |
371 | 1192 |
print >>self.output, self._const(node.expr) |
1193 |
else: |
|
1194 |
raise TranslationError("unsupported type (in _discard)", node.expr) |
|
1195 |
||
1196 |
def _if(self, node, current_klass): |
|
1197 |
for i in range(len(node.tests)): |
|
1198 |
test, consequence = node.tests[i] |
|
1199 |
if i == 0: |
|
1200 |
keyword = "if" |
|
1201 |
else: |
|
1202 |
keyword = "else if" |
|
1203 |
||
1204 |
self._if_test(keyword, test, consequence, current_klass) |
|
1205 |
||
1206 |
if node.else_: |
|
1207 |
keyword = "else" |
|
1208 |
test = None |
|
1209 |
consequence = node.else_ |
|
1210 |
||
1211 |
self._if_test(keyword, test, consequence, current_klass) |
|
1212 |
||
1213 |
def _if_test(self, keyword, test, consequence, current_klass): |
|
1214 |
if test: |
|
1215 |
expr = self.expr(test, current_klass) |
|
1216 |
||
1217 |
print >>self.output, " " + keyword + " (pyjslib.bool(" + expr + ")) {" |
|
1218 |
else: |
|
1219 |
print >>self.output, " " + keyword + " {" |
|
1220 |
||
1221 |
if isinstance(consequence, ast.Stmt): |
|
1222 |
for child in consequence.nodes: |
|
1223 |
self._stmt(child, current_klass) |
|
1224 |
else: |
|
1225 |
raise TranslationError("unsupported type (in _if_test)", consequence) |
|
1226 |
||
1227 |
print >>self.output, " }" |
|
1228 |
||
1229 |
def _from(self, node): |
|
1230 |
for name in node.names: |
|
1231 |
# look up "hack" in AppTranslator as to how findFile gets here |
|
1232 |
module_name = node.modname + "." + name[0] |
|
1233 |
try: |
|
1234 |
ff = self.findFile(module_name + ".py") |
|
1235 |
except Exception: |
|
1236 |
ff = None |
|
1237 |
if ff: |
|
1238 |
self.add_imported_module(module_name) |
|
1239 |
else: |
|
1240 |
self.imported_classes[name[0]] = node.modname |
|
1241 |
||
1242 |
def _compare(self, node, current_klass): |
|
1243 |
lhs = self.expr(node.expr, current_klass) |
|
1244 |
||
1245 |
if len(node.ops) != 1: |
|
1246 |
raise TranslationError("only one ops supported (in _compare)", node) |
|
1247 |
||
1248 |
op = node.ops[0][0] |
|
1249 |
rhs_node = node.ops[0][1] |
|
1250 |
rhs = self.expr(rhs_node, current_klass) |
|
1251 |
||
1252 |
if op == "==": |
|
1253 |
return "pyjslib.eq(%s, %s)" % (lhs, rhs) |
|
1254 |
if op == "in": |
|
1255 |
return rhs + ".__contains__(" + lhs + ")" |
|
1256 |
elif op == "not in": |
|
1257 |
return "!" + rhs + ".__contains__(" + lhs + ")" |
|
1258 |
elif op == "is": |
|
1259 |
op = "===" |
|
1260 |
elif op == "is not": |
|
1261 |
op = "!==" |
|
1262 |
||
1263 |
return "(" + lhs + " " + op + " " + rhs + ")" |
|
1264 |
||
1265 |
def _not(self, node, current_klass): |
|
1266 |
expr = self.expr(node.expr, current_klass) |
|
1267 |
||
1268 |
return "!(" + expr + ")" |
|
1269 |
||
1270 |
def _or(self, node, current_klass): |
|
1271 |
expr = "("+(") || (".join([self.expr(child, current_klass) for child in node.nodes]))+')' |
|
1272 |
return expr |
|
1273 |
||
1274 |
def _and(self, node, current_klass): |
|
1275 |
expr = "("+(") && (".join([self.expr(child, current_klass) for child in node.nodes]))+")" |
|
1276 |
return expr |
|
1277 |
||
1278 |
def _for(self, node, current_klass): |
|
1279 |
assign_name = "" |
|
1280 |
assign_tuple = "" |
|
1281 |
||
1282 |
# based on Bob Ippolito's Iteration in Javascript code |
|
1283 |
if isinstance(node.assign, ast.AssName): |
|
1284 |
assign_name = node.assign.name |
|
1285 |
self.add_local_arg(assign_name) |
|
1286 |
if node.assign.flags == "OP_ASSIGN": |
|
1287 |
op = "=" |
|
1288 |
elif isinstance(node.assign, ast.AssTuple): |
|
1289 |
op = "=" |
|
1290 |
i = 0 |
|
1291 |
for child in node.assign: |
|
1292 |
child_name = child.name |
|
1293 |
if assign_name == "": |
|
1294 |
assign_name = "temp_" + child_name |
|
1295 |
self.add_local_arg(child_name) |
|
1296 |
assign_tuple += """ |
|
1297 |
var %(child_name)s %(op)s %(assign_name)s.__getitem__(%(i)i); |
|
1298 |
""" % locals() |
|
1299 |
i += 1 |
|
1300 |
else: |
|
1301 |
raise TranslationError("unsupported type (in _for)", node.assign) |
|
1302 |
||
1303 |
if isinstance(node.list, ast.Name): |
|
1304 |
list_expr = self._name(node.list, current_klass) |
|
1305 |
elif isinstance(node.list, ast.Getattr): |
|
1306 |
list_expr = self._getattr(node.list, current_klass) |
|
1307 |
elif isinstance(node.list, ast.CallFunc): |
|
1308 |
list_expr = self._callfunc(node.list, current_klass) |
|
1309 |
else: |
|
1310 |
raise TranslationError("unsupported type (in _for)", node.list) |
|
1311 |
||
1312 |
lhs = "var " + assign_name |
|
1313 |
iterator_name = "__" + assign_name |
|
1314 |
||
1315 |
print >>self.output, """ |
|
1316 |
var %(iterator_name)s = %(list_expr)s.__iter__(); |
|
1317 |
try { |
|
1318 |
while (true) { |
|
1319 |
%(lhs)s %(op)s %(iterator_name)s.next(); |
|
1320 |
%(assign_tuple)s |
|
1321 |
""" % locals() |
|
1322 |
for node in node.body.nodes: |
|
1323 |
self._stmt(node, current_klass) |
|
1324 |
print >>self.output, """ |
|
1325 |
} |
|
1326 |
} catch (e) { |
|
1327 |
if (e.__name__ != pyjslib.StopIteration.__name__) { |
|
1328 |
throw e; |
|
1329 |
} |
|
1330 |
} |
|
1331 |
""" % locals() |
|
1332 |
||
1333 |
def _while(self, node, current_klass): |
|
1334 |
test = self.expr(node.test, current_klass) |
|
1335 |
print >>self.output, " while (pyjslib.bool(" + test + ")) {" |
|
1336 |
if isinstance(node.body, ast.Stmt): |
|
1337 |
for child in node.body.nodes: |
|
1338 |
self._stmt(child, current_klass) |
|
1339 |
else: |
|
1340 |
raise TranslationError("unsupported type (in _while)", node.body) |
|
1341 |
print >>self.output, " }" |
|
1342 |
||
1343 |
def _const(self, node): |
|
1344 |
if isinstance(node.value, int): |
|
1345 |
return str(node.value) |
|
1346 |
elif isinstance(node.value, float): |
|
1347 |
return str(node.value) |
|
1348 |
elif isinstance(node.value, basestring): |
|
1349 |
v = node.value |
|
1350 |
if isinstance(node.value, unicode): |
|
1351 |
v = v.encode('utf-8') |
|
1738
d2e979738700
clean-up: fix PEP8 E271 multiple spaces after keyword
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1737
diff
changeset
|
1352 |
return "String('%s')" % escapejs(v) |
371 | 1353 |
elif node.value is None: |
1354 |
return "null" |
|
1355 |
else: |
|
1356 |
raise TranslationError("unsupported type (in _const)", node) |
|
1357 |
||
1358 |
def _unaryadd(self, node, current_klass): |
|
1359 |
return self.expr(node.expr, current_klass) |
|
1360 |
||
1361 |
def _unarysub(self, node, current_klass): |
|
1362 |
return "-" + self.expr(node.expr, current_klass) |
|
1363 |
||
1364 |
def _add(self, node, current_klass): |
|
1365 |
return self.expr(node.left, current_klass) + " + " + self.expr(node.right, current_klass) |
|
1366 |
||
1367 |
def _sub(self, node, current_klass): |
|
1368 |
return self.expr(node.left, current_klass) + " - " + self.expr(node.right, current_klass) |
|
1369 |
||
1370 |
def _div(self, node, current_klass): |
|
1371 |
return self.expr(node.left, current_klass) + " / " + self.expr(node.right, current_klass) |
|
1372 |
||
1373 |
def _mul(self, node, current_klass): |
|
1374 |
return self.expr(node.left, current_klass) + " * " + self.expr(node.right, current_klass) |
|
1375 |
||
1376 |
def _mod(self, node, current_klass): |
|
1377 |
if isinstance(node.left, ast.Const) and isinstance(node.left.value, StringType): |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
1378 |
self.imported_js.add("sprintf.js") # Include the sprintf functionality if it is used |
371 | 1379 |
return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")" |
1380 |
return self.expr(node.left, current_klass) + " % " + self.expr(node.right, current_klass) |
|
1381 |
||
1382 |
def _invert(self, node, current_klass): |
|
1383 |
return "~" + self.expr(node.expr, current_klass) |
|
1384 |
||
1385 |
def _bitand(self, node, current_klass): |
|
1386 |
return " & ".join([self.expr(child, current_klass) for child in node.nodes]) |
|
1387 |
||
1388 |
def _bitshiftleft(self, node, current_klass): |
|
1389 |
return self.expr(node.left, current_klass) + " << " + self.expr(node.right, current_klass) |
|
1390 |
||
1391 |
def _bitshiftright(self, node, current_klass): |
|
1392 |
return self.expr(node.left, current_klass) + " >>> " + self.expr(node.right, current_klass) |
|
1393 |
||
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1738
diff
changeset
|
1394 |
def _bitxor(self, node, current_klass): |
371 | 1395 |
return " ^ ".join([self.expr(child, current_klass) for child in node.nodes]) |
1396 |
||
1397 |
def _bitor(self, node, current_klass): |
|
1398 |
return " | ".join([self.expr(child, current_klass) for child in node.nodes]) |
|
1399 |
||
1400 |
def _subscript(self, node, current_klass): |
|
1401 |
if node.flags == "OP_APPLY": |
|
1402 |
if len(node.subs) == 1: |
|
1403 |
return self.expr(node.expr, current_klass) + ".__getitem__(" + self.expr(node.subs[0], current_klass) + ")" |
|
1404 |
else: |
|
1405 |
raise TranslationError("must have one sub (in _subscript)", node) |
|
1406 |
else: |
|
1407 |
raise TranslationError("unsupported flag (in _subscript)", node) |
|
1408 |
||
1409 |
def _subscript_stmt(self, node, current_klass): |
|
1410 |
if node.flags == "OP_DELETE": |
|
1411 |
print >>self.output, " " + self.expr(node.expr, current_klass) + ".__delitem__(" + self.expr(node.subs[0], current_klass) + ");" |
|
1412 |
else: |
|
1413 |
raise TranslationError("unsupported flag (in _subscript)", node) |
|
1414 |
||
1415 |
def _list(self, node, current_klass): |
|
1416 |
return "new pyjslib.List([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])" |
|
1417 |
||
1418 |
def _dict(self, node, current_klass): |
|
1419 |
items = [] |
|
1420 |
for x in node.items: |
|
1421 |
key = self.expr(x[0], current_klass) |
|
1422 |
value = self.expr(x[1], current_klass) |
|
1423 |
items.append("[" + key + ", " + value + "]") |
|
1424 |
return "new pyjslib.Dict([" + ", ".join(items) + "])" |
|
1425 |
||
1426 |
def _tuple(self, node, current_klass): |
|
1427 |
return "new pyjslib.Tuple([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])" |
|
1428 |
||
1429 |
def _lambda(self, node, current_klass): |
|
1430 |
if node.varargs: |
|
1431 |
raise TranslationError("varargs are not supported in Lambdas", node) |
|
1432 |
if node.kwargs: |
|
1433 |
raise TranslationError("kwargs are not supported in Lambdas", node) |
|
1434 |
res = cStringIO.StringIO() |
|
1435 |
arg_names = list(node.argnames) |
|
1436 |
function_args = ", ".join(arg_names) |
|
1437 |
for child in node.getChildNodes(): |
|
1438 |
expr = self.expr(child, None) |
|
1439 |
print >> res, "function (%s){" % function_args |
|
1440 |
self._default_args_handler(node, arg_names, None, |
|
1441 |
output=res) |
|
1442 |
print >> res, 'return %s;}' % expr |
|
1443 |
return res.getvalue() |
|
1444 |
||
1445 |
def _slice(self, node, current_klass): |
|
1446 |
if node.flags == "OP_APPLY": |
|
1447 |
lower = "null" |
|
1448 |
upper = "null" |
|
1743
c3c3d1318130
clean-up: fix PEP8 E711 comparison to None should be 'if cond is not None:'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1742
diff
changeset
|
1449 |
if node.lower is not None: |
371 | 1450 |
lower = self.expr(node.lower, current_klass) |
1743
c3c3d1318130
clean-up: fix PEP8 E711 comparison to None should be 'if cond is not None:'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1742
diff
changeset
|
1451 |
if node.upper is not None: |
371 | 1452 |
upper = self.expr(node.upper, current_klass) |
1738
d2e979738700
clean-up: fix PEP8 E271 multiple spaces after keyword
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1737
diff
changeset
|
1453 |
return "pyjslib.slice(" + self.expr(node.expr, current_klass) + ", " + lower + ", " + upper + ")" |
371 | 1454 |
else: |
1455 |
raise TranslationError("unsupported flag (in _slice)", node) |
|
1456 |
||
1457 |
def _global(self, node, current_klass): |
|
1458 |
for name in node.names: |
|
1459 |
self.method_imported_globals.add(name) |
|
1460 |
||
1461 |
def expr(self, node, current_klass): |
|
1462 |
if isinstance(node, ast.Const): |
|
1463 |
return self._const(node) |
|
1464 |
# @@@ not sure if the parentheses should be here or in individual operator functions - JKT |
|
1465 |
elif isinstance(node, ast.Mul): |
|
1466 |
return " ( " + self._mul(node, current_klass) + " ) " |
|
1467 |
elif isinstance(node, ast.Add): |
|
1468 |
return " ( " + self._add(node, current_klass) + " ) " |
|
1469 |
elif isinstance(node, ast.Sub): |
|
1470 |
return " ( " + self._sub(node, current_klass) + " ) " |
|
1471 |
elif isinstance(node, ast.Div): |
|
1472 |
return " ( " + self._div(node, current_klass) + " ) " |
|
1473 |
elif isinstance(node, ast.Mod): |
|
1474 |
return self._mod(node, current_klass) |
|
1475 |
elif isinstance(node, ast.UnaryAdd): |
|
1476 |
return self._unaryadd(node, current_klass) |
|
1477 |
elif isinstance(node, ast.UnarySub): |
|
1478 |
return self._unarysub(node, current_klass) |
|
1479 |
elif isinstance(node, ast.Not): |
|
1480 |
return self._not(node, current_klass) |
|
1481 |
elif isinstance(node, ast.Or): |
|
1482 |
return self._or(node, current_klass) |
|
1483 |
elif isinstance(node, ast.And): |
|
1484 |
return self._and(node, current_klass) |
|
1485 |
elif isinstance(node, ast.Invert): |
|
1486 |
return self._invert(node, current_klass) |
|
1487 |
elif isinstance(node, ast.Bitand): |
|
1488 |
return "("+self._bitand(node, current_klass)+")" |
|
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1738
diff
changeset
|
1489 |
elif isinstance(node, ast.LeftShift): |
371 | 1490 |
return self._bitshiftleft(node, current_klass) |
1491 |
elif isinstance(node, ast.RightShift): |
|
1492 |
return self._bitshiftright(node, current_klass) |
|
1493 |
elif isinstance(node, ast.Bitxor): |
|
1494 |
return "("+self._bitxor(node, current_klass)+")" |
|
1495 |
elif isinstance(node, ast.Bitor): |
|
1496 |
return "("+self._bitor(node, current_klass)+")" |
|
1497 |
elif isinstance(node, ast.Compare): |
|
1498 |
return self._compare(node, current_klass) |
|
1499 |
elif isinstance(node, ast.CallFunc): |
|
1500 |
return self._callfunc(node, current_klass) |
|
1501 |
elif isinstance(node, ast.Name): |
|
1502 |
return self._name(node, current_klass) |
|
1503 |
elif isinstance(node, ast.Subscript): |
|
1504 |
return self._subscript(node, current_klass) |
|
1505 |
elif isinstance(node, ast.Getattr): |
|
1506 |
return self._getattr(node, current_klass) |
|
1507 |
elif isinstance(node, ast.List): |
|
1508 |
return self._list(node, current_klass) |
|
1509 |
elif isinstance(node, ast.Dict): |
|
1510 |
return self._dict(node, current_klass) |
|
1511 |
elif isinstance(node, ast.Tuple): |
|
1512 |
return self._tuple(node, current_klass) |
|
1513 |
elif isinstance(node, ast.Slice): |
|
1514 |
return self._slice(node, current_klass) |
|
1515 |
elif isinstance(node, ast.Lambda): |
|
1516 |
return self._lambda(node, current_klass) |
|
1517 |
else: |
|
1518 |
raise TranslationError("unsupported type (in expr)", node) |
|
1519 |
||
1520 |
||
1521 |
import cStringIO |
|
1522 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
1523 |
|
371 | 1524 |
def translate(file_name, module_name, debug=False): |
1525 |
f = file(file_name, "r") |
|
1526 |
src = f.read() |
|
1527 |
f.close() |
|
1528 |
output = cStringIO.StringIO() |
|
1529 |
mod = compiler.parseFile(file_name) |
|
1530 |
t = Translator(module_name, module_name, module_name, src, debug, mod, output) |
|
1531 |
return output.getvalue() |
|
1532 |
||
1533 |
||
1534 |
class PlatformParser: |
|
1744
69dfdb26f600
clean-up: fix PEP8 E251 unexpected spaces around keyword / parameter equals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1743
diff
changeset
|
1535 |
def __init__(self, platform_dir="", verbose=True): |
371 | 1536 |
self.platform_dir = platform_dir |
1537 |
self.parse_cache = {} |
|
1538 |
self.platform = "" |
|
1539 |
self.verbose = verbose |
|
1540 |
||
1541 |
def setPlatform(self, platform): |
|
1542 |
self.platform = platform |
|
1543 |
||
1544 |
def parseModule(self, module_name, file_name): |
|
1545 |
||
1546 |
importing = False |
|
1547 |
if not self.parse_cache.has_key(file_name): |
|
1548 |
importing = True |
|
1549 |
mod = compiler.parseFile(file_name) |
|
1550 |
self.parse_cache[file_name] = mod |
|
1551 |
else: |
|
1552 |
mod = self.parse_cache[file_name] |
|
1553 |
||
1554 |
override = False |
|
1555 |
platform_file_name = self.generatePlatformFilename(file_name) |
|
1556 |
if self.platform and os.path.isfile(platform_file_name): |
|
1557 |
mod = copy.deepcopy(mod) |
|
1558 |
mod_override = compiler.parseFile(platform_file_name) |
|
1559 |
self.merge(mod, mod_override) |
|
1560 |
override = True |
|
1561 |
||
1562 |
if self.verbose: |
|
1563 |
if override: |
|
1564 |
print "Importing %s (Platform %s)" % (module_name, self.platform) |
|
1565 |
elif importing: |
|
1566 |
print "Importing %s" % (module_name) |
|
1567 |
||
1568 |
return mod, override |
|
1569 |
||
1570 |
def generatePlatformFilename(self, file_name): |
|
1571 |
(module_name, extension) = os.path.splitext(os.path.basename(file_name)) |
|
1572 |
platform_file_name = module_name + self.platform + extension |
|
1573 |
||
1574 |
return os.path.join(os.path.dirname(file_name), self.platform_dir, platform_file_name) |
|
1575 |
||
1576 |
def merge(self, tree1, tree2): |
|
1577 |
for child in tree2.node: |
|
1578 |
if isinstance(child, ast.Function): |
|
1579 |
self.replaceFunction(tree1, child.name, child) |
|
1580 |
elif isinstance(child, ast.Class): |
|
1581 |
self.replaceClassMethods(tree1, child.name, child) |
|
1582 |
||
1583 |
return tree1 |
|
1584 |
||
1585 |
def replaceFunction(self, tree, function_name, function_node): |
|
1586 |
# find function to replace |
|
1587 |
for child in tree.node: |
|
1588 |
if isinstance(child, ast.Function) and child.name == function_name: |
|
1589 |
self.copyFunction(child, function_node) |
|
1590 |
return |
|
1591 |
raise TranslationError("function not found: " + function_name, function_node) |
|
1592 |
||
1593 |
def replaceClassMethods(self, tree, class_name, class_node): |
|
1594 |
# find class to replace |
|
1595 |
old_class_node = None |
|
1596 |
for child in tree.node: |
|
1597 |
if isinstance(child, ast.Class) and child.name == class_name: |
|
1598 |
old_class_node = child |
|
1599 |
break |
|
1600 |
||
1601 |
if not old_class_node: |
|
1602 |
raise TranslationError("class not found: " + class_name, class_node) |
|
1603 |
||
1604 |
# replace methods |
|
1605 |
for function_node in class_node.code: |
|
1606 |
if isinstance(function_node, ast.Function): |
|
1607 |
found = False |
|
1608 |
for child in old_class_node.code: |
|
1609 |
if isinstance(child, ast.Function) and child.name == function_node.name: |
|
1610 |
found = True |
|
1611 |
self.copyFunction(child, function_node) |
|
1612 |
break |
|
1613 |
||
1614 |
if not found: |
|
1615 |
raise TranslationError("class method not found: " + class_name + "." + function_node.name, function_node) |
|
1616 |
||
1617 |
def copyFunction(self, target, source): |
|
1618 |
target.code = source.code |
|
1619 |
target.argnames = source.argnames |
|
1620 |
target.defaults = source.defaults |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
1621 |
target.doc = source.doc # @@@ not sure we need to do this any more |
371 | 1622 |
|
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
1623 |
|
371 | 1624 |
def dotreplace(fname): |
1625 |
path, ext = os.path.splitext(fname) |
|
1626 |
return path.replace(".", "/") + ext |
|
1627 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
1628 |
|
371 | 1629 |
class AppTranslator: |
1630 |
||
1631 |
def __init__(self, library_dirs=[], parser=None, dynamic=False, |
|
1632 |
optimize=False, verbose=True): |
|
1633 |
self.extension = ".py" |
|
1634 |
self.optimize = optimize |
|
1635 |
self.library_modules = [] |
|
1636 |
self.overrides = {} |
|
1637 |
self.library_dirs = path + library_dirs |
|
1638 |
self.dynamic = dynamic |
|
1639 |
self.verbose = verbose |
|
1640 |
||
1641 |
if not parser: |
|
1642 |
self.parser = PlatformParser() |
|
1643 |
else: |
|
1644 |
self.parser = parser |
|
1645 |
||
1646 |
self.parser.dynamic = dynamic |
|
1647 |
||
1648 |
def findFile(self, file_name): |
|
1649 |
if os.path.isfile(file_name): |
|
1650 |
return file_name |
|
1651 |
||
1652 |
for library_dir in self.library_dirs: |
|
1653 |
file_name = dotreplace(file_name) |
|
1654 |
full_file_name = os.path.join( |
|
1655 |
os.path.abspath(os.path.dirname(__file__)), library_dir, file_name) |
|
1656 |
if os.path.isfile(full_file_name): |
|
1657 |
return full_file_name |
|
1658 |
||
1659 |
fnameinit, ext = os.path.splitext(file_name) |
|
1660 |
fnameinit = fnameinit + "/__init__.py" |
|
1661 |
||
1662 |
full_file_name = os.path.join( |
|
1663 |
os.path.abspath(os.path.dirname(__file__)), library_dir, fnameinit) |
|
1664 |
if os.path.isfile(full_file_name): |
|
1665 |
return full_file_name |
|
1666 |
||
1667 |
raise Exception("file not found: " + file_name) |
|
1668 |
||
1669 |
def _translate(self, module_name, is_app=True, debug=False, |
|
1670 |
imported_js=set()): |
|
1671 |
if module_name not in self.library_modules: |
|
1672 |
self.library_modules.append(module_name) |
|
1673 |
||
1674 |
file_name = self.findFile(module_name + self.extension) |
|
1675 |
||
1676 |
output = cStringIO.StringIO() |
|
1677 |
||
1678 |
f = file(file_name, "r") |
|
1679 |
src = f.read() |
|
1680 |
f.close() |
|
1681 |
||
1682 |
mod, override = self.parser.parseModule(module_name, file_name) |
|
1683 |
if override: |
|
1684 |
override_name = "%s.%s" % (self.parser.platform.lower(), |
|
1685 |
module_name) |
|
1686 |
self.overrides[override_name] = override_name |
|
1687 |
if is_app: |
|
1688 |
mn = '__main__' |
|
1689 |
else: |
|
1690 |
mn = module_name |
|
1691 |
t = Translator(mn, module_name, module_name, |
|
1692 |
src, debug, mod, output, self.dynamic, self.optimize, |
|
1693 |
self.findFile) |
|
1694 |
||
1695 |
module_str = output.getvalue() |
|
1696 |
imported_js.update(set(t.imported_js)) |
|
1697 |
imported_modules_str = "" |
|
1698 |
for module in t.imported_modules: |
|
1699 |
if module not in self.library_modules: |
|
1700 |
self.library_modules.append(module) |
|
1701 |
#imported_js.update(set(t.imported_js)) |
|
1702 |
#imported_modules_str += self._translate( |
|
1703 |
# module, False, debug=debug, imported_js=imported_js) |
|
1704 |
||
1705 |
return imported_modules_str + module_str |
|
1706 |
||
1707 |
def translate(self, module_name, is_app=True, debug=False, |
|
1708 |
library_modules=[]): |
|
1709 |
app_code = cStringIO.StringIO() |
|
1710 |
lib_code = cStringIO.StringIO() |
|
1711 |
imported_js = set() |
|
1712 |
self.library_modules = [] |
|
1713 |
self.overrides = {} |
|
1714 |
for library in library_modules: |
|
1715 |
if library.endswith(".js"): |
|
1716 |
imported_js.add(library) |
|
1717 |
continue |
|
1718 |
self.library_modules.append(library) |
|
1719 |
if self.verbose: |
|
1720 |
print 'Including LIB', library |
|
1721 |
print >> lib_code, '\n//\n// BEGIN LIB '+library+'\n//\n' |
|
1722 |
print >> lib_code, self._translate( |
|
1723 |
library, False, debug=debug, imported_js=imported_js) |
|
1724 |
||
1725 |
print >> lib_code, "/* initialize static library */" |
|
1726 |
print >> lib_code, "%s%s();\n" % (UU, library) |
|
1727 |
||
1728 |
print >> lib_code, '\n//\n// END LIB '+library+'\n//\n' |
|
1729 |
if module_name: |
|
1730 |
print >> app_code, self._translate( |
|
1731 |
module_name, is_app, debug=debug, imported_js=imported_js) |
|
1732 |
for js in imported_js: |
|
1733 |
path = self.findFile(js) |
|
1734 |
if os.path.isfile(path): |
|
1735 |
if self.verbose: |
|
1736 |
print 'Including JS', js |
|
1737 |
print >> lib_code, '\n//\n// BEGIN JS '+js+'\n//\n' |
|
1738 |
print >> lib_code, file(path).read() |
|
1739 |
print >> lib_code, '\n//\n// END JS '+js+'\n//\n' |
|
1740 |
else: |
|
1741 |
print >>sys.stderr, 'Warning: Unable to find imported javascript:', js |
|
1742 |
return lib_code.getvalue(), app_code.getvalue() |
|
1743 |
||
1749
d73b64672238
clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1746
diff
changeset
|
1744 |
|
371 | 1745 |
usage = """ |
1746 |
usage: %s file_name [module_name] |
|
1747 |
""" |
|
1748 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1734
diff
changeset
|
1749 |
|
371 | 1750 |
def main(): |
1751 |
import sys |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
1752 |
if len(sys.argv) < 2: |
371 | 1753 |
print >> sys.stderr, usage % sys.argv[0] |
1754 |
sys.exit(1) |
|
1755 |
file_name = os.path.abspath(sys.argv[1]) |
|
1756 |
if not os.path.isfile(file_name): |
|
1757 |
print >> sys.stderr, "File not found %s" % file_name |
|
1758 |
sys.exit(1) |
|
1759 |
if len(sys.argv) > 2: |
|
1760 |
module_name = sys.argv[2] |
|
1761 |
else: |
|
1762 |
module_name = None |
|
1763 |
print translate(file_name, module_name), |
|
1764 |
||
1749
d73b64672238
clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1746
diff
changeset
|
1765 |
|
371 | 1766 |
if __name__ == "__main__": |
1767 |
main() |