X Tutup
Skip to content

Commit b877794

Browse files
author
Troy Melhase
committed
Initial support for configuration modules.
Doc string updates.
1 parent 661544c commit b877794

File tree

4 files changed

+99
-63
lines changed

4 files changed

+99
-63
lines changed

bin/java_to_python

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def transform(options):
5050
else:
5151
output = open(fileout, 'w')
5252

53-
set_config(options.configs)
53+
set_config(options.configs, options.includedefaults)
5454
M = Module(filein, fileout)
5555
W.walk(ast, M)
5656
print >> output, M
@@ -69,7 +69,9 @@ def cli_options(argv):
6969
help='use CONFIG (multiple allowed)',
7070
metavar='CONFIG', default=[],
7171
action='append')
72-
72+
parser.add_option('-n', '--nodefaults', dest='includedefaults',
73+
help='ignore default configuration',
74+
default=True, action='store_false')
7375
options, args = parser.parse_args(argv)
7476
return options, args
7577

lib/defaultconfig.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434

3535

36-
globalSubs = [
36+
outputSubs = [
3737
(r'(\.self\.)', '.'),
3838
(r'String\.valueOf\((.*?)\)', r'str(\1)'),
3939
(r'System\.out\.println\((.*?)\)', r'print \1'),
@@ -43,3 +43,40 @@
4343
(r'([\w.]+)\.size\(\)', r'len(\1)'),
4444
(r'(\w+)\.get\((.*?)\)', r'\1[\2]'),
4545
]
46+
47+
48+
typeTypeMap = {
49+
'String':'str',
50+
'int':'int',
51+
'double':'float',
52+
'Vector':'list',
53+
'boolean':'bool',
54+
}
55+
56+
57+
typeValueMap = {
58+
'String':'""',
59+
'int':'0',
60+
'double':'0.0',
61+
'Vector':'[]',
62+
'boolean':'False',
63+
'str':'""',
64+
}
65+
66+
67+
renameMethodMap = {
68+
'equals':'__eq__'
69+
}
70+
71+
72+
renameAnyMap = {
73+
'this':'self',
74+
'null':'None',
75+
'false':'False',
76+
'true':'True',
77+
}
78+
79+
80+
modifierDecoratorMap = {
81+
'synchronized':'@synchronized(mlock)'
82+
}

lib/sourcetypes.py

Lines changed: 52 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,20 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3-
"""
4-
todo:
5-
add project override, file override options
6-
done:
7-
fix empty type declarations
8-
fix while, for statements
9-
add decorator for overloaded methods
10-
fix compound expressions
11-
add property get/set on duplicate method names
12-
reorder class statements to place inner classes first
13-
fix missing self references (in expressions w/o all values defined)
14-
add property for some modifiers (e.g., syncronized)
15-
for classes without bases, add object as base
16-
for classes that implement something, add something as base
3+
""" java2python.lib.sourcetypes -> heirarchy of classes for building source.
4+
5+
176
"""
187
from cStringIO import StringIO
198
import re
209

2110

22-
I = ' ' * 4
23-
24-
2511
def import_name(name):
2612
""" import_name(name) -> import and return a module by name in dotted form
2713
28-
Copied from the Python lib docs.
14+
Copied from the Python lib docs.
15+
16+
@param name module or package name in dotted form
17+
@return module object
2918
"""
3019
mod = __import__(name)
3120
for comp in name.split('.')[1:]:
@@ -34,56 +23,54 @@ def import_name(name):
3423

3524

3625
def set_config(names, includeDefault=True):
26+
""" build and set a Config object on the Source class
27+
28+
@param names sequence of module names
29+
@keyparam includeDefault=True flag to include default configuration module
30+
@return None
31+
"""
3732
if includeDefault:
3833
names.insert(0, 'java2python.lib.defaultconfig')
3934
Source.config = Config(*names)
4035

4136

4237
class Config:
38+
""" Config -> wraps multiple configuration modules
39+
40+
41+
"""
4342
def __init__(self, *names):
4443
self.configs = [import_name(name) for name in names]
44+
45+
def all(self, name, missing=None):
46+
""" value of name in each config module
47+
48+
@param name module attribute as string
49+
@keyparam missing=None default for missing attributes
50+
@return list of values
51+
"""
52+
return [getattr(config, name, missing) for config in self.configs]
4553

46-
def get(self, name, default=None):
47-
for config in self.configs:
54+
def last(self, name, default=None):
55+
"""
56+
57+
"""
58+
for config in reversed(self.configs):
4859
if hasattr(config, name):
4960
return getattr(config, name)
5061
return default
5162

52-
def all(self, name, missing=None):
53-
return [getattr(config, name, missing) for config in self.configs]
63+
def combined(self, name):
64+
combined = {}
65+
for mapping in reversed(self.all(name, {})):
66+
combined.update(mapping)
67+
return combined
5468

5569

56-
class Source:
57-
typeTypeMap = {
58-
'String':'str',
59-
'int':'int',
60-
'double':'float',
61-
'Vector':'list',
62-
'boolean':'bool',
63-
}
64-
65-
typeValueMap = {
66-
'String':'""',
67-
'int':'0',
68-
'double':'0.0',
69-
'Vector':'[]',
70-
'boolean':'False',
71-
'str':'""',
72-
}
73-
74-
renameMap = {
75-
'this':'self',
76-
'null':'None',
77-
'false':'False',
78-
'true':'True',
79-
'equals':'__eq__',
80-
}
81-
82-
modifierDecoratorMap = {
83-
'synchronized':'@synchronized(mlock)'
84-
}
70+
I = ' ' * 4
8571

8672

73+
class Source:
8774
emptyAssign = ('%s', '<empty>')
8875
missingValue = ('%s', '<missing>')
8976
unknownExpression = ('%s', '<unknown>')
@@ -102,8 +89,9 @@ def __str__(self):
10289
out = StringIO()
10390
self.writeTo(out, 0)
10491
source = out.getvalue()
105-
#for sub in astextra.globalSubs:
106-
# source = re.sub(sub[0], sub[1], source)
92+
for subs in self.config.all('outputSubs', []):
93+
for sub in subs:
94+
source = re.sub(sub[0], sub[1], source)
10795
return source
10896

10997
def addComment(self, text):
@@ -172,7 +160,7 @@ def newFor(self):
172160
self.addSource(f)
173161
return s, f
174162

175-
def newMethod(self, name=''):
163+
def newMethod(self, name=None):
176164
m = Method(parent=self, name=name)
177165
self.addSource(m)
178166
return m
@@ -201,8 +189,9 @@ def formatExpression(self, s):
201189
return (self.formatExpression(s[0]), self.formatExpression(s[1]))
202190

203191
def reName(self, value):
192+
mapping = self.config.combined('renameAnyMap')
204193
try:
205-
return self.renameMap[value]
194+
return mapping[value]
206195
except (KeyError, ):
207196
return value
208197

@@ -350,7 +339,7 @@ def __init__(self, parent, name):
350339

351340
def addModifier(self, mod):
352341
try:
353-
mod = self.modifierDecoratorMap[mod]
342+
mod = self.config.combined("modifierDecoratorMap")[mod]
354343
except (KeyError, ):
355344
Source.addModifier(self, mod)
356345
else:
@@ -374,6 +363,13 @@ def formatDecl(self, indent):
374363
decl = '%sdef %s(%s):' % (I * indent, name, params)
375364
return decl
376365

366+
def reName(self, value):
367+
mapping = self.config.combined('renameMethodMap')
368+
try:
369+
return mapping[value]
370+
except (KeyError, ):
371+
return value
372+
377373
def writeTo(self, output, indent):
378374
offset = I * indent
379375
output.write('\n')

lib/walker.g

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ returns [spec]
6565
{
6666
value = t0.getFirstChild().getText()
6767
try:
68-
spec = block.typeTypeMap[value]
68+
spec = block.config.combined("typeTypeMap")[value]
6969
except (KeyError, ):
7070
spec = value
7171
}
@@ -219,7 +219,7 @@ variable_def [block]
219219
{
220220
block.addVariable(dec[1])
221221
if val == block.emptyAssign:
222-
val = ("%s", block.typeValueMap.get(typ, "%s()" % typ))
222+
val = ("%s", block.config.combined("typeValueMap").get(typ, "%s()" % typ))
223223
block.addSource( ("%s = %s", (dec, val)) )
224224
}
225225
;
@@ -732,12 +732,13 @@ returns [value = block.missingValue]
732732
)
733733
)
734734
{
735+
alltypes = block.config.combined("typeValueMap")
735736
if arrdecl:
736737
value = ("[%s() for __idx0 in range(%s)]", (("%s", typ), ("%s", arrdecl)))
737738
elif exp:
738739
value = ("%s(%s)", (("%s", typ), ("%s", exp)))
739-
elif typ in block.typeValueMap:
740-
value = ("%s", block.typeValueMap[typ])
740+
elif typ in alltypes:
741+
value = ("%s", alltypes[typ])
741742
else:
742743
value = ("%s()", typ)
743744
}

0 commit comments

Comments
 (0)
X Tutup