Skip to content

Commit 0dbe3cd

Browse files
committed
Map None to None_ while keep null as None. Fix bugs in constructor, and make SuperCtorTest pass
1 parent adb1b8a commit 0dbe3cd

File tree

3 files changed

+138
-51
lines changed

3 files changed

+138
-51
lines changed

java2python/lib/defaultconfig.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@
180180
'or':'or_',
181181
'print':'print_',
182182
'None':'None_',
183+
'null':'None',
183184
}
184185

185186

java2python/lib/sourcetypes.py

Lines changed: 110 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def addSourceBefore(self, value, stat=None):
177177
if isinstance(stat, int):
178178
idx = stat
179179
else:
180-
idx = -2 if stat == None else self.lines.index(stat)
180+
idx = 0 if stat == None else self.lines.index(stat)
181181
self.lines.insert(idx, value)
182182
else:
183183
self.lines.append(value)
@@ -224,23 +224,46 @@ def allVars(self):
224224
yield v
225225

226226
@property
227-
def allMembers(self):
228-
""" all member variables in this class
227+
def methodVars(self):
228+
""" all vars declared in the current method
229229
230-
@return yields all member names from this class
230+
@return yeilds all vars declared in the method
231+
"""
232+
233+
for obj in [self, ] + list(self.allParents):
234+
for v in obj.variables:
235+
yield v.name
236+
if isinstance(obj, Method): break
237+
238+
@property
239+
def instanceMembers(self):
240+
""" all instance members in this class
241+
242+
@return yields all instance member names from this class
231243
"""
232244
for obj in [self, ] + list(self.allParents):
233245
if isinstance(obj, Class):
234246
for v in obj.variables:
235-
yield v.name
236-
for v in obj.methods:
237-
yield v.name
247+
if not v.isStatic:
248+
yield v.name
238249
for v in obj.extraVars:
239250
yield v
240251

252+
@property
253+
def instanceMethods(self):
254+
""" all instance methods in this class
255+
256+
@return yields all instance method names from this class
257+
"""
258+
for obj in [self, ] + list(self.allParents):
259+
if isinstance(obj, Class):
260+
for v in obj.methods:
261+
if not v.isStatic:
262+
yield v.name
263+
241264
@property
242265
def staticMembers(self):
243-
""" all static member variable in this class
266+
""" all static members in this class
244267
245268
@return yields static member names from this class
246269
"""
@@ -250,6 +273,18 @@ def staticMembers(self):
250273
if v.isStatic:
251274
yield v.name
252275

276+
@property
277+
def staticMethods(self):
278+
""" all static methods in this class
279+
280+
@return yields static method names from this class
281+
"""
282+
for obj in [self, ] + list(self.allParents):
283+
if isinstance(obj, Class):
284+
for v in obj.methods:
285+
if v.isStatic:
286+
yield v.name
287+
253288
@property
254289
def extraVars(self):
255290
""" extra variable names; subclasses can and should reimplement
@@ -289,6 +324,14 @@ def isMethod(self):
289324
"""
290325
return isinstance(self, Method)
291326

327+
@property
328+
def isStatic(self):
329+
""" True if this instance is static
330+
331+
@return if the variable is static return True
332+
"""
333+
return 'static' in self.modifiers
334+
292335
@property
293336
def declFormat(self):
294337
""" string format for variable names in this block
@@ -324,20 +367,23 @@ def fixDecl(self, *args):
324367
@return fixed name or names
325368
"""
326369
fixed = list(args)
327-
allvars = list(self.allMembers)
328-
staticvars = list(self.staticMembers)
370+
methodvars = list(self.methodVars)
371+
membervars = list(self.instanceMembers) + list(self.instanceMethods)
372+
staticvars = list(self.staticMembers) + list(self.staticMethods)
329373
mapping = self.config.combined('variableNameMapping')
330374
format = self.declFormat
331-
if not self.isClass:
332-
for i, arg in enumerate(args):
333-
if arg in staticvars:
334-
arg = mapping.get(arg, arg)
335-
fixed[i] = "%s.%s" % (self.className, arg)
336-
elif arg in allvars:
337-
arg = mapping.get(arg, arg)
338-
fixed[i] = format % (arg, )
339-
else:
340-
fixed[i] = mapping.get(arg, arg)
375+
for i, arg in enumerate(args):
376+
if arg in methodvars:
377+
arg = mapping.get(arg, arg)
378+
fixed[i] = arg
379+
elif arg in staticvars:
380+
arg = mapping.get(arg, arg)
381+
fixed[i] = "%s.%s" % (self.className, arg)
382+
elif arg in membervars:
383+
arg = mapping.get(arg, arg)
384+
fixed[i] = format % (arg, )
385+
else:
386+
fixed[i] = mapping.get(arg, arg)
341387
if len(fixed) == 1:
342388
return fixed[0]
343389
else:
@@ -447,7 +493,7 @@ def formatExpression(self, expr):
447493
elif isinstance(first, basestring) and isinstance(second, tuple):
448494
return fixdecl(first) % format(second)
449495
elif isinstance(first, tuple) and isinstance(second, basestring):
450-
return format(first) % format(second)
496+
return format(first) % fixdecl(second)
451497
elif isinstance(first, tuple) and isinstance(second, tuple):
452498
return (format(first), format(second))
453499
else:
@@ -631,6 +677,21 @@ def addBaseClass(self, name):
631677
name = self.formatExpression(name)
632678
self.bases.append(name)
633679

