forked from natural/java2python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathj2py
More file actions
executable file
·210 lines (175 loc) · 6.4 KB
/
Copy pathj2py
File metadata and controls
executable file
·210 lines (175 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict
from logging import _levelNames as logLevels, exception, warning, info, basicConfig
from optparse import Option, OptionParser, OptionValueError
from os import path
from time import time
from java2python.compiler import Module, buildAST, transformAST
from java2python.config import Config
from java2python.lib.colortools import colors
version = '0.5'
def isWindows():
return sys.platform.startswith('win')
def badLogLevel(name, value):
msg = 'option %s: invalid loglevel: %r'
raise OptionValueError(msg % (name, value))
def checkLogLevel(option, opt, value):
try:
lvl = int(value)
except (ValueError, ):
name = value.upper()
if name not in logLevels:
badLogLevel(opt, value)
lvl = logLevels[name]
else:
if lvl not in logLevels:
badLogLevel(opt, value)
return lvl
class LocalOption(Option):
TYPES = Option.TYPES + ('loglevel', )
TYPE_CHECKER = Option.TYPE_CHECKER.copy()
TYPE_CHECKER['loglevel'] = checkLogLevel
def mainProfile(options):
if options.profile:
import cProfile, pstats
prof = cProfile.Profile()
prof.runcall(main, options)
stats = pstats.Stats(prof, stream=sys.stderr)
stats.strip_dirs().sort_stats('cumulative')
stats.print_stats().print_callers()
return 0
else:
return main(options)
def configFromDir(inname, dirname):
name = path.join(dirname, path.basename(path.splitext(inname)[0]))
return '%s.py' % path.abspath(name)
def main(options):
timed = defaultdict(time)
timed['overall']
filein = fileout = filedefault = '-'
if options.inputfile and not isinstance(options.inputfile, file):
filein = options.inputfile
if options.outputfile and not isinstance(options.outputfile, file):
fileout = path.basename(options.outputfile)
elif fileout != filedefault:
fileout = '%s.py' % (path.splitext(filein)[0])
configs = options.configs
if options.configdir and not isinstance(filein, file):
dirconfigname = configFromDir(filein, options.configdir)
if path.exists(dirconfigname):
configs.insert(0, dirconfigname)
if options.includedefaults:
configs.insert(0, 'java2python.config.default')
try:
if filein != '-':
source = open(filein).read()
else:
source = sys.stdin.read()
except (IOError, ), exc:
code, msg = exc.args[0:2]
print 'IOError: %s.' % (msg, )
return code
config = Config(configs)
timed['comp']
try:
tree = buildAST(source, config)
except (Exception, ), exc:
exception('exception while parsing')
return 1
timed['comp_finish']
timed['xform']
transformAST(tree, config)
timed['xform_finish']
timed['visit']
module = Module(config)
module.sourceFilename = path.abspath(filein) if filein != '-' else None
module.name = path.splitext(path.basename(filein))[0] if filein != '-' else '<stdin>'
module.walk(tree)
timed['visit_finish']
timed['encode']
source = unicode(module)
timed['encode_finish']
timed['overall_finish']
if options.javaast:
tree.dump(sys.stderr)
print >> sys.stderr
if options.pytree:
module.dumpRepr(sys.stderr)
print >> sys.stderr
if not options.skipsource:
if fileout == filedefault:
output = sys.stdout
else:
output = open(fileout, 'w')
module.name = path.splitext(filein)[0] if filein != '-' else '<stdin>'
print >> output, source
try:
compile(source, '<string>', 'exec')
except (SyntaxError, ), ex:
warning('Generated source has invalid syntax. %s', ex)
else:
info('Generated source has valid syntax.')
info('Parse: %.4f seconds', timed['comp_finish'] - timed['comp'])
info('Visit: %.4f seconds', timed['visit_finish'] - timed['visit'])
info('Transform: %.4f seconds', timed['xform_finish'] - timed['xform'])
info('Encode: %.4f seconds', timed['encode_finish'] - timed['encode'])
info('Total: %.4f seconds', timed['overall_finish'] - timed['overall'])
return 0
def config(argv):
parser = OptionParser(option_class=LocalOption, version='%prog '+version)
addopt = parser.add_option
addopt('-i', '--input', dest='inputfile',
help='Read from INPUTFILE. May use - for stdin.',
metavar='INPUTFILE', default=None)
addopt('-o', '--output', dest='outputfile',
help='Write to OUTPUTFILE. May use - for stdout.',
metavar='OUTPUTFILE', default=None)
addopt('-c', '--config', dest='configs',
help='Use CONFIG file or module. May be repeated.',
metavar='CONFIG', default=[],
action='append')
addopt('-d', '--configdir', dest='configdir',
help='Use DIR to match input filename with config filename.',
metavar='DIR', default=None)
addopt('-n', '--nodefaults', dest='includedefaults',
help='Ignore default configuration module.',
default=True, action='store_false')
addopt('-l', '--loglevel', dest='loglevel',
help='Set log level by name or value.',
default='WARN', type='loglevel')
addopt('-p', '--python-tree', dest='pytree',
help='Print python object tree to stderr.',
default=False, action='store_true')
addopt('-j', '--java-ast', dest='javaast',
help='Print java source AST tree to stderr.',
default=False, action='store_true')
addopt('-f', '--profile', dest='profile',
help='Profile execution and print results to stderr.',
default=False, action='store_true')
addopt('-s', '--skip-source', dest='skipsource',
help='Skip writing translated source; useful when printing trees',
default=False, action='store_true')
addopt('-r', '--nocolor', dest='nocolor',
help='Disable color output.' +\
(' No effect on Win OS.' if isWindows() else ''),
default=False, action='store_true')
options, args = parser.parse_args(argv)
if len(args) > 2:
parser.error('Only one input file supported.')
elif len(args) == 2:
options.inputfile = args[1]
if options.inputfile == '-':
options.inputfile = sys.stdin
if options.outputfile == '-':
options.outputfile = sys.stdout
## these next statements don't belong here, but this is as good a
## place as any.
if isWindows() or options.nocolor:
colors.clear()
fmt = '# %(levelname)s %(funcName)s: %(message)s'
basicConfig(level=options.loglevel, format=fmt)
return options
if __name__ == '__main__':
sys.exit(mainProfile(config(sys.argv)))