Debian Codegraph @

rpython/translator/goal/translate.py

raw symbols SCIP
1 #! /usr/bin/env pypy
2 """
3 Command-line options for translate:
4
5 See below
6 """
7
8 import os
9 import sys
10 import py
11 from rpython.config.config import (to_optparse, OptionDescription, BoolOption,
12 ArbitraryOption, StrOption, IntOption, Config, ChoiceOption, OptHelpFormatter)
13 from rpython.config.translationoption import (get_combined_translation_config,
14 set_opt_level, OPT_LEVELS, DEFAULT_OPT_LEVEL, set_platform, CACHE_DIR)
15
16 # clean up early rpython/_cache
17 try:
18 py.path.local(CACHE_DIR).remove()
19 except Exception:
20 pass
21
22
23 GOALS = [
24 ("annotate", "do type inference", "-a --annotate", ""),
25 ("rtype", "do rtyping", "-t --rtype", ""),
26 ("pyjitpl", "JIT generation step", "--pyjitpl", ""),
27 ("jittest", "JIT test with llgraph backend", "--pyjittest", ""),
28 ("backendopt", "do backend optimizations", "--backendopt", ""),
29 ("source", "create source", "-s --source", ""),
30 ("compile", "compile", "-c --compile", " (default goal)"),
31 ("llinterpret", "interpret the rtyped flow graphs", "--llinterpret", ""),
32 ]
33
34
35 def goal_options():
36 result = []
37 for name, doc, cmdline, extra in GOALS:
38 optional = False
39 if name.startswith('?'):
40 optional = True
41 name = name[1:]
42 yesdoc = doc[0].upper() + doc[1:] + extra
43 result.append(BoolOption(name, yesdoc, default=False, cmdline=cmdline,
44 negation=False))
45 if not optional:
46 result.append(BoolOption("no_%s" % name, "Don't " + doc, default=False,
47 cmdline="--no-" + name, negation=False))
48 return result
49
50 translate_optiondescr = OptionDescription("translate", "XXX", [
51 StrOption("targetspec", "XXX", default='targetpypystandalone',
52 cmdline=None),
53 ChoiceOption("opt",
54 "optimization level", OPT_LEVELS, default=DEFAULT_OPT_LEVEL,
55 cmdline="--opt -O"),
56 BoolOption("profile",
57 "cProfile (to debug the speed of the translation process)",
58 default=False,
59 cmdline="--profile"),
60 BoolOption("pdb",
61 "Always run pdb even if the translation succeeds",
62 default=False,
63 cmdline="--pdb"),
64 BoolOption("batch", "Don't run interactive helpers", default=False,
65 cmdline="--batch", negation=False),
66 IntOption("huge", "Threshold in the number of functions after which "
67 "a local call graph and not a full one is displayed",
68 default=100, cmdline="--huge"),
69 BoolOption("view", "Start the pygame viewer", default=False,
70 cmdline="--view", negation=False),
71 BoolOption("help", "show this help message and exit", default=False,
72 cmdline="-h --help", negation=False),
73 BoolOption("fullhelp", "show full help message and exit", default=False,
74 cmdline="--full-help", negation=False),
75 ArbitraryOption("goals", "XXX",
76 defaultfactory=list),
77 # xxx default goals ['annotate', 'rtype', 'backendopt', 'source', 'compile']
78 ArbitraryOption("skipped_goals", "XXX",
79 defaultfactory=list),
80 OptionDescription("goal_options",
81 "Goals that should be reached during translation",
82 goal_options()),
83 ])
84
85 import optparse
86 from rpython.tool.ansi_print import AnsiLogger
87 log = AnsiLogger("translation")
88
89 def load_target(targetspec):
90 log.info("Translating target as defined by %s" % targetspec)
91 if not targetspec.endswith('.py'):
92 targetspec += '.py'
93 thismod = sys.modules[__name__]
94 sys.modules['translate'] = thismod
95 specname = os.path.splitext(os.path.basename(targetspec))[0]
96 sys.path.insert(0, os.path.dirname(targetspec))
97 mod = __import__(specname)
98 if 'target' not in mod.__dict__:
99 raise Exception("file %r is not a valid targetxxx.py." % (targetspec,))
100 return mod.__dict__
101
102 def parse_options_and_load_target():
103 opt_parser = optparse.OptionParser(usage="%prog [options] [target] [target-specific-options]",
104 prog="translate",
105 formatter=OptHelpFormatter(),
106 add_help_option=False)
107
108 opt_parser.disable_interspersed_args()
109
110 config = get_combined_translation_config(translating=True)
111 to_optparse(config, parser=opt_parser, useoptions=['translation.*'])
112 translateconfig = Config(translate_optiondescr)
113 to_optparse(translateconfig, parser=opt_parser)
114
115 options, args = opt_parser.parse_args()
116
117 # set goals and skipped_goals
118 reset = False
119 for name, _, _, _ in GOALS:
120 if name.startswith('?'):
121 continue
122 if getattr(translateconfig.goal_options, name):
123 if name not in translateconfig.goals:
124 translateconfig.goals.append(name)
125 if getattr(translateconfig.goal_options, 'no_' + name):
126 if name not in translateconfig.skipped_goals:
127 if not reset:
128 translateconfig.skipped_goals[:] = []
129 reset = True
130 translateconfig.skipped_goals.append(name)
131
132 if args:
133 arg = args[0]
134 args = args[1:]
135 if os.path.isfile(arg + '.py'):
136 assert not os.path.isfile(arg), (
137 "ambiguous file naming, please rename %s" % arg)
138 translateconfig.targetspec = arg
139 elif os.path.isfile(arg) and arg.endswith('.py'):
140 translateconfig.targetspec = arg[:-3]
141 else:
142 log.ERROR("Could not find target %r" % (arg, ))
143 sys.exit(1)
144 else:
145 show_help(translateconfig, opt_parser, None, config)
146
147 # print the version of the host
148 # (if it's PyPy, it includes the hg checksum)
149 log.info(sys.version)
150
151 # apply the platform settings
152 set_platform(config)
153
154 targetspec = translateconfig.targetspec
155 targetspec_dic = load_target(targetspec)
156
157 if args and not targetspec_dic.get('take_options', False):
158 log.WARNING("target specific arguments supplied but will be ignored: %s" % ' '.join(args))
159
160 # give the target the possibility to get its own configuration options
161 # into the config
162 if 'get_additional_config_options' in targetspec_dic:
163 optiondescr = targetspec_dic['get_additional_config_options']()
164 config = get_combined_translation_config(
165 optiondescr,
166 existing_config=config,
167 translating=True)
168
169 config.translation.rpython_translate = True
170
171 # show the target-specific help if --help was given
172 show_help(translateconfig, opt_parser, targetspec_dic, config)
173
174 # apply the optimization level settings
175 set_opt_level(config, translateconfig.opt)
176
177 # let the target modify or prepare itself
178 # based on the config
179 if 'handle_config' in targetspec_dic:
180 targetspec_dic['handle_config'](config, translateconfig)
181
182 return targetspec_dic, translateconfig, config, args
183
184 def show_help(translateconfig, opt_parser, targetspec_dic, config):
185 if translateconfig.help:
186 if targetspec_dic is None:
187 opt_parser.print_help()
188 print "\n\nDefault target: %s" % translateconfig.targetspec
189 print "Run '%s --help %s' for target-specific help" % (
190 sys.argv[0], translateconfig.targetspec)
191 elif 'print_help' in targetspec_dic:
192 print "\n\nTarget specific help for %s:\n\n" % (
193 translateconfig.targetspec,)
194 targetspec_dic['print_help'](config)
195 else:
196 print "\n\nNo target-specific help available for %s" % (
197 translateconfig.targetspec,)
198 print "\n\nFor detailed descriptions of the command line options see"
199 print "http://pypy.readthedocs.org/en/latest/config/commandline.html"
200 sys.exit(0)
201
202 def log_options(options, header="options in effect"):
203 # list options (xxx filter, filter for target)
204 log('%s:' % header)
205 optnames = options.__dict__.keys()
206 optnames.sort()
207 for name in optnames:
208 optvalue = getattr(options, name)
209 log('%25s: %s' % (name, optvalue))
210
211 def log_config(config, header="config used"):
212 log('%s:' % header)
213 log(str(config))
214 for warning in config.get_warnings():
215 log.WARNING(warning)
216
217 def main():
218 sys.setrecursionlimit(2000) # PyPy can't translate within cpython's 1k limit
219 targetspec_dic, translateconfig, config, args = parse_options_and_load_target()
220 from rpython.translator import translator
221 from rpython.translator import driver
222 from rpython.translator.tool.pdbplus import PdbPlusShow
223
224 if translateconfig.view:
225 translateconfig.pdb = True
226
227 if translateconfig.profile:
228 from cProfile import Profile
229 prof = Profile()
230 prof.enable()
231 else:
232 prof = None
233
234 t = translator.TranslationContext(config=config)
235
236 pdb_plus_show = PdbPlusShow(t) # need a translator to support extended commands
237
238 def finish_profiling():
239 if prof:
240 prof.disable()
241 statfilename = 'prof.dump'
242 log.info('Dumping profiler stats to: %s' % statfilename)
243 prof.dump_stats(statfilename)
244
245 def debug(got_error):
246 tb = None
247 if got_error:
248 import traceback
249 stacktrace_errmsg = ["Error:\n"]
250 exc, val, tb = sys.exc_info()
251 stacktrace_errmsg.extend([" %s" % line for line in traceback.format_tb(tb)])
252 summary_errmsg = traceback.format_exception_only(exc, val)
253 block = getattr(val, '__annotator_block', None)
254 if block:
255 class FileLike:
256 def write(self, s):
257 summary_errmsg.append(" %s" % s)
258 summary_errmsg.append("Processing block:\n")
259 t.about(block, FileLike())
260 log.info(''.join(stacktrace_errmsg))
261 log.ERROR(''.join(summary_errmsg))
262 else:
263 log.event('Done.')
264
265 if translateconfig.batch:
266 log.event("batch mode, not calling interactive helpers")
267 return
268
269 log.event("start debugger...")
270
271 if translateconfig.view:
272 try:
273 t1 = drv.hint_translator
274 except (NameError, AttributeError):
275 t1 = t
276 from rpython.translator.tool import graphpage
277 page = graphpage.TranslatorPage(t1, translateconfig.huge)
278 page.display_background()
279
280 pdb_plus_show.start(tb)
281
282 try:
283 drv = driver.TranslationDriver.from_targetspec(targetspec_dic, config, args,
284 empty_translator=t,
285 disable=translateconfig.skipped_goals,
286 default_goal='compile')
287 log_config(translateconfig, "translate.py configuration")
288 if config.translation.jit:
289 if (translateconfig.goals != ['annotate'] and
290 translateconfig.goals != ['rtype']):
291 drv.set_extra_goals(['pyjitpl'])
292 # early check:
293 from rpython.jit.backend.detect_cpu import getcpuclassname
294 getcpuclassname(config.translation.jit_backend)
295
296 log_config(config.translation, "translation configuration")
297 pdb_plus_show.expose({'drv': drv, 'prof': prof})
298
299 if config.translation.output:
300 drv.exe_name = config.translation.output
301 elif drv.exe_name is None and '__name__' in targetspec_dic:
302 drv.exe_name = targetspec_dic['__name__'] + '-%(backend)s'
303
304 # Double check to ensure we are not overwriting the current interpreter
305 goals = translateconfig.goals
306 if not goals or 'compile' in goals:
307 try:
308 this_exe = py.path.local(sys.executable).new(ext='')
309 exe_name = drv.compute_exe_name()
310 samefile = this_exe.samefile(exe_name)
311 assert not samefile, (
312 'Output file %s is the currently running '
313 'interpreter (please move the executable, and '
314 'possibly its associated libpypy-c, somewhere else '
315 'before you execute it)' % exe_name)
316 except EnvironmentError:
317 pass
318
319 try:
320 drv.proceed(goals)
321 finally:
322 drv.timer.pprint()
323 except SystemExit:
324 raise
325 except:
326 finish_profiling()
327 debug(True)
328 raise SystemExit(1)
329 else:
330 finish_profiling()
331 if translateconfig.pdb:
332 debug(False)
333
334
335 if __name__ == '__main__':
336 main()