680+
def fixDecl(self, *args):
681+
""" fixes variable names that are class members
682+
683+
@varparam args names to fix
684+
@return fixed name or names
685+
"""
686+
ret = list(args)
687+
for i, arg in enumerate(args):
688+
if self.className != arg:
689+
ret[i] = Source.fixDecl(self, arg)
690+
if len(ret) > 1:
691+
return ret
692+
else:
693+
return ret[0]
694+
634695
def formatDecl(self):
635696
""" generates a class statement accounting for base types
636697
@@ -724,19 +785,37 @@ def F_0(...)
724785
method.preamble.append('@%s.register(%s)' % (firstname, params))
725786
method.name = '%s_%s' % (method.name, index)
726787

727-
def declVars(self):
788+
def fixCtor(self):
728789
"""Declare class member vars in init method
729790
730791
"""
731-
meth = None
732-
if "__init__" in list(self.allMembers):
733-
meth = self.newMethod("__init_vars__")
734-
elif len(self.variables) > 0:
735-
meth = self.newMethod("__init__")
736-
if meth:
737-
for v in self.variables:
738-
if not v.isStatic:
739-
meth.addSource(("self.%s = %s", (("%s", v.name), v.expr)))
792+
found = False
793+
for meth in self.methods:
794+
if meth.name == '__init__':
795+
found = True
796+
break
797+
if not found and len(list(self.instanceMembers)) > 0:
798+
meth = self.newMethod('__init__')
799+
meth.calledSuperCtor = False
800+
meth.calledOtherCtor = False
801+
802+
for meth in self.methods:
803+
if meth.name == '__init__':
804+
if not (meth.calledSuperCtor or meth.calledOtherCtor):
805+
meth.addSourceBefore("super(%s, self).__init__()" % meth.className, 0)
806+
meth.stmtAfterSuper = meth.newStatementBefore("if", 1)
807+
808+
if not meth.calledOtherCtor:
809+
stmt = meth.stmtAfterSuper
810+
meth.addSourceBefore("# begin of instance variables", stmt)
811+
for v in self.variables:
812+
if not v.isStatic:
813+
meth.addSourceBefore(
814+
("self.%s = %s", (("%s", v.name), v.expr)),
815+
stmt)
816+
idx = meth.lines.index(stmt)
817+
meth.lines[idx] = "# end of instance variables"
818+
740819

741820
def writeTo(self, output, indent):
742821
""" writes the string representation of this block
@@ -968,10 +1047,3 @@ def setExpression(self, expr):
9681047
"""
9691048
self.expr = expr
9701049

971-
@property
972-
def isStatic(self):
973-
"""Check is this variable a static variable
974-
975-
@return if the variable is static return True
976-
"""
977-
return 'static' in self.modifiers

java2python/lib/walker.g

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ returns [typ]
9797

9898
builtin_type [block]
9999
returns [typ]
100-
: "void" {typ = "None" }
100+
: "void" {typ = "null" }
101101
| "boolean" {typ = "bool" }
102102
| "byte" {typ = "str" }
103103
| "char" {typ = "str" }
@@ -167,22 +167,21 @@ obj_block [block]
167167
| method_def[block]
168168
| variable_def[block, False]
169169
| typ = type_def[block]
170-
| #(STATIC_INIT statement_list[block])
170+
| static_init[block]
171171
| #(INSTANCE_INIT statement_list[block])
172172
)*
173173
)
174-
{ block.declVars() }
174+
{ block.fixCtor() }
175175
;
176176

177177

178178
ctor_def [block]
179179
: {
180180
meth = block.newMethod()
181+
meth.calledSuperCtor = False
182+
meth.calledOtherCtor = False
181183
}
182184
#(CTOR_DEF
183-
{
184-
meth.addSource("self.__init_vars__()")
185-
}
186185
modifiers[meth]
187186
method_head[meth, "__init__"]
188187
(statement_list[meth])?
@@ -244,14 +243,24 @@ variable_def [block, append = True]
244243
)
245244
{
246245
if val == block.emptyAssign:
247-
val = ("%s", block.config.combined("typeValueMap").get(typ, "None"))
246+
val = ("%s", block.config.combined("typeValueMap").get(typ, "null"))
248247
var.setName(dec[1])
249248
var.setExpression(val)
250249
if append or var.isStatic:
251250
block.addSource( ("%s = %s", (dec, val)) )
252251
}
253252
;
254253

254+
static_init [block]
255+
: #(STATIC_INIT
256+
{
257+
if not hasattr(block, "static_init"):
258+
block.static_init = block.newMethod("__static_init__")
259+
block.static_init.addModifier("static")
260+
block.parent.addSource("%s.__static_init__()\n" % block.className)
261+
}
262+
statement_list[block.static_init])
263+
;
255264

256265
parameter_def [meth, exc=False]
257266
: #(pd0:PARAMETER_DEF
@@ -386,7 +395,7 @@ statement [block]
386395
}
387396
#("for"
388397
#(FOR_INIT
389-
((variable_def[for_init])+ | for_exp = expr_list[for_init])?)
398+
((variable_def[for_init])+ | for_exp = expr_list[for_init, True])?)
390399
#(FOR_CONDITION (for_cond = expression[for_stat, False])?)
391400
#(FOR_ITERATOR (for_iter = expr_list[for_stat, False])?)
392401
statement[for_stat]
@@ -463,7 +472,7 @@ statement [block]
463472
}
464473
#("return" (return_value = expression[block, False])? )
465474
{
466-
if return_value in (None, ("%s", "None")):
475+
if return_value in (None, ("%s", "null")):
467476
block.addSource("return")
468477
else:
469478
block.addSource(("return %s", return_value))
@@ -695,15 +704,15 @@ returns [exp = block.unknownExpression]
695704

696705
| #(NOT_EQUAL left=expr[block] right=expr[block])
697706
{
698-
if right in ("None", (("%s", "None"))):
707+
if right in ("null", (("%s", "null"))):
699708
exp = ("%s is not %s", (left, right))
700709
else:
701710
exp = ("(%s != %s)", (left, right))
702711
}
703712

704713
| #(EQUAL left=expr[block] right=expr[block])
705714
{
706-
if right in ("None", (("%s", "None"))):
715+
if right in ("null", (("%s", "null"))):
707716
exp = ("%s is %s", (left, right))
708717
else:
709718
exp = ("(%s == %s)", (left, right))
@@ -842,7 +851,7 @@ returns [exp = block.missingValue]
842851
| "true" {exp = ("%s", "True" )}
843852
| "false" {exp = ("%s", "False" )}
844853
| "this" {exp = ("%s", "self" )}
845-
| "null" {exp = ("%s", "None" )}
854+
| "null" {exp = ("%s", "null" )}
846855
// type name used with instanceof
847856
| typ = type_spec[block] {exp = ("%s", typ)}
848857
;
@@ -852,8 +861,9 @@ ctor_call [block]
852861
: #(cn:CTOR_CALL seq=expr_list[block, False] )
853862
{
854863
name = block.parent.name
855-
call = ("super(%s, self).__init__(%s)", (("%s", name), ("%s", seq)))
864+
call = ("self.__init__(%s)", ("%s", seq))
856865
block.addSource(call)
866+
block.calledOtherCtor = True
857867
}
858868

859869
| #(SUPER_CTOR_CALL
@@ -868,6 +878,10 @@ ctor_call [block]
868878
block.addSource(call)
869879
}
870880
)
881+
{
882+
block.calledSuperCtor = True
883+
block.stmtAfterSuper = block.newStatement("if")
884+
}
871885
;
872886

873887

0 commit comments

Comments
 (0)