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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
|
#! /usr/bin/env pypy
"""
Command-line options for translate:
See below
"""
import os
import sys
import py
from rpython.config.config import (to_optparse, OptionDescription, BoolOption,
ArbitraryOption, StrOption, IntOption, Config, ChoiceOption, OptHelpFormatter)
from rpython.config.translationoption import (get_combined_translation_config,
set_opt_level, OPT_LEVELS, DEFAULT_OPT_LEVEL, set_platform, CACHE_DIR)
# clean up early rpython/_cache
try:
py.path.local(CACHE_DIR).remove()
except Exception:
pass
GOALS = [
("annotate", "do type inference", "-a --annotate", ""),
("rtype", "do rtyping", "-t --rtype", ""),
("pyjitpl", "JIT generation step", "--pyjitpl", ""),
("jittest", "JIT test with llgraph backend", "--pyjittest", ""),
("backendopt", "do backend optimizations", "--backendopt", ""),
("source", "create source", "-s --source", ""),
("compile", "compile", "-c --compile", " (default goal)"),
("llinterpret", "interpret the rtyped flow graphs", "--llinterpret", ""),
]
def goal_options():
result = []
for name, doc, cmdline, extra in GOALS:
optional = False
if name.startswith('?'):
optional = True
name = name[1:]
yesdoc = doc[0].upper() + doc[1:] + extra
result.append(BoolOption(name, yesdoc, default=False, cmdline=cmdline,
negation=False))
if not optional:
result.append(BoolOption("no_%s" % name, "Don't " + doc, default=False,
cmdline="--no-" + name, negation=False))
return result
translate_optiondescr = OptionDescription("translate", "XXX", [
StrOption("targetspec", "XXX", default='targetpypystandalone',
cmdline=None),
ChoiceOption("opt",
"optimization level", OPT_LEVELS, default=DEFAULT_OPT_LEVEL,
cmdline="--opt -O"),
BoolOption("profile",
"cProfile (to debug the speed of the translation process)",
default=False,
cmdline="--profile"),
BoolOption("pdb",
"Always run pdb even if the translation succeeds",
default=False,
cmdline="--pdb"),
BoolOption("batch", "Don't run interactive helpers", default=False,
cmdline="--batch", negation=False),
IntOption("huge", "Threshold in the number of functions after which "
"a local call graph and not a full one is displayed",
default=100, cmdline="--huge"),
BoolOption("view", "Start the pygame viewer", default=False,
cmdline="--view", negation=False),
BoolOption("help", "show this help message and exit", default=False,
cmdline="-h --help", negation=False),
BoolOption("fullhelp", "show full help message and exit", default=False,
cmdline="--full-help", negation=False),
ArbitraryOption("goals", "XXX",
defaultfactory=list),
# xxx default goals ['annotate', 'rtype', 'backendopt', 'source', 'compile']
ArbitraryOption("skipped_goals", "XXX",
defaultfactory=list),
OptionDescription("goal_options",
"Goals that should be reached during translation",
goal_options()),
])
import optparse
from rpython.tool.ansi_print import AnsiLogger
log = AnsiLogger("translation")
def load_target(targetspec):
log.info("Translating target as defined by %s" % targetspec)
if not targetspec.endswith('.py'):
targetspec += '.py'
thismod = sys.modules[__name__]
sys.modules['translate'] = thismod
specname = os.path.splitext(os.path.basename(targetspec))[0]
sys.path.insert(0, os.path.dirname(targetspec))
mod = __import__(specname)
if 'target' not in mod.__dict__:
raise Exception("file %r is not a valid targetxxx.py." % (targetspec,))
return mod.__dict__
def parse_options_and_load_target():
opt_parser = optparse.OptionParser(usage="%prog [options] [target] [target-specific-options]",
prog="translate",
formatter=OptHelpFormatter(),
add_help_option=False)
opt_parser.disable_interspersed_args()
config = get_combined_translation_config(translating=True)
to_optparse(config, parser=opt_parser, useoptions=['translation.*'])
translateconfig = Config(translate_optiondescr)
to_optparse(translateconfig, parser=opt_parser)
options, args = opt_parser.parse_args()
# set goals and skipped_goals
reset = False
for name, _, _, _ in GOALS:
if name.startswith('?'):
continue
if getattr(translateconfig.goal_options, name):
if name not in translateconfig.goals:
translateconfig.goals.append(name)
if getattr(translateconfig.goal_options, 'no_' + name):
if name not in translateconfig.skipped_goals:
if not reset:
translateconfig.skipped_goals[:] = []
reset = True
translateconfig.skipped_goals.append(name)
if args:
arg = args[0]
args = args[1:]
if os.path.isfile(arg + '.py'):
assert not os.path.isfile(arg), (
"ambiguous file naming, please rename %s" % arg)
translateconfig.targetspec = arg
elif os.path.isfile(arg) and arg.endswith('.py'):
translateconfig.targetspec = arg[:-3]
else:
log.ERROR("Could not find target %r" % (arg, ))
sys.exit(1)
else:
show_help(translateconfig, opt_parser, None, config)
# print the version of the host
# (if it's PyPy, it includes the hg checksum)
log.info(sys.version)
# apply the platform settings
set_platform(config)
targetspec = translateconfig.targetspec
targetspec_dic = load_target(targetspec)
if args and not targetspec_dic.get('take_options', False):
log.WARNING("target specific arguments supplied but will be ignored: %s" % ' '.join(args))
# give the target the possibility to get its own configuration options
# into the config
if 'get_additional_config_options' in targetspec_dic:
optiondescr = targetspec_dic['get_additional_config_options']()
config = get_combined_translation_config(
optiondescr,
existing_config=config,
translating=True)
# show the target-specific help if --help was given
show_help(translateconfig, opt_parser, targetspec_dic, config)
# apply the optimization level settings
set_opt_level(config, translateconfig.opt)
# let the target modify or prepare itself
# based on the config
if 'handle_config' in targetspec_dic:
targetspec_dic['handle_config'](config, translateconfig)
return targetspec_dic, translateconfig, config, args
def show_help(translateconfig, opt_parser, targetspec_dic, config):
if translateconfig.help:
if targetspec_dic is None:
opt_parser.print_help()
print "\n\nDefault target: %s" % translateconfig.targetspec
print "Run '%s --help %s' for target-specific help" % (
sys.argv[0], translateconfig.targetspec)
elif 'print_help' in targetspec_dic:
print "\n\nTarget specific help for %s:\n\n" % (
translateconfig.targetspec,)
targetspec_dic['print_help'](config)
else:
print "\n\nNo target-specific help available for %s" % (
translateconfig.targetspec,)
print "\n\nFor detailed descriptions of the command line options see"
print "http://pypy.readthedocs.org/en/latest/config/commandline.html"
sys.exit(0)
def log_options(options, header="options in effect"):
# list options (xxx filter, filter for target)
log('%s:' % header)
optnames = options.__dict__.keys()
optnames.sort()
for name in optnames:
optvalue = getattr(options, name)
log('%25s: %s' % (name, optvalue))
def log_config(config, header="config used"):
log('%s:' % header)
log(str(config))
for warning in config.get_warnings():
log.WARNING(warning)
def main():
sys.setrecursionlimit(2000) # PyPy can't translate within cpython's 1k limit
targetspec_dic, translateconfig, config, args = parse_options_and_load_target()
from rpython.translator import translator
from rpython.translator import driver
from rpython.translator.tool.pdbplus import PdbPlusShow
if translateconfig.view:
translateconfig.pdb = True
if translateconfig.profile:
from cProfile import Profile
prof = Profile()
prof.enable()
else:
prof = None
t = translator.TranslationContext(config=config)
pdb_plus_show = PdbPlusShow(t) # need a translator to support extended commands
def finish_profiling():
if prof:
prof.disable()
statfilename = 'prof.dump'
log.info('Dumping profiler stats to: %s' % statfilename)
prof.dump_stats(statfilename)
def debug(got_error):
tb = None
if got_error:
import traceback
stacktrace_errmsg = ["Error:\n"]
exc, val, tb = sys.exc_info()
stacktrace_errmsg.extend([" %s" % line for line in traceback.format_tb(tb)])
summary_errmsg = traceback.format_exception_only(exc, val)
block = getattr(val, '__annotator_block', None)
if block:
class FileLike:
def write(self, s):
summary_errmsg.append(" %s" % s)
summary_errmsg.append("Processing block:\n")
t.about(block, FileLike())
log.info(''.join(stacktrace_errmsg))
log.ERROR(''.join(summary_errmsg))
else:
log.event('Done.')
if translateconfig.batch:
log.event("batch mode, not calling interactive helpers")
return
log.event("start debugger...")
if translateconfig.view:
try:
t1 = drv.hint_translator
except (NameError, AttributeError):
t1 = t
from rpython.translator.tool import graphpage
page = graphpage.TranslatorPage(t1, translateconfig.huge)
page.display_background()
pdb_plus_show.start(tb)
try:
drv = driver.TranslationDriver.from_targetspec(targetspec_dic, config, args,
empty_translator=t,
disable=translateconfig.skipped_goals,
default_goal='compile')
log_config(translateconfig, "translate.py configuration")
if config.translation.jit:
if (translateconfig.goals != ['annotate'] and
translateconfig.goals != ['rtype']):
drv.set_extra_goals(['pyjitpl'])
# early check:
from rpython.jit.backend.detect_cpu import getcpuclassname
getcpuclassname(config.translation.jit_backend)
log_config(config.translation, "translation configuration")
pdb_plus_show.expose({'drv': drv, 'prof': prof})
if config.translation.output:
drv.exe_name = config.translation.output
elif drv.exe_name is None and '__name__' in targetspec_dic:
drv.exe_name = targetspec_dic['__name__'] + '-%(backend)s'
# Double check to ensure we are not overwriting the current interpreter
goals = translateconfig.goals
if not goals or 'compile' in goals:
try:
this_exe = py.path.local(sys.executable).new(ext='')
exe_name = drv.compute_exe_name()
samefile = this_exe.samefile(exe_name)
assert not samefile, (
'Output file %s is the currently running '
'interpreter (please move the executable, and '
'possibly its associated libpypy-c, somewhere else '
'before you execute it)' % exe_name)
except EnvironmentError:
pass
try:
drv.proceed(goals)
finally:
drv.timer.pprint()
except SystemExit:
raise
except:
finish_profiling()
debug(True)
raise SystemExit(1)
else:
finish_profiling()
if translateconfig.pdb:
debug(False)
if __name__ == '__main__':
main()
|