Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 269 lines (241 sloc) 8.743 kb
bdf2920 add java2py for converting java to python duh
lkcl authored
1 #!/usr/bin/env python
2 """ Use this to help speed up manual conversion of e.g. GWT Java to e.g.
3 Pyjamas python
44969bc identify need for replacing variables with self.variable
lkcl authored
4
5 TODO: in java2pythonlinebyline and redofunctions, identify a list
6 of variables and functions, and do replace "variable" with "self.variable"
bdf2920 add java2py for converting java to python duh
lkcl authored
7 """
8
9 import sys
7790a8c add redo functions, few more javaisms
lkcl authored
10 import string
bdf2920 add java2py for converting java to python duh
lkcl authored
11
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
12 def import_gwt_to_pyjamas(txt):
13 """ this bit is specifically hard-coded to deal with gwt-dnd
14 conversion. almost everything else is "generic" java-to-python
15 """
16 if txt.startswith("package "):
17 return ''
18 if not txt.startswith('import '):
19 return txt
20 if txt == 'import com.google.gwt.dom.client.NativeEvent;':
21 return 'from pyjamas.ui import Event'
22 if txt.startswith('import com.google.gwt.user.client.ui.'):
23 module = txt[37:-1]
24 return "from pyjamas.ui.%s import %s" % (module, module)
25 if txt.startswith('import com.google.gwt.user.client.'):
26 module = txt[34:-1]
27 if module == 'Element':
28 return ''
29 return "from pyjamas import %s" % module
30 if txt.startswith('import com.allen_sauer.gwt.dnd.client.drop.'):
31 module = txt[43:-1]
32 return "from pyjamas.dnd.drop import %s" % module
33 if txt.startswith('import com.allen_sauer.gwt.dnd.client.util.'):
34 module = txt[43:-1]
35 return "from pyjamas.dnd.util import %s" % module
a051f0d more gchart update
lkcl authored
36 if txt.startswith('import com.googlecode.gchart.client.'):
37 module = txt[36:-1]
38 if module == 'GChart':
39 return "from pyjamas.chart.GChart import GChart"
40 return "from pyjamas.chart import %s" % module
41
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
42 if txt.startswith('import com.allen_sauer.gwt.dnd.client.'):
43 module = txt[38:-1]
44 return "from pyjamas.dnd import %s" % module
45 return ''
46
47 def convert_stupid_js_import_to_stupid_js_import(txt):
48 """ this is GWT-to-PyJS-specific conversion: support of assembly-like
49 direct insertion of javascript. again, it's one of the few bits
50 of non-generic java-to-python
51 """
52 txt = txt.replace("/*-{", '{\nJS("""')
53 txt = txt.replace("}-*/", '""")\n}')
54 return txt
55
56 def join_single_open_brace_to_previous_line(txt):
57 res = []
58 for l in txt.split("\n"):
59 x = l.strip()
60 if x == '{':
61 res[-1] += (' {')
62 else:
63 res.append(l)
64 return '\n'.join(res)
65
37c4846 more java2py
lkcl authored
66 def countspaces(txt):
67 count = 0
68 while count < len(txt) and txt[count] == ' ':
69 count += 1
70 return count
7790a8c add redo functions, few more javaisms
lkcl authored
71
bdf2920 add java2py for converting java to python duh
lkcl authored
72 def java2pythonlinebyline(txt):
73 if txt.find('if (') >= 0:
f69f162 using java2py to convert GChart
lkcl authored
74 if not txt.strip().endswith("{"):
75 print txt
76 error # deliberate error on lines with no {
bdf2920 add java2py for converting java to python duh
lkcl authored
77 txt = txt.replace('if (', 'if ')
7790a8c add redo functions, few more javaisms
lkcl authored
78 txt = txt.replace('!', 'not ')
79 txt = txt.replace('not =', '!=') # whoops
bdf2920 add java2py for converting java to python duh
lkcl authored
80 txt = txt.replace(') {', ':')
f418e18 add exception support, more convert && and || etc.
lkcl authored
81 elif txt.endswith("else {"):
82 txt = txt.replace('else {', 'else:')
37c4846 more java2py
lkcl authored
83 elif txt.find('class ') >= 0 and txt.endswith("{"):
84 txt = txt.replace('{', ':')
f418e18 add exception support, more convert && and || etc.
lkcl authored
85 elif txt.find('try {') >= 0:
86 txt = txt.replace('try {', 'try:')
87 elif txt.find('} catch') >= 0:
88 txt = txt.replace('} catch', 'except')
f69f162 using java2py to convert GChart
lkcl authored
89 elif txt.find('finally {') >= 0:
90 txt = txt.replace('finally {', 'except:')
37c4846 more java2py
lkcl authored
91 elif txt.find('while (') >= 0:
92 txt = txt.replace('while (', 'while ')
93 txt = txt.replace(') {', ':')
94 elif txt.find('for (') >= 0:
95 txt = txt.replace('for (', 'for ')
96 txt = txt.replace(') {', ':')
97 count = countspaces(txt)
98 if txt[count:].startswith("}"):
99 txt = count * ' ' + txt[count+1:]
100
101 if txt[count:].startswith("protected ") >= 0:
44969bc identify need for replacing variables with self.variable
lkcl authored
102 # TODO: check if "class" in current line, add class name
103 # otherwise assume last word of line is variable
37c4846 more java2py
lkcl authored
104 txt = txt.replace("protected ", "")
105 if txt[count:].startswith("public ") >= 0:
44969bc identify need for replacing variables with self.variable
lkcl authored
106 # TODO: check if "class" in current line, add class name
107 # otherwise assume last word of line is variable
37c4846 more java2py
lkcl authored
108 txt = txt.replace("public ", "")
109 if txt[count:].startswith("private ") >= 0:
44969bc identify need for replacing variables with self.variable
lkcl authored
110 # TODO: check if "class" in current line, add class name
111 # otherwise assume last word of line is variable e.g.
112 # private final Area >>>targetArea<<<;
37c4846 more java2py
lkcl authored
113 txt = txt.replace("private ", "")
114 if txt[count:].startswith("static ") >= 0:
115 txt = txt.replace("static ", "")
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
116 if txt[count:].startswith("native ") >= 0:
117 txt = txt.replace("native ", "")
37c4846 more java2py
lkcl authored
118 if txt[count:].startswith("final ") >= 0:
119 txt = txt.replace("final ", "")
7790a8c add redo functions, few more javaisms
lkcl authored
120 if txt.endswith(";"):
121 txt = txt[:-1]
122 if txt.endswith(" :"):
123 txt = txt[:-2] + ":"
124
bdf2920 add java2py for converting java to python duh
lkcl authored
125 return txt
126
7790a8c add redo functions, few more javaisms
lkcl authored
127 def redofunctions(txt):
f69f162 using java2py to convert GChart
lkcl authored
128 if txt.strip().startswith("#"):
129 return txt
7790a8c add redo functions, few more javaisms
lkcl authored
130 if not txt.endswith("{"):
131 return txt
132 lbr = txt.find("(")
133 rbr = txt.find(") {")
134 if lbr == -1 or rbr == -1 or lbr > rbr:
135 return txt
f418e18 add exception support, more convert && and || etc.
lkcl authored
136 lbr2 = txt.find("(", lbr+1)
137 if lbr2 > 0:
138 return txt
7790a8c add redo functions, few more javaisms
lkcl authored
139 count = countspaces(txt)
140 pre = txt[count:lbr]
141 args = txt[lbr+1:rbr]
142
f69f162 using java2py to convert GChart
lkcl authored
143 if pre.strip() == 'switch':
144 return txt
145
f418e18 add exception support, more convert && and || etc.
lkcl authored
146 is_exception = 0
147 if pre.find("except") >= 0:
148 is_exception = 1
7790a8c add redo functions, few more javaisms
lkcl authored
149 else:
f418e18 add exception support, more convert && and || etc.
lkcl authored
150 pre = map(string.strip, pre.split(' '))
151 if len(pre) == 1: # assume it's a constructor
152 pre = '__init__'
153 elif len(pre) == 2:
154 pre = pre[-1] # drop the first word (return type)
155 else:
f69f162 using java2py to convert GChart
lkcl authored
156 print txt, pre
f418e18 add exception support, more convert && and || etc.
lkcl authored
157 error # deliberately cause error - investigate 3-word thingies!
7790a8c add redo functions, few more javaisms
lkcl authored
158
159 args = map(string.strip, args.split(','))
160 newargs = []
161 for arg in args:
162 if arg == '':
163 continue
164 arg = map(string.strip, arg.split(' '))
165 if len(arg) == 2:
166 newargs.append(arg[1]) # drop first word (arg type)
167 else:
f69f162 using java2py to convert GChart
lkcl authored
168 print txt
7790a8c add redo functions, few more javaisms
lkcl authored
169 print pre, args, arg
170 error # deliberately cause error - find out why arg no type
f418e18 add exception support, more convert && and || etc.
lkcl authored
171 if count != 0 and not is_exception:
7790a8c add redo functions, few more javaisms
lkcl authored
172 # assume class not global function - add self
173 newargs = ['self'] + newargs
174 newargs = ', '.join(newargs)
f418e18 add exception support, more convert && and || etc.
lkcl authored
175 if is_exception:
176 return "%s%s%s:" % (count*' ', pre, newargs)
7790a8c add redo functions, few more javaisms
lkcl authored
177 return "%sdef %s(%s):" % (count*' ', pre, newargs)
178
bdf2920 add java2py for converting java to python duh
lkcl authored
179 def reindent(txt):
37c4846 more java2py
lkcl authored
180 """ reindents according to { and } braces. strips all whitespace,
181 possibly not smartest thing to do. oh well.
182 """
bdf2920 add java2py for converting java to python duh
lkcl authored
183 res = ''
184 indent = 0
185 for l in txt.split("\n"):
186 l = l.strip()
187 if l.startswith("}"):
188 indent -= 1
f69f162 using java2py to convert GChart
lkcl authored
189 if indent < 0:
190 res += "INDENT ERROR"
bdf2920 add java2py for converting java to python duh
lkcl authored
191 res += ' ' * indent + l + "\n"
192 if l.endswith("{"):
193 indent += 1
194 return res
195
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
196 def java_replace(txt, rep, repwith):
197 res = ''
198 while txt:
199 i = txt.find('JS("""')
200 if i == -1:
201 return res + txt.replace(rep, repwith)
202 j = txt.find('""")', i)
203 if (j == -1):
204 error # whoops
205 res += txt[:i].replace(rep, repwith) + txt[i:j]
206 txt = txt[j:]
207 return txt
208
209 def java_linemap(fn, lines):
210
211 res = []
212 in_stupid_js = False
213
214 for l in lines:
215
216 if in_stupid_js:
217 res.append(l)
218 if l.find('""")') >= 0:
219 in_stupid_js = False
220 continue
221
222 if l.find('JS("""') >= 0:
223 in_stupid_js = True
224 res.append(l)
225 continue
64eff55 @xtfxme find * -name '*.py' | xargs sed -i -r 's,\s+$,,'
xtfxme authored
226
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
227 res.append(fn(l))
228
229 return res
230
bdf2920 add java2py for converting java to python duh
lkcl authored
231 def java2python(txt):
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
232 txt = txt.replace("\r\n", '\n') # yuk dos files.
233 txt = convert_stupid_js_import_to_stupid_js_import(txt)
234 txt = join_single_open_brace_to_previous_line(txt)
bdf2920 add java2py for converting java to python duh
lkcl authored
235 txt = reindent(txt)
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
236 txt = java_replace(txt, "/*", '"""')
237 txt = java_replace(txt, "*/", '"""')
238 txt = java_replace(txt, "<>", '!=')
239 txt = java_replace(txt, "&&", ' and ')
240 txt = java_replace(txt, "||", ' or ')
241 txt = java_replace(txt, "null", 'None')
242 txt = java_replace(txt, "!= None", 'is not None')
243 txt = java_replace(txt, "== None", 'is None')
244 txt = java_replace(txt, "throw ", 'raise ')
245 txt = java_replace(txt, "true", 'True')
246 txt = java_replace(txt, "false", 'False')
247 txt = java_replace(txt, "//", '#')
248 txt = java_replace(txt, "this.", 'self.')
249 txt = java_replace(txt, "else if", 'elif')
250 txt = java_replace(txt, "new ", '')
bdf2920 add java2py for converting java to python duh
lkcl authored
251 l = txt.split("\n")
5d618ba support JS(""" .... """) and deal with imports
lkcl authored
252 l = java_linemap(import_gwt_to_pyjamas, l)
253 l = java_linemap(java2pythonlinebyline, l)
254 l = java_linemap(redofunctions, l)
255 txt = java_replace(txt, "}", '')
bdf2920 add java2py for converting java to python duh
lkcl authored
256 return '\n'.join(l)
257
258 if __name__ == "__main__":
7f7bfcf add 1st revision of HTML5 video and audio
Luke Leighton authored
259 fnames = sys.argv[1:]
260 for fname in fnames:
261 f = open(fname, "r")
262 txt = java2python(f.read())
263 f.close()
bdf2920 add java2py for converting java to python duh
lkcl authored
264
7f7bfcf add 1st revision of HTML5 video and audio
Luke Leighton authored
265 f = open(fname[:-5] + ".py", "w")
266 f.write(txt)
267 f.close()
bdf2920 add java2py for converting java to python duh
lkcl authored
268
Something went wrong with that request. Please try again.