[pypy-svn] r33158 - in pypy/branch/even-more-config3/pypy: config config/test objspace/flow objspace/flow/test rpython/memory/test translator translator/backendopt translator/c translator/c/src translator/c/test translator/test
cfbolz at codespeak.net
cfbolz at codespeak.net
Wed Oct 11 13:59:06 CEST 2006
Author: cfbolz
Date: Wed Oct 11 13:58:56 2006
New Revision: 33158
Removed:
pypy/branch/even-more-config3/pypy/translator/c/src/ll_stackless.h
Modified:
pypy/branch/even-more-config3/pypy/config/config.py
pypy/branch/even-more-config3/pypy/config/pypyoption.py
pypy/branch/even-more-config3/pypy/config/test/test_config.py
pypy/branch/even-more-config3/pypy/config/test/test_pypyoption.py
pypy/branch/even-more-config3/pypy/objspace/flow/flowcontext.py
pypy/branch/even-more-config3/pypy/objspace/flow/objspace.py
pypy/branch/even-more-config3/pypy/objspace/flow/specialcase.py
pypy/branch/even-more-config3/pypy/objspace/flow/test/test_objspace.py
pypy/branch/even-more-config3/pypy/rpython/memory/test/test_transformed_gc.py
pypy/branch/even-more-config3/pypy/translator/backendopt/all.py
pypy/branch/even-more-config3/pypy/translator/c/database.py
pypy/branch/even-more-config3/pypy/translator/c/gc.py
pypy/branch/even-more-config3/pypy/translator/c/genc.py
pypy/branch/even-more-config3/pypy/translator/c/src/g_include.h
pypy/branch/even-more-config3/pypy/translator/c/test/test_backendoptimized.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_boehm.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_exceptiontransform.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_genc.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_newgc.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_stackless.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_symboltable.py
pypy/branch/even-more-config3/pypy/translator/c/test/test_typed.py
pypy/branch/even-more-config3/pypy/translator/driver.py
pypy/branch/even-more-config3/pypy/translator/geninterplevel.py
pypy/branch/even-more-config3/pypy/translator/interactive.py
pypy/branch/even-more-config3/pypy/translator/test/test_driver.py
pypy/branch/even-more-config3/pypy/translator/translator.py
Log:
merge forward: svn merge -r 33037:HEAD http://codespeak.net/svn/pypy/branch/even-more-config2
Modified: pypy/branch/even-more-config3/pypy/config/config.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/config/config.py (original)
+++ pypy/branch/even-more-config3/pypy/config/config.py Wed Oct 11 13:58:56 2006
@@ -2,68 +2,77 @@
from py.compat import optparse
class Config(object):
- _frozen = False
+ _cfgimpl_frozen = False
def __init__(self, descr, parent=None, **overrides):
- self._descr = descr
- self._value_owners = {}
- self._parent = parent
- self._build(overrides)
+ self._cfgimpl_descr = descr
+ self._cfgimpl_value_owners = {}
+ self._cfgimpl_parent = parent
+ self._cfgimpl_values = {}
+ self._cfgimpl_build(overrides)
- def _build(self, overrides):
- for child in self._descr._children:
+ def _cfgimpl_build(self, overrides):
+ for child in self._cfgimpl_descr._children:
if isinstance(child, Option):
- self.__dict__[child._name] = child.default
- self._value_owners[child._name] = 'default'
+ self._cfgimpl_values[child._name] = child.default
+ self._cfgimpl_value_owners[child._name] = 'default'
elif isinstance(child, OptionDescription):
- self.__dict__[child._name] = Config(child, parent=self)
+ self._cfgimpl_values[child._name] = Config(child, parent=self)
+ self.override(overrides)
+
+ def override(self, overrides):
for name, value in overrides.iteritems():
- subconfig, name = self._get_by_path(name)
+ subconfig, name = self._cfgimpl_get_by_path(name)
setattr(subconfig, name, value)
+ subconfig._cfgimpl_value_owners[name] = 'default'
def __setattr__(self, name, value):
- if self._frozen:
+ if self._cfgimpl_frozen and getattr(self, name) != value:
raise TypeError("trying to change a frozen option object")
- if name.startswith('_'):
+ if name.startswith('_cfgimpl_'):
self.__dict__[name] = value
return
self.setoption(name, value, 'user')
+ def __getattr__(self, name):
+ if name not in self._cfgimpl_values:
+ raise AttributeError("%s object has no attribute %s" %
+ (self.__class__, name))
+ return self._cfgimpl_values[name]
+
def setoption(self, name, value, who):
- if name not in self.__dict__:
- raise ValueError('unknown option %s' % (name,))
- child = getattr(self._descr, name)
- oldowner = self._value_owners[child._name]
+ if name not in self._cfgimpl_values:
+ raise AttributeError('unknown option %s' % (name,))
+ child = getattr(self._cfgimpl_descr, name)
+ oldowner = self._cfgimpl_value_owners[child._name]
oldvalue = getattr(self, name)
- if oldowner == 'required':
- if oldvalue != value:
- raise ValueError('can not override value %s for option %s' %
- (value, name))
- return
+ if oldvalue != value and oldowner != "default":
+ raise ValueError('can not override value %s for option %s' %
+ (value, name))
child.setoption(self, value)
- self._value_owners[name] = who
+ self._cfgimpl_value_owners[name] = who
def require(self, name, value):
self.setoption(name, value, "required")
- def _get_by_path(self, path):
+ def _cfgimpl_get_by_path(self, path):
"""returns tuple (config, name)"""
path = path.split('.')
for step in path[:-1]:
self = getattr(self, step)
return self, path[-1]
- def _get_toplevel(self):
- while self._parent is not None:
- self = self._parent
+ def _cfgimpl_get_toplevel(self):
+ while self._cfgimpl_parent is not None:
+ self = self._cfgimpl_parent
return self
def _freeze_(self):
- self.__dict__['_frozen'] = True
+ self.__dict__['_cfgimpl_frozen'] = True
return True
def getkey(self):
- return self._descr.getkey(self)
+ return self._cfgimpl_descr.getkey(self)
def __hash__(self):
return hash(self.getkey())
@@ -75,15 +84,15 @@
return not self == other
def __iter__(self):
- for child in self._descr._children:
+ for child in self._cfgimpl_descr._children:
if isinstance(child, Option):
yield child._name, getattr(self, child._name)
def __str__(self):
- result = "[%s]\n" % (self._descr._name, )
- for child in self._descr._children:
+ result = "[%s]\n" % (self._cfgimpl_descr._name, )
+ for child in self._cfgimpl_descr._children:
if isinstance(child, Option):
- if self._value_owners[child._name] == 'default':
+ if self._cfgimpl_value_owners[child._name] == 'default':
continue
result += " %s = %s\n" % (
child._name, getattr(self, child._name))
@@ -101,7 +110,7 @@
if currpath is None:
currpath = []
paths = []
- for option in self._descr._children:
+ for option in self._cfgimpl_descr._children:
attr = option._name
if attr.startswith('_'):
continue
@@ -137,7 +146,7 @@
name = self._name
if not self.validate(value):
raise ValueError('invalid value %s for option %s' % (value, name))
- config.__dict__[name] = value
+ config._cfgimpl_values[name] = value
def getkey(self, value):
return value
@@ -146,7 +155,7 @@
raise NotImplemented('abstract base class')
class ChoiceOption(Option):
- def __init__(self, name, doc, values, default, requires=None,
+ def __init__(self, name, doc, values, default=None, requires=None,
cmdline=DEFAULT_OPTION_NAME):
super(ChoiceOption, self).__init__(name, doc, cmdline)
self.values = values
@@ -158,12 +167,13 @@
def setoption(self, config, value):
name = self._name
for path, reqvalue in self._requires.get(value, []):
- subconfig, name = config._get_toplevel()._get_by_path(path)
+ toplevel = config._cfgimpl_get_toplevel()
+ subconfig, name = toplevel._cfgimpl_get_by_path(path)
subconfig.require(name, reqvalue)
super(ChoiceOption, self).setoption(config, value)
def validate(self, value):
- return value in self.values
+ return value is None or value in self.values
def add_optparse_option(self, argnames, parser, config):
def _callback(option, opt_str, value, parser, *args, **kwargs):
@@ -171,18 +181,30 @@
config.setoption(self._name, value.strip(), who='cmdline')
except ValueError, e:
raise optparse.OptionValueError(e.args[0])
- parser.add_option(help=self.doc,
- action='callback', type='string',
- callback=_callback, *argnames)
+ option = parser.add_option(help=self.doc,
+ action='callback', type='string',
+ callback=_callback, *argnames)
+
+
+def _getnegation(optname):
+ if optname.startswith("without"):
+ return "with" + optname[len("without"):]
+ if optname.startswith("with"):
+ return "without" + optname[len("with"):]
+ return "no-" + optname
class BoolOption(ChoiceOption):
def __init__(self, name, doc, default=True, requires=None,
- cmdline=DEFAULT_OPTION_NAME):
+ cmdline=DEFAULT_OPTION_NAME, negation=True):
if requires is not None:
requires = {True: requires}
super(BoolOption, self).__init__(name, doc, [True, False], default,
requires=requires,
cmdline=cmdline)
+ self.negation = negation
+
+ def validate(self, value):
+ return isinstance(value, bool)
def add_optparse_option(self, argnames, parser, config):
def _callback(option, opt_str, value, parser, *args, **kwargs):
@@ -190,23 +212,28 @@
config.setoption(self._name, True, who='cmdline')
except ValueError, e:
raise optparse.OptionValueError(e.args[0])
- parser.add_option(help=self.doc,
- action='callback',
- callback=_callback, *argnames)
- no_argnames = ["--no-" + argname.lstrip("-") for argname in argnames
- if argname.startswith("--")]
+ option = parser.add_option(help=self.doc,
+ action='callback',
+ callback=_callback, *argnames)
+ if not self.negation:
+ return
+ no_argnames = ["--" + _getnegation(argname.lstrip("-"))
+ for argname in argnames
+ if argname.startswith("--")]
if len(no_argnames) == 0:
- no_argnames = ["--no-" + argname.lstrip("-")
+ no_argnames = ["--" + _getnegation(argname.lstrip("-"))
for argname in argnames]
def _callback(option, opt_str, value, parser, *args, **kwargs):
try:
config.setoption(self._name, False, who='cmdline')
except ValueError, e:
raise optparse.OptionValueError(e.args[0])
- parser.add_option(help="unset option set by %s" % (argnames[0], ),
- action='callback',
- callback=_callback, *no_argnames)
+ option = parser.add_option(help="unset option set by %s" % (argname, ),
+ action='callback',
+ callback=_callback, *no_argnames)
+
+
class IntOption(Option):
def __init__(self, name, doc, default=0, cmdline=DEFAULT_OPTION_NAME):
super(IntOption, self).__init__(name, doc, cmdline)
@@ -228,9 +255,9 @@
def add_optparse_option(self, argnames, parser, config):
def _callback(option, opt_str, value, parser, *args, **kwargs):
config.setoption(self._name, value, who='cmdline')
- parser.add_option(help=self.doc,
- action='callback', type='int',
- callback=_callback, *argnames)
+ option = parser.add_option(help=self.doc,
+ action='callback', type='int',
+ callback=_callback, *argnames)
class FloatOption(Option):
def __init__(self, name, doc, default=0.0, cmdline=DEFAULT_OPTION_NAME):
@@ -253,9 +280,34 @@
def add_optparse_option(self, argnames, parser, config):
def _callback(option, opt_str, value, parser, *args, **kwargs):
config.setoption(self._name, value, who='cmdline')
- parser.add_option(help=self.doc,
- action='callback', type='float',
- callback=_callback, *argnames)
+ option = parser.add_option(help=self.doc,
+ action='callback', type='float',
+ callback=_callback, *argnames)
+
+class StrOption(Option):
+ def __init__(self, name, doc, default='', cmdline=DEFAULT_OPTION_NAME):
+ super(StrOption, self).__init__(name, doc, cmdline)
+ self.default = default
+
+ def validate(self, value):
+ try:
+ str(value)
+ except TypeError:
+ return False
+ return True
+
+ def setoption(self, config, value):
+ try:
+ super(StrOption, self).setoption(config, str(value))
+ except TypeError, e:
+ raise ValueError(*e.args)
+
+ def add_optparse_option(self, argnames, parser, config):
+ def _callback(option, opt_str, value, parser, *args, **kwargs):
+ config.setoption(self._name, value, who='cmdline')
+ option = parser.add_option(help=self.doc,
+ action='callback', type='str',
+ callback=_callback, *argnames)
class OptionDescription(object):
def __init__(self, name, doc, children, cmdline=DEFAULT_OPTION_NAME):
@@ -274,30 +326,7 @@
for child in self._children])
def add_optparse_option(self, argnames, parser, config):
- for child in self._children:
- if not isinstance(child, BoolOption):
- raise ValueError(
- "cannot make OptionDescription %s a cmdline option" % (
- self._name, ))
- def _callback(option, opt_str, value, parser, *args, **kwargs):
- try:
- values = value.split(",")
- for value in values:
- value = value.strip()
- if value.startswith("-"):
- value = value[1:]
- set_to = False
- else:
- set_to = True
- option = getattr(self, value, None)
- if option is None:
- raise ValueError("did not find option %s" % (value, ))
- getattr(config, self._name).setoption(
- value, set_to, who='cmdline')
- except ValueError, e:
- raise optparse.OptionValueError(e.args[0])
- parser.add_option(help=self._name, action='callback', type='string',
- callback=_callback, *argnames)
+ return
def to_optparse(config, useoptions=None, parser=None):
@@ -319,25 +348,21 @@
for path in useoptions:
if path.endswith(".*"):
path = path[:-2]
- subconf, name = config._get_by_path(path)
+ subconf, name = config._cfgimpl_get_by_path(path)
children = [
path + "." + child._name
- for child in getattr(subconf, name)._descr._children]
+ for child in getattr(subconf, name)._cfgimpl_descr._children]
useoptions.extend(children)
else:
- subconf, name = config._get_by_path(path)
- option = getattr(subconf._descr, name)
+ subconf, name = config._cfgimpl_get_by_path(path)
+ option = getattr(subconf._cfgimpl_descr, name)
if option.cmdline is DEFAULT_OPTION_NAME:
chunks = ('--%s' % (path.replace('.', '-'),),)
elif option.cmdline is None:
continue
else:
chunks = option.cmdline.split(' ')
- try:
- grp = get_group(path, subconf._descr.doc)
- option.add_optparse_option(chunks, grp, subconf)
- except ValueError:
- # an option group that does not only contain bool values
- pass
+ grp = get_group(path, subconf._cfgimpl_descr.doc)
+ option.add_optparse_option(chunks, grp, subconf)
return parser
Modified: pypy/branch/even-more-config3/pypy/config/pypyoption.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/config/pypyoption.py (original)
+++ pypy/branch/even-more-config3/pypy/config/pypyoption.py Wed Oct 11 13:58:56 2006
@@ -47,8 +47,8 @@
OptionDescription("usemodules", "Which Modules should be used", [
BoolOption(modname, "use module %s" % (modname, ),
default=modname in default_modules,
- cmdline=None)
- for modname in all_modules], cmdline="--usemodules"),
+ cmdline="--withmod-%s" % (modname, ))
+ for modname in all_modules]),
BoolOption("geninterp", "specify whether geninterp should be used"),
@@ -101,12 +101,123 @@
BoolOption("translating", "indicates whether we are translating currently",
default=False, cmdline=None),
+
+ OptionDescription("translation", "Translation Options", [
+ BoolOption("stackless", "compile stackless features in",
+ default=False, cmdline="--stackless",
+ requires=[("translation.type_system", "lltype"),
+ ("objspace.usemodules._stackless", True)]),
+ ChoiceOption("type_system", "Type system to use when RTyping",
+ ["lltype", "ootype"], cmdline=None),
+ ChoiceOption("backend", "Backend to use for code generation",
+ ["c", "llvm", "cli", "js", "squeak", "cl"],
+ requires={
+ "c": [("translation.type_system", "lltype")],
+ "llvm": [("translation.type_system", "lltype")],
+ "cli": [("translation.type_system", "ootype")],
+ "js": [("translation.type_system", "ootype")],
+ "squeak": [("translation.type_system", "ootype")],
+ "cl": [("translation.type_system", "ootype")],
+ }),
+ ChoiceOption("gc", "Garbage Collection Strategy",
+ ["boehm", "ref", "framework", "none", "stacklessgc",
+ "exact_boehm"],
+ "boehm", requires={
+ "stacklessgc": [("translation.stackless", True)]},
+ cmdline="--gc"),
+
+ BoolOption("thread", "enable use of threading primitives",
+ default=False),
+ BoolOption("verbose", "Print extra information", default=False),
+ BoolOption("debug", "Record extra annotation information",
+ cmdline="-d --debug", default=False),
+ BoolOption("insist", "Try hard to go on RTyping", default=False,
+ cmdline="--insist"),
+ BoolOption("countmallocs", "Count mallocs and frees", default=False,
+ cmdline=None),
+ BoolOption("lowmem", "Try to use little memory during translation",
+ default=False, cmdline="--lowmem",
+ requires=[("objspace.geninterp", False)]),
+
+ # misc
+ # XXX cc missing, no support for general string options yet
+ # XXX profopt missing, no support for general string options yet
+ StrOption("cc", "Specify compiler", default='', cmdline="--cc"),
+ StrOption("profopt", "Specify profile based optimization script",
+ default="", cmdline="--profopt"),
+ 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("text", "Don't start the pygame viewer", default=False,
+ cmdline="--text", negation=False),
+
+
+
+ # Flags of the TranslationContext:
+ BoolOption("simplifying", "Simplify flow graphs", default=True),
+ BoolOption("do_imports_immediately", "XXX", default=True,
+ cmdline=None),
+ BoolOption("builtins_can_raise_exceptions", "XXX", default=False,
+ cmdline=None),
+ BoolOption("list_comprehension_operations", "XXX", default=False,
+ cmdline=None),
+
+ OptionDescription("backendopt", "Backend Optimization Options", [
+ BoolOption("print_statistics", "Print statistics while optimizing",
+ default=False),
+ BoolOption("merge_if_blocks", "Merge if ... elif chains",
+ cmdline="--if-block-merge", default=True),
+ BoolOption("raisingop2direct_call",
+ "Transform exception raising operations",
+ default=False, cmdline="--raisingop2direct_call"),
+ BoolOption("mallocs", "Remove mallocs", default=True),
+ BoolOption("propagate", "Constant propagation, deprecated",
+ default=False),
+ BoolOption("constfold", "Constant propagation",
+ default=True),
+ BoolOption("heap2stack", "Escape analysis and stack allocation",
+ default=False,
+ requires=[("translation.stackless", False)]),
+ BoolOption("clever_malloc_removal",
+ "Remove mallocs in a clever way", default=False),
+ IntOption("inline_threshold", "Threshold when to inline functions",
+ default=1, cmdline=None),
+ ]),
+ OptionDescription("goals",
+ "Goals that should be reached during translation", [
+ # XXX not sure what the defaults should be here
+ BoolOption("annotate", "Do type inference", default=False,
+ cmdline="-a --annotate", negation=False),
+ BoolOption("no_annotate", "Don't do type inference", default=False,
+ cmdline="--no-annotate", negation=False),
+ BoolOption("rtype", "Do rtyping", default=False,
+ cmdline="-t --rtype", negation=False),
+ BoolOption("no_rtype", "Don't do rtyping", default=False,
+ cmdline="--no-rtype", negation=False),
+ BoolOption("backendopt", "Do backend optimizations", default=False,
+ cmdline="--backendopt", negation=False),
+ BoolOption("no_backenopt", "Don't do backend optimizations",
+ default=False, cmdline="--no-backendopt", negation=False),
+ BoolOption("source", "Create source", default=False,
+ cmdline="-s --source", negation=False),
+ BoolOption("no_source", "Don't create source", default=False,
+ cmdline="--no-source", negation=False),
+ BoolOption("compile", "Compile", default=False,
+ cmdline="--compile", negation=False),
+ BoolOption("no_compile", "Don't compile", default=False,
+ cmdline="--no-compile", negation=False),
+ BoolOption("llinterpret", "Interpret the rtyped flow graphs",
+ default=False, cmdline="--llinterpret", negation=False),
+ ]),
+ ]),
])
if __name__ == '__main__':
config = Config(pypy_optiondescription)
print config.getpaths()
- parser = to_optparse(config)
+ parser = to_optparse(config) #, useoptions=["translation.*"])
option, args = parser.parse_args()
print config
Modified: pypy/branch/even-more-config3/pypy/config/test/test_config.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/config/test/test_config.py (original)
+++ pypy/branch/even-more-config3/pypy/config/test/test_config.py Wed Oct 11 13:58:56 2006
@@ -9,13 +9,19 @@
booloption = BoolOption('bool', 'Test boolean option')
intoption = IntOption('int', 'Test int option')
floatoption = FloatOption('float', 'Test float option', default=2.3)
+ stroption = StrOption('str', 'Test string option', default="abc")
wantref_option = BoolOption('wantref', 'Test requires', default=False,
requires=[('gc.name', 'ref')])
+ wantframework_option = BoolOption('wantframework', 'Test requires',
+ default=False,
+ requires=[('gc.name', 'framework')])
gcgroup = OptionDescription('gc', '', [gcoption, gcdummy, floatoption])
descr = OptionDescription('pypy', '', [gcgroup, booloption, objspaceoption,
- wantref_option, intoption])
+ wantref_option, stroption,
+ wantframework_option,
+ intoption])
return descr
def test_base_config():
@@ -39,19 +45,22 @@
assert not config.wantref
+ assert config.str == "abc"
+ config.str = "def"
+ assert config.str == "def"
+
py.test.raises(ValueError, 'config.objspace = "foo"')
py.test.raises(ValueError, 'config.gc.name = "foo"')
- py.test.raises(ValueError, 'config.gc.foo = "bar"')
+ py.test.raises(AttributeError, 'config.gc.foo = "bar"')
py.test.raises(ValueError, 'config.bool = 123')
py.test.raises(ValueError, 'config.int = "hello"')
py.test.raises(ValueError, 'config.gc.float = None')
- # test whether the gc.name is set to 'ref' when wantref is true (note that
- # the current value of gc.name is 'framework')
- config.wantref = True
+ config = Config(descr, bool=False)
assert config.gc.name == 'ref'
- py.test.raises(ValueError, 'config.gc.name = "framework"')
- config.gc.name = "ref"
+ config.wantframework = True
+ py.test.raises(ValueError, 'config.gc.name = "ref"')
+ config.gc.name = "framework"
def test_annotator_folding():
from pypy.translator.interactive import Translation
@@ -77,6 +86,8 @@
assert block.operations[0].opname == 'int_add'
assert config._freeze_()
+ # does not raise, since it does not change the attribute
+ config.gc.name = "ref"
py.test.raises(TypeError, 'config.gc.name = "framework"')
def test_compare_configs():
@@ -111,6 +122,9 @@
assert config.gc.name == 'framework'
+
+ config = Config(descr)
+ parser = to_optparse(config, ['gc.name'])
(options, args) = parser.parse_args(args=['-g ref'])
assert config.gc.name == 'ref'
@@ -138,8 +152,13 @@
booloption1 = BoolOption('bool1', 'Boolean option test', default=False,
cmdline='--bool1 -b')
booloption2 = BoolOption('bool2', 'Boolean option test', default=True,
- cmdline='--bool2 -c')
- descr = OptionDescription('test', '', [booloption1, booloption2])
+ cmdline='--with-bool2 -c')
+ booloption3 = BoolOption('bool3', 'Boolean option test', default=True,
+ cmdline='--bool3')
+ booloption4 = BoolOption('bool4', 'Boolean option test', default=True,
+ cmdline='--bool4', negation=False)
+ descr = OptionDescription('test', '', [booloption1, booloption2,
+ booloption3, booloption4])
config = Config(descr)
parser = to_optparse(config, ['bool1', 'bool2'])
@@ -149,57 +168,17 @@
assert config.bool2
config = Config(descr)
- parser = to_optparse(config, ['bool1', 'bool2'])
- (options, args) = parser.parse_args(args=['--no-bool2'])
+ parser = to_optparse(config, ['bool1', 'bool2', 'bool3', 'bool4'])
+ (options, args) = parser.parse_args(args=['--without-bool2', '--no-bool3',
+ '--bool4'])
assert not config.bool1
assert not config.bool2
+ assert not config.bool3
py.test.raises(SystemExit,
"(options, args) = parser.parse_args(args=['-bfoo'])")
-
-def test_optparse_boolgroup():
- group = OptionDescription("test", '', [
- BoolOption("smallint", "use tagged integers",
- default=False),
- BoolOption("strjoin", "use strings optimized for addition",
- default=False),
- BoolOption("strslice", "use strings optimized for slicing",
- default=False),
- BoolOption("strdict", "use dictionaries optimized for string keys",
- default=False),
- BoolOption("normal", "do nothing special",
- default=True),
- ], cmdline="--test")
- descr = OptionDescription("all", '', [group])
- config = Config(descr)
- parser = to_optparse(config, ['test'])
- (options, args) = parser.parse_args(
- args=['--test=smallint,strjoin,strdict'])
-
- assert config.test.smallint
- assert config.test.strjoin
- assert config.test.strdict
- assert config.test.normal
-
- config = Config(descr)
- parser = to_optparse(config, ['test'])
- (options, args) = parser.parse_args(
- args=['--test=smallint'])
-
- assert config.test.smallint
- assert not config.test.strjoin
- assert not config.test.strdict
- assert config.test.normal
-
- config = Config(descr)
- parser = to_optparse(config, ['test'])
- (options, args) = parser.parse_args(
- args=['--test=-normal,smallint'])
-
- assert config.test.smallint
- assert not config.test.strjoin
- assert not config.test.strdict
- assert not config.test.normal
+ py.test.raises(SystemExit,
+ "(options, args) = parser.parse_args(args=['--no-bool4'])")
def test_config_start():
descr = make_description()
@@ -227,11 +206,12 @@
config = Config(descr)
assert config.getpaths() == ['gc.name', 'gc.dummy', 'gc.float', 'bool',
- 'objspace', 'wantref', 'int']
+ 'objspace', 'wantref', 'str', 'wantframework',
+ 'int']
assert config.gc.getpaths() == ['name', 'dummy', 'float']
assert config.getpaths(include_groups=True) == [
'gc', 'gc.name', 'gc.dummy', 'gc.float',
- 'bool', 'objspace', 'wantref', 'int']
+ 'bool', 'objspace', 'wantref', 'str', 'wantframework', 'int']
def test_none():
dummy1 = BoolOption('dummy1', 'doc dummy', default=False, cmdline=None)
@@ -274,3 +254,25 @@
config.s.backend = "cli"
assert config.s.type_system == "oo"
+def test_choice_with_no_default():
+ descr = OptionDescription("test", "", [
+ ChoiceOption("backend", "", ["c", "llvm"])])
+ config = Config(descr)
+ assert config.backend is None
+ config.backend = "c"
+
+def test_overrides_are_defaults():
+ descr = OptionDescription("test", "", [
+ BoolOption("b1", "", default=False, requires=[("b2", False)]),
+ BoolOption("b2", "", default=False),
+ ])
+ config = Config(descr, b2=True)
+ assert config.b2
+ config.b1 = True
+ assert not config.b2
+ print config._cfgimpl_value_owners
+
+def test_str():
+ descr = make_description()
+ c = Config(descr)
+ print c # does not crash
Modified: pypy/branch/even-more-config3/pypy/config/test/test_pypyoption.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/config/test/test_pypyoption.py (original)
+++ pypy/branch/even-more-config3/pypy/config/test/test_pypyoption.py Wed Oct 11 13:58:56 2006
@@ -14,8 +14,9 @@
conf.objspace.std.withsmallint = True
assert not conf.objspace.std.withprebuiltint
+ conf = Config(pypy_optiondescription)
conf.objspace.std.withprebuiltint = True
- assert not conf.objspace.std.withsmallint
+ py.test.raises(ValueError, "conf.objspace.std.withsmallint = True")
def test_objspace_incopatibilities():
conf = Config(pypy_optiondescription)
@@ -24,3 +25,9 @@
conf = Config(pypy_optiondescription)
conf.objspace.name = "logic"
assert not conf.objspace.geninterp
+
+def test_stacklessgc_required():
+ conf = Config(pypy_optiondescription)
+ conf.translation.gc = "stacklessgc"
+ assert conf.translation.stackless
+ assert conf.translation.type_system == "lltype"
Modified: pypy/branch/even-more-config3/pypy/objspace/flow/flowcontext.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/objspace/flow/flowcontext.py (original)
+++ pypy/branch/even-more-config3/pypy/objspace/flow/flowcontext.py Wed Oct 11 13:58:56 2006
@@ -281,7 +281,7 @@
except OperationError, e:
#print "OE", e.w_type, e.w_value
- if (self.space.do_imports_immediately and
+ if (self.space.config.translation.do_imports_immediately and
e.w_type is self.space.w_ImportError):
raise ImportError('import statement always raises %s' % (
e,))
Modified: pypy/branch/even-more-config3/pypy/objspace/flow/objspace.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/objspace/flow/objspace.py (original)
+++ pypy/branch/even-more-config3/pypy/objspace/flow/objspace.py Wed Oct 11 13:58:56 2006
@@ -34,9 +34,6 @@
full_exceptions = False
- builtins_can_raise_exceptions = False
- do_imports_immediately = True
-
def initialize(self):
import __builtin__
self.concrete_mode = 1
@@ -428,7 +425,7 @@
exceptions = [Exception] # *any* exception by default
if isinstance(w_callable, Constant):
c = w_callable.value
- if not self.builtins_can_raise_exceptions:
+ if not self.config.translation.builtins_can_raise_exceptions:
if (isinstance(c, (types.BuiltinFunctionType,
types.BuiltinMethodType,
types.ClassType,
Modified: pypy/branch/even-more-config3/pypy/objspace/flow/specialcase.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/objspace/flow/specialcase.py (original)
+++ pypy/branch/even-more-config3/pypy/objspace/flow/specialcase.py Wed Oct 11 13:58:56 2006
@@ -11,7 +11,7 @@
# import * in a function gives us the locals as Variable
# we always forbid it as a SyntaxError
raise SyntaxError, "RPython: import * is not allowed in functions"
- if space.do_imports_immediately:
+ if space.config.translation.do_imports_immediately:
name, glob, loc, frm = (space.unwrap(w_name), space.unwrap(w_glob),
space.unwrap(w_loc), space.unwrap(w_frm))
try:
@@ -36,7 +36,7 @@
else:
raise Exception, "should call %r with exactly %d arguments" % (
fn, Arity[opname])
- if space.builtins_can_raise_exceptions:
+ if space.config.translation.builtins_can_raise_exceptions:
# in this mode, avoid constant folding and raise an implicit Exception
w_result = space.do_operation(opname, *args_w)
space.handle_implicit_exceptions([Exception])
Modified: pypy/branch/even-more-config3/pypy/objspace/flow/test/test_objspace.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/objspace/flow/test/test_objspace.py (original)
+++ pypy/branch/even-more-config3/pypy/objspace/flow/test/test_objspace.py Wed Oct 11 13:58:56 2006
@@ -713,9 +713,9 @@
class TestFlowObjSpaceDelay(Base):
- def setup_class(cls):
+ def setup_class(cls):
cls.space = FlowObjSpace()
- cls.space.do_imports_immediately = False
+ cls.space.config.translation.do_imports_immediately = False
def test_import_something(self):
def f():
Modified: pypy/branch/even-more-config3/pypy/rpython/memory/test/test_transformed_gc.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/rpython/memory/test/test_transformed_gc.py (original)
+++ pypy/branch/even-more-config3/pypy/rpython/memory/test/test_transformed_gc.py Wed Oct 11 13:58:56 2006
@@ -198,7 +198,7 @@
ARGS = lltype.FixedSizeArray(lltype.Signed, nbargs)
s_args = annmodel.SomePtr(lltype.Ptr(ARGS))
t = rtype(entrypoint, [s_args])
- cbuild = CStandaloneBuilder(t, entrypoint, self.gcpolicy)
+ cbuild = CStandaloneBuilder(t, entrypoint, gcpolicy=self.gcpolicy)
db = cbuild.generate_graphs_for_llinterp()
entrypointptr = cbuild.getentrypointptr()
entrygraph = entrypointptr._obj.graph
Modified: pypy/branch/even-more-config3/pypy/translator/backendopt/all.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/backendopt/all.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/backendopt/all.py Wed Oct 11 13:58:56 2006
@@ -12,8 +12,6 @@
from pypy.translator.backendopt.support import log
from pypy.objspace.flow.model import checkgraph
-PRINT_STATISTICS = False
-
def backend_optimizations(translator, graphs=None,
raisingop2direct_call_all=False,
inline_threshold=1,
@@ -24,10 +22,22 @@
heap2stack=False,
clever_malloc_removal=False):
+ config = translator.config.translation.backendopt
+ # ZZZ the arguments here should disappear
+ raisingop2direct_call_all = (config.raisingop2direct_call or
+ raisingop2direct_call_all)
+ mallocs = config.mallocs or mallocs
+ merge_if_blocks_to_switch = (config.merge_if_blocks or
+ merge_if_blocks_to_switch)
+ propagate = config.propagate or propagate
+ constfold = config.propagate or propagate
+ heap2stack = config.heap2stack or heap2stack
+ clever_malloc_removal = config.clever_malloc_removal or clever_malloc_removal
+
if graphs is None:
graphs = translator.graphs
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "before optimizations:"
print_statistics(translator.graphs[0], translator, "per-graph.txt")
@@ -41,7 +51,7 @@
simplify.transform_dead_op_vars(graph, translator)
removenoops.remove_duplicate_casts(graph, translator)
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "after no-op removal:"
print_statistics(translator.graphs[0], translator)
@@ -60,7 +70,7 @@
removenoops.remove_superfluous_keep_alive(graph)
removenoops.remove_duplicate_casts(graph, translator)
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "after inlining:"
print_statistics(translator.graphs[0], translator)
@@ -77,14 +87,14 @@
tot += count
log.malloc("removed %d simple mallocs in total" % tot)
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "after malloc removal:"
print_statistics(translator.graphs[0], translator)
else:
assert graphs is translator.graphs # XXX for now
clever_inlining_and_malloc_removal(translator)
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "after clever inlining and malloc removal"
print_statistics(translator.graphs[0], translator)
@@ -104,7 +114,7 @@
for graph in graphs:
merge_if_blocks(graph)
- if PRINT_STATISTICS:
+ if config.print_statistics:
print "after if-to-switch:"
print_statistics(translator.graphs[0], translator)
Modified: pypy/branch/even-more-config3/pypy/translator/c/database.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/database.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/database.py Wed Oct 11 13:58:56 2006
@@ -15,17 +15,25 @@
from pypy.translator.c.support import log
from pypy.translator.c.extfunc import do_the_getting
from pypy import conftest
+from pypy.translator.c import gc
+
# ____________________________________________________________
class LowLevelDatabase(object):
- stacklesstransformer = None
gctransformer = None
- def __init__(self, translator=None, standalone=False, gcpolicy=None, thread_enabled=False):
+ def __init__(self, translator=None, standalone=False,
+ gcpolicyclass=None,
+ stacklesstransformer=None,
+ thread_enabled=False):
self.translator = translator
self.standalone = standalone
- self.thread_enabled = thread_enabled
+ self.stacklesstransformer = stacklesstransformer
+ if gcpolicyclass is None:
+ gcpolicyclass = gc.RefcountingGcPolicy
+ self.gcpolicy = gcpolicyclass(self, thread_enabled)
+
self.structdefnodes = {}
self.pendingsetupnodes = []
self.containernodes = {}
@@ -46,31 +54,12 @@
from pypy.translator.c.pyobj import PyObjMaker
self.pyobjmaker = PyObjMaker(self.namespace, self, translator)
- gcpolicy = gcpolicy or conftest.option.gcpolicy or 'ref'
- if isinstance(gcpolicy, str):
- from pypy.translator.c import gc
- polname = gcpolicy
- if polname == 'boehm':
- gcpolicy = gc.BoehmGcPolicy
- elif polname == 'exact_boehm':
- gcpolicy = gc.MoreExactBoehmGcPolicy
- elif polname == 'ref':
- gcpolicy = gc.RefcountingGcPolicy
- elif polname == 'none':
- gcpolicy = gc.NoneGcPolicy
- elif polname == 'framework':
- gcpolicy = gc.FrameworkGcPolicy
- elif polname == 'stacklessgc':
- gcpolicy = gc.StacklessFrameworkGcPolicy
- else:
- assert False, "unknown gc policy %r"%polname
if translator is None or translator.rtyper is None:
self.exctransformer = None
else:
self.exctransformer = translator.getexceptiontransformer()
- self.gcpolicy = gcpolicy(self, thread_enabled)
if translator is not None:
- self.gctransformer = gcpolicy.transformerclass(translator)
+ self.gctransformer = self.gcpolicy.transformerclass(translator)
self.completed = False
def gettypedefnode(self, T, varlength=1):
Modified: pypy/branch/even-more-config3/pypy/translator/c/gc.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/gc.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/gc.py Wed Oct 11 13:58:56 2006
@@ -427,3 +427,15 @@
class StacklessFrameworkGcPolicy(FrameworkGcPolicy):
transformerclass = stacklessframework.StacklessFrameworkGCTransformer
requires_stackless = True
+
+
+name_to_gcpolicy = {
+ 'boehm': BoehmGcPolicy,
+ 'exact_boehm': MoreExactBoehmGcPolicy,
+ 'ref': RefcountingGcPolicy,
+ 'none': NoneGcPolicy,
+ 'framework': FrameworkGcPolicy,
+ 'stacklessgc': StacklessFrameworkGcPolicy,
+}
+
+
Modified: pypy/branch/even-more-config3/pypy/translator/c/genc.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/genc.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/genc.py Wed Oct 11 13:58:56 2006
@@ -14,20 +14,27 @@
from pypy.translator.locality.calltree import CallTree
from pypy.translator.c.support import log, c_string_constant
from pypy.rpython.typesystem import getfunctionptr
+from pypy.translator.c import gc
class CBuilder(object):
c_source_filename = None
_compiled = False
symboltable = None
- stackless = False
modulename = None
- def __init__(self, translator, entrypoint, gcpolicy=None, libraries=None, thread_enabled=False):
+ def __init__(self, translator, entrypoint, config=None, libraries=None,
+ gcpolicy=None):
self.translator = translator
self.entrypoint = entrypoint
self.originalentrypoint = entrypoint
self.gcpolicy = gcpolicy
- self.thread_enabled = thread_enabled
+ if config is None:
+ from pypy.config.config import Config
+ from pypy.config.pypyoption import pypy_optiondescription
+ config = Config(pypy_optiondescription)
+ if gcpolicy is not None and gcpolicy.requires_stackless:
+ config.translation.stackless = True
+ self.config = config
if libraries is None:
libraries = []
@@ -36,23 +43,25 @@
def build_database(self, exports=[], pyobj_options=None):
translator = self.translator
- db = LowLevelDatabase(translator, standalone=self.standalone,
- gcpolicy=self.gcpolicy, thread_enabled=self.thread_enabled)
- assert self.stackless in (False, 'old', True)
- if db.gcpolicy.requires_stackless:
- assert self.stackless != 'old' # incompatible
- self.stackless = True
- if self.stackless:
+ gcpolicyclass = self.get_gcpolicyclass()
+
+ if self.config.translation.stackless:
if not self.standalone:
raise Exception("stackless: only for stand-alone builds")
-
+
from pypy.translator.stackless.transform import StacklessTransformer
- db.stacklesstransformer = StacklessTransformer(translator,
- self.originalentrypoint,
- db.gcpolicy.requires_stackless)
- self.entrypoint = db.stacklesstransformer.slp_entry_point
+ stacklesstransformer = StacklessTransformer(
+ translator, self.originalentrypoint,
+ stackless_gc=gcpolicyclass.requires_stackless)
+ self.entrypoint = stacklesstransformer.slp_entry_point
+ else:
+ stacklesstransformer = None
+ db = LowLevelDatabase(translator, standalone=self.standalone,
+ gcpolicyclass=gcpolicyclass,
+ stacklesstransformer=stacklesstransformer,
+ thread_enabled=self.config.translation.thread)
# pass extra options into pyobjmaker
if pyobj_options:
for key, value in pyobj_options.items():
@@ -97,6 +106,12 @@
have___thread = None
+
+ def get_gcpolicyclass(self):
+ if self.gcpolicy is None:
+ return gc.name_to_gcpolicy[self.config.translation.gc]
+ return self.gcpolicy
+
def generate_source(self, db=None, defines={}):
assert self.c_source_filename is None
translator = self.translator
@@ -112,12 +127,14 @@
targetdir = udir.ensure(modulename, dir=1)
self.targetdir = targetdir
defines = defines.copy()
- # defines={'COUNT_OP_MALLOCS': 1}
+ if self.config.translation.countmallocs:
+ defines['COUNT_OP_MALLOCS'] = 1
if CBuilder.have___thread is None:
CBuilder.have___thread = check_under_under_thread()
if not self.standalone:
from pypy.translator.c.symboltable import SymbolTable
- self.symboltable = SymbolTable()
+ # XXX fix symboltable
+ #self.symboltable = SymbolTable()
cfile, extra = gen_source(db, modulename, targetdir,
defines = defines,
exports = self.exports,
@@ -125,9 +142,6 @@
else:
if CBuilder.have___thread:
defines['HAVE___THREAD'] = 1
- if self.stackless == 'old':
- defines['USE_STACKLESS'] = '1'
- defines['USE_OPTIMIZED_STACKLESS_UNWIND'] = '1'
cfile, extra = gen_source_standalone(db, modulename, targetdir,
entrypointname = pfname,
defines = defines)
@@ -135,7 +149,7 @@
self.extrafiles = extra
if self.standalone:
self.gen_makefile(targetdir)
- return cfile
+ return cfile
def generate_graphs_for_llinterp(self, db=None):
# prepare the graphs as when the source is generated, but without
@@ -282,7 +296,10 @@
print >> f
print >> f, 'CFLAGS =', ' '.join(compiler.compile_extra)
print >> f, 'LDFLAGS =', ' '.join(compiler.link_extra)
- print >> f, 'TFLAGS = ' + ('', '-pthread')[self.thread_enabled]
+ if self.config.translation.thread:
+ print >> f, 'TFLAGS = ' + '-pthread'
+ else:
+ print >> f, 'TFLAGS = ' + ''
print >> f, 'PROFOPT = ' + profopt
print >> f, 'CC = ' + cc
print >> f
@@ -624,10 +641,6 @@
sg.set_strategy(targetdir)
sg.gen_readable_parts_of_source(f)
- # 2bis) old-style stackless data
- if hasattr(database, 'stacklessdata'):
- database.stacklessdata.writefiles(sg)
-
# 3) start-up code
print >> f
gen_startupcode(f, database)
Modified: pypy/branch/even-more-config3/pypy/translator/c/src/g_include.h
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/src/g_include.h (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/src/g_include.h Wed Oct 11 13:58:56 2006
@@ -40,7 +40,6 @@
# ifdef RPyExc_thread_error
# include "src/ll_thread.h"
# endif
-# include "src/ll_stackless.h"
# include "src/ll__socket.h"
#endif
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_backendoptimized.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_backendoptimized.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_backendoptimized.py Wed Oct 11 13:58:56 2006
@@ -15,12 +15,12 @@
t.view()
def test_remove_same_as(self):
- def f(n=bool):
+ def f(n):
if bool(bool(bool(n))):
return 123
else:
return 456
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [bool])
assert f(True) == 123
assert f(False) == 456
@@ -39,13 +39,13 @@
def __del__(self):
b.num_deleted += 1
- def f(x=int):
+ def f(x):
a = A()
for i in range(x):
a = A()
return b.num_deleted
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
res = f(5)
assert res == 5
res = fn(5)
@@ -66,7 +66,7 @@
s.b_dels += 1
class C(A):
pass
- def f(x=int):
+ def f(x):
A()
B()
C()
@@ -77,7 +77,7 @@
return s.a_dels * 10 + s.b_dels
else:
return -1
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
res = f(1)
assert res == 42
res = fn(1)
@@ -92,7 +92,7 @@
backend_optimizations(t, merge_if_blocks_to_switch=True)
def test_int_switch(self):
- def f(x=int):
+ def f(x):
if x == 3:
return 9
elif x == 9:
@@ -101,12 +101,12 @@
return 3
return 0
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [int])
for x in (0,1,2,3,9,27,48, -9):
assert fn(x) == f(x)
def test_uint_switch(self):
- def f(x=r_uint):
+ def f(x):
if x == r_uint(3):
return 9
elif x == r_uint(9):
@@ -115,12 +115,12 @@
return 3
return 0
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [r_uint])
for x in (0,1,2,3,9,27,48):
assert fn(x) == f(x)
def test_longlong_switch(self):
- def f(x=r_longlong):
+ def f(x):
if x == r_longlong(3):
return 9
elif x == r_longlong(9):
@@ -129,12 +129,12 @@
return 3
return 0
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [r_longlong])
for x in (0,1,2,3,9,27,48, -9):
assert fn(x) == f(x)
def test_ulonglong_switch(self):
- def f(x=r_ulonglong):
+ def f(x):
if x == r_ulonglong(3):
return 9
elif x == r_ulonglong(9):
@@ -143,12 +143,12 @@
return 3
return 0
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [r_ulonglong])
for x in (0,1,2,3,9,27,48, -9):
assert fn(x) == f(x)
def test_chr_switch(self):
- def f(y=int):
+ def f(y):
x = chr(y)
if x == 'a':
return 'b'
@@ -158,13 +158,13 @@
return 'd'
return '@'
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [int])
for x in 'ABCabc@':
y = ord(x)
assert fn(y) == f(y)
def test_unichr_switch(self):
- def f(y=int):
+ def f(y):
x = unichr(y)
if x == u'a':
return 'b'
@@ -174,7 +174,7 @@
return 'd'
return '@'
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [int])
for x in u'ABCabc@':
y = ord(x)
assert fn(y) == f(y)
@@ -219,13 +219,13 @@
backend_optimizations(t, raisingop2direct_call_all=True)
def test_int_floordiv_zer(self):
- def f(x=int):
+ def f(x):
try:
y = 123 / x
except:
y = 456
return y
codegenerator = self.CodeGenerator()
- fn = codegenerator.getcompiled(f)
+ fn = codegenerator.getcompiled(f, [int])
for x in (0,1,2,3,9,27,48, -9):
assert fn(x) == f(x)
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_boehm.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_boehm.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_boehm.py Wed Oct 11 13:58:56 2006
@@ -3,6 +3,8 @@
from pypy.translator.tool.cbuild import check_boehm_presence
from pypy.translator.c.genc import CExtModuleBuilder
from pypy import conftest
+from pypy.config.config import Config
+from pypy.config.pypyoption import pypy_optiondescription
def setup_module(mod):
if not check_boehm_presence():
@@ -32,7 +34,9 @@
t.buildrtyper().specialize()
t.checkgraphs()
def compile():
- cbuilder = CExtModuleBuilder(t, func, gcpolicy=self.gcpolicy)
+ config = Config(pypy_optiondescription)
+ config.translation.gc = self.gcpolicy
+ cbuilder = CExtModuleBuilder(t, func, config=config)
c_source_filename = cbuilder.generate_source()
if conftest.option.view:
t.view()
@@ -44,7 +48,7 @@
class TestUsingBoehm(AbstractTestClass):
- from pypy.translator.c.gc import BoehmGcPolicy as gcpolicy
+ gcpolicy = "boehm"
def test_malloc_a_lot(self):
def malloc_a_lot():
@@ -140,7 +144,7 @@
s = State()
s.dels = 0
def g():
- a = A()
+ a = A()
def f():
s.dels = 0
for i in range(10):
@@ -178,6 +182,6 @@
class TestUsingExactBoehm(TestUsingBoehm):
- from pypy.translator.c.gc import MoreExactBoehmGcPolicy as gcpolicy
+ gcpolicy = "exact_boehm"
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_exceptiontransform.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_exceptiontransform.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_exceptiontransform.py Wed Oct 11 13:58:56 2006
@@ -4,6 +4,7 @@
from pypy.translator.c import exceptiontransform, genc, gc
from pypy.objspace.flow.model import c_last_exception
from pypy.rpython.test.test_llinterp import get_interpreter
+from pypy.translator.c.test.test_genc import compile
from pypy import conftest
import sys
@@ -39,20 +40,6 @@
_already_transformed[t] = True
return interp.eval_graph(graph, values)
-def compile_func(fn, inputtypes):
- t = TranslationContext()
- t.buildannotator().build_types(fn, inputtypes)
- t.buildrtyper().specialize()
-## etrafo = exceptiontransform.ExceptionTransformer(t)
-## etrafo.transform_completely()
- builder = genc.CExtModuleBuilder(t, fn, gcpolicy=gc.RefcountingGcPolicy)
- builder.generate_source()
- builder.compile()
- builder.import_module()
- if conftest.option.view:
- t.view()
- return builder.get_entry_point()
-
def test_simple():
def one():
return 1
@@ -65,7 +52,7 @@
assert len(list(g.iterblocks())) == 2 # graph does not change
result = interpret(foo, [])
assert result == 1
- f = compile_func(foo, [])
+ f = compile(foo, [])
assert f() == 1
def test_passthrough():
@@ -77,7 +64,7 @@
one(0)
one(1)
t, g = transform_func(foo, [])
- f = compile_func(foo, [])
+ f = compile(foo, [])
py.test.raises(ValueError, f)
def test_catches():
@@ -101,7 +88,7 @@
return 4 + x
t, g = transform_func(foo, [int])
assert len(list(g.iterblocks())) == 9
- f = compile_func(foo, [int])
+ f = compile(foo, [int])
result = interpret(foo, [6])
assert result == 2
result = f(6)
@@ -132,7 +119,7 @@
return 4 + x
t, g = transform_func(foo, [int])
assert len(list(g.iterblocks())) == 5
- f = compile_func(foo, [int])
+ f = compile(foo, [int])
result = interpret(foo, [6])
assert result == 2
result = f(6)
@@ -152,7 +139,7 @@
raise ValueError()
t, g = transform_func(foo, [int])
assert len(list(g.iterblocks())) == 3
- f = compile_func(foo, [int])
+ f = compile(foo, [int])
f(0)
py.test.raises(ValueError, f, 1)
@@ -172,7 +159,7 @@
y.z = 42
r = can_raise(n)
return r + y.z
- f = compile_func(foo, [int])
+ f = compile(foo, [int])
res = f(0)
assert res == 43
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_genc.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_genc.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_genc.py Wed Oct 11 13:58:56 2006
@@ -12,6 +12,7 @@
from pypy.translator.tool.cbuild import enable_fast_compilation
from pypy.translator.gensupp import uniquemodulename
from pypy.translator.backendopt.all import backend_optimizations
+from pypy.translator.interactive import Translation
from pypy import conftest
# XXX this tries to make compiling faster for full-scale testing
@@ -19,7 +20,6 @@
#from pypy.translator.tool import cbuild
#cbuild.enable_fast_compilation()
-
def compile_db(db):
enable_fast_compilation() # for testing
modulename = uniquemodulename('testing')
@@ -30,21 +30,17 @@
libraries = db.gcpolicy.gc_libraries())
return m
-def compile(fn, argtypes, view=False, gcpolicy=None, backendopt=True,
+def compile(fn, argtypes, view=False, gcpolicy="ref", backendopt=True,
annotatorpolicy=None):
- t = TranslationContext()
- a = t.buildannotator(policy=annotatorpolicy)
- a.build_types(fn, argtypes)
- t.buildrtyper().specialize()
- if backendopt:
- backend_optimizations(t)
- db = LowLevelDatabase(t, gcpolicy=gcpolicy)
- entrypoint = db.get(pyobjectptr(fn))
- db.complete()
- module = compile_db(db)
- if view or conftest.option.view:
- t.view()
- compiled_fn = getattr(module, entrypoint)
+ t = Translation(fn, argtypes, gc=gcpolicy, backend="c")
+ if not backendopt:
+ t.disable(["backendopt_lltype"])
+ t.annotate()
+ # XXX fish
+ t.driver.config.translation.countmallocs = True
+ compiled_fn = t.compile_c()
+ # XXX fish fish fish some more
+ module = t.driver.cbuilder.c_ext_module
def checking_fn(*args, **kwds):
if 'expected_extra_mallocs' in kwds:
expected_extra_mallocs = kwds.pop('expected_extra_mallocs')
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_newgc.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_newgc.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_newgc.py Wed Oct 11 13:58:56 2006
@@ -9,16 +9,19 @@
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.lltypesystem.lloperation import llop
from pypy.rpython.objectmodel import cast_weakgcaddress_to_object, cast_object_to_weakgcaddress
-
+from pypy.config.config import Config
+from pypy.config.pypyoption import pypy_optiondescription
from pypy import conftest
-def compile_func(fn, inputtypes, t=None, gcpolicy=gc.RefcountingGcPolicy):
+def compile_func(fn, inputtypes, t=None, gcpolicy="ref"):
+ config = Config(pypy_optiondescription)
+ config.translation.gc = gcpolicy
if t is None:
- t = TranslationContext()
+ t = TranslationContext(config=config)
if inputtypes is not None:
t.buildannotator().build_types(fn, inputtypes)
t.buildrtyper().specialize()
- builder = genc.CExtModuleBuilder(t, fn, gcpolicy=gcpolicy)
+ builder = genc.CExtModuleBuilder(t, fn, config=config)
builder.generate_source(defines={'COUNT_OP_MALLOCS': 1})
builder.compile()
builder.import_module()
@@ -143,7 +146,7 @@
assert fn(0) == 5
def test_del_basic():
- for gcpolicy in [gc.RefcountingGcPolicy]: #, gc.FrameworkGcPolicy]:
+ for gcpolicy in ["ref"]: #, "framework"]:
S = lltype.GcStruct('S', ('x', lltype.Signed))
TRASH = lltype.GcStruct('TRASH', ('x', lltype.Signed))
lltype.attachRuntimeTypeInfo(S)
@@ -399,7 +402,7 @@
from pypy.translator.c.test.test_boehm import AbstractTestClass
class TestUsingFramework(AbstractTestClass):
- from pypy.translator.c.gc import FrameworkGcPolicy as gcpolicy
+ gcpolicy = "framework"
def test_empty_collect(self):
def f():
@@ -862,7 +865,7 @@
res = fn()
class TestUsingStacklessFramework(TestUsingFramework):
- from pypy.translator.c.gc import StacklessFrameworkGcPolicy as gcpolicy
+ gcpolicy = "stacklessgc"
def getcompiled(self, f):
# XXX quick hack
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_stackless.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_stackless.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_stackless.py Wed Oct 11 13:58:56 2006
@@ -5,23 +5,25 @@
from pypy.annotation.listdef import s_list_of_strings
from pypy.rpython.rstack import stack_unwind, stack_frames_depth, stack_too_big
from pypy.rpython.rstack import yield_current_frame_to_caller
+from pypy.config.config import Config
+from pypy.config.pypyoption import pypy_optiondescription
import os
class StacklessTest(object):
backendopt = False
stacklessmode = True
- gcpolicy = gc.BoehmGcPolicy
+ gcpolicy = "boehm"
def setup_class(cls):
import py
- if cls.gcpolicy in (None, gc.RefcountingGcPolicy):
+ if cls.gcpolicy in (None, "ref"):
# to re-enable this, remove the two characters 'gc' in the
# declaregcptrtype(rstack.frame_stack_top,...) call in
# rpython/extfunctable. Doing so breaks translator/stackless/.
import py
py.test.skip("stackless + refcounting doesn't work any more for now")
- elif cls.gcpolicy is gc.BoehmGcPolicy:
+ elif cls.gcpolicy is "boehm":
from pypy.translator.tool.cbuild import check_boehm_presence
if not check_boehm_presence():
py.test.skip("Boehm GC not present")
@@ -31,7 +33,10 @@
os.write(1, str(fn())+"\n")
return 0
- t = TranslationContext()
+ config = Config(pypy_optiondescription)
+ config.translation.gc = self.gcpolicy
+ config.translation.stackless = True
+ t = TranslationContext(config=config)
self.t = t
t.buildannotator().build_types(entry_point, [s_list_of_strings])
t.buildrtyper().specialize()
@@ -41,7 +46,7 @@
from pypy.translator.transform import insert_ll_stackcheck
insert_ll_stackcheck(t)
- cbuilder = CStandaloneBuilder(t, entry_point, gcpolicy=self.gcpolicy)
+ cbuilder = CStandaloneBuilder(t, entry_point, config=config)
cbuilder.stackless = self.stacklessmode
cbuilder.generate_source()
cbuilder.compile()
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_symboltable.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_symboltable.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_symboltable.py Wed Oct 11 13:58:56 2006
@@ -1,6 +1,7 @@
from pypy.translator.c.symboltable import getsymboltable
from pypy.translator.c.test import test_typed
+py.test.skip("XXX symboltable not supported currently")
getcompiled = test_typed.TestTypedTestCase().getcompiled
def test_simple():
Modified: pypy/branch/even-more-config3/pypy/translator/c/test/test_typed.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/c/test/test_typed.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/c/test/test_typed.py Wed Oct 11 13:58:56 2006
@@ -18,14 +18,7 @@
def annotatefunc(self, func, argtypes=None):
t = TranslationContext(simplifying=True)
if argtypes is None:
- # builds starting-types from func_defs
- # XXX kill kill kill!
argtypes = []
- if func.func_defaults:
- for spec in func.func_defaults:
- if isinstance(spec, tuple):
- spec = spec[0] # use the first type only for the tests
- argtypes.append(spec)
a = t.buildannotator()
a.build_types(func, argtypes)
a.simplify()
@@ -65,15 +58,15 @@
assert inheritance2() == ((-12, -12), (3, "world"))
def test_factorial2(self):
- factorial2 = self.getcompiled(snippet.factorial2)
+ factorial2 = self.getcompiled(snippet.factorial2, [int])
assert factorial2(5) == 120
def test_factorial(self):
- factorial = self.getcompiled(snippet.factorial)
+ factorial = self.getcompiled(snippet.factorial, [int])
assert factorial(5) == 120
def test_simple_method(self):
- simple_method = self.getcompiled(snippet.simple_method)
+ simple_method = self.getcompiled(snippet.simple_method, [int])
assert simple_method(55) == 55
def test_sieve_of_eratosthenes(self):
@@ -81,19 +74,16 @@
assert sieve_of_eratosthenes() == 1028
def test_nested_whiles(self):
- nested_whiles = self.getcompiled(snippet.nested_whiles)
+ nested_whiles = self.getcompiled(snippet.nested_whiles, [int, int])
assert nested_whiles(5,3) == '!!!!!'
def test_call_five(self):
- call_five = self.getcompiled(snippet.call_five)
+ call_five = self.getcompiled(snippet.call_five, [int])
result = call_five()
assert result == [5]
- # -- currently result isn't a real list, but a pseudo-array
- # that can't be inspected from Python.
- #self.assertEquals(result.__class__.__name__[:8], "list of ")
def test_call_unpack_56(self):
- call_unpack_56 = self.getcompiled(snippet.call_unpack_56)
+ call_unpack_56 = self.getcompiled(snippet.call_unpack_56, [])
result = call_unpack_56()
assert result == (2, 5, 6)
@@ -108,16 +98,16 @@
assert fn() == "hello world"
def test_tuple_repr(self):
- def tuple_repr(x=int, y=object):
+ def tuple_repr(x, y):
z = x, y
while x:
x = x-1
return z
- fn = self.getcompiled(tuple_repr)
+ fn = self.getcompiled(tuple_repr, [int, str])
assert fn(6,'a') == (6,'a')
def test_classattribute(self):
- fn = self.getcompiled(snippet.classattribute)
+ fn = self.getcompiled(snippet.classattribute, [int])
assert fn(1) == 123
assert fn(2) == 456
assert fn(3) == 789
@@ -125,51 +115,41 @@
assert fn(5) == 101112
def test_get_set_del_slice(self):
- fn = self.getcompiled(snippet.get_set_del_slice)
+ fn = self.getcompiled(snippet.get_set_del_slice, [list])
l = list('abcdefghij')
result = fn(l)
assert l == [3, 'c', 8, 11, 'h', 9]
assert result == ([3, 'c'], [9], [11, 'h'])
- def test_slice_long(self):
- def slice_long(l=list, n=long):
- return l[:n]
- fn = self.getcompiled(slice_long)
- l = list('abc')
- result = fn(l, 2**32)
- assert result == list('abc')
- result = fn(l, 2**64)
- assert result == list('abc')
-
def test_type_conversion(self):
# obfuscated test case specially for typer.insert_link_conversions()
- def type_conversion(n=int):
+ def type_conversion(n):
if n > 3:
while n > 0:
n = n-1
if n == 5:
n += 3.1416
return n
- fn = self.getcompiled(type_conversion)
+ fn = self.getcompiled(type_conversion, [int])
assert fn(3) == 3
assert fn(5) == 0
assert abs(fn(7) + 0.8584) < 1E-5
def test_do_try_raise_choose(self):
- fn = self.getcompiled(snippet.try_raise_choose)
+ fn = self.getcompiled(snippet.try_raise_choose, [int])
result = []
for n in [-1,0,1,2]:
result.append(fn(n))
- assert result == [-1,0,1,2]
+ assert result == [-1,0,1,2]
def test_is_perfect_number(self):
- fn = self.getcompiled(snippet.is_perfect_number)
+ fn = self.getcompiled(snippet.is_perfect_number, [int])
for i in range(1, 33):
perfect = fn(i)
assert perfect is (i in (6,28))
def test_prime(self):
- fn = self.getcompiled(snippet.prime)
+ fn = self.getcompiled(snippet.prime, [int])
result = [fn(i) for i in range(1, 21)]
assert result == [False, True, True, False, True, False, True, False,
False, False, True, False, True, False, False, False,
@@ -178,7 +158,7 @@
def test_mutate_global(self):
class Stuff:
pass
- g1 = Stuff(); g1.value = 1
+ g1 = Stuff(); g1.value = 1
g2 = Stuff(); g2.value = 2
g3 = Stuff(); g3.value = 3
g1.next = g3
@@ -193,88 +173,88 @@
assert fn() == 1
def test_float_ops(self):
- def f(x=float):
+ def f(x):
return abs((-x) ** 3 + 1)
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [float])
assert fn(-4.5) == 92.125
assert fn(4.5) == 90.125
def test_memoryerror(self):
- def f(i=int):
+ def f(i):
lst = [0]*i
lst[-1] = 5
return lst[0]
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
assert fn(1) == 5
assert fn(2) == 0
py.test.raises(MemoryError, fn, sys.maxint//2+1)
py.test.raises(MemoryError, fn, sys.maxint)
def test_chr(self):
- def f(x=int):
+ def f(x):
try:
return 'Yes ' + chr(x)
except ValueError:
return 'No'
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
assert fn(65) == 'Yes A'
assert fn(256) == 'No'
assert fn(-1) == 'No'
def test_unichr(self):
- def f(x=int):
+ def f(x):
try:
return ord(unichr(x))
except ValueError:
return -42
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
assert fn(65) == 65
assert fn(-12) == -42
assert fn(sys.maxint) == -42
def test_list_indexerror(self):
- def f(i=int):
+ def f(i):
lst = [123, 456]
try:
lst[i] = 789
except IndexError:
return 42
return lst[0]
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int])
assert fn(1) == 123
assert fn(2) == 42
assert fn(-2) == 789
assert fn(-3) == 42
def test_long_long(self):
- def f(i=r_ulonglong):
+ def f(i):
return 4*i
- fn = self.getcompiled(f, view=False)
+ fn = self.getcompiled(f, [r_ulonglong], view=False)
assert fn(sys.maxint) == 4*sys.maxint
- def g(i=r_longlong):
+ def g(i):
return 4*i
- gn = self.getcompiled(g, view=False)
+ gn = self.getcompiled(g, [r_longlong], view=False)
assert gn(sys.maxint) == 4*sys.maxint
def test_specializing_int_functions(self):
def f(i):
return i + 1
f._annspecialcase_ = "specialize:argtype(0)"
- def g(n=int):
+ def g(n):
if n > 0:
return f(r_longlong(0))
else:
return f(0)
- fn = self.getcompiled(g)
+ fn = self.getcompiled(g, [int])
assert g(0) == 1
assert g(1) == 1
def test_downcast_int(self):
- def f(i=r_longlong):
+ def f(i):
return int(i)
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [r_longlong])
assert fn(0) == 0
def test_function_ptr(self):
@@ -282,13 +262,13 @@
return 1
def f2():
return 2
- def g(i=int):
+ def g(i):
if i:
f = f1
else:
f = f2
return f()
- fn = self.getcompiled(g)
+ fn = self.getcompiled(g, [int])
assert fn(0) == 2
assert fn(1) == 1
@@ -346,92 +326,92 @@
assert result is False
def test_str_compare(self):
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] == s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] != s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] < s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] <= s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] > s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'twos', 'foobar']
return s1[i] >= s2[j]
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(6):
res = fn(i, j)
assert res is testfn(i, j)
def test_str_methods(self):
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
return s1[i].startswith(s2[j])
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(9):
res = fn(i, j)
assert res is testfn(i, j)
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = ['one', 'two']
s2 = ['one', 'two', 'o', 'on', 'ne', 'e', 'twos', 'foobar', 'fortytwo']
return s1[i].endswith(s2[j])
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(2):
for j in range(9):
res = fn(i, j)
assert res is testfn(i, j)
def test_str_join(self):
- def testfn(i=int, j=int):
+ def testfn(i, j):
s1 = [ '', ',', ' and ']
s2 = [ [], ['foo'], ['bar', 'baz', 'bazz']]
return s1[i].join(s2[j])
- fn = self.getcompiled(testfn)
+ fn = self.getcompiled(testfn, [int, int])
for i in range(3):
for j in range(3):
res = fn(i, j)
@@ -439,9 +419,9 @@
def test_unichr_eq(self):
l = list(u'Hello world')
- def f(i=int,j=int):
+ def f(i, j):
return l[i] == l[j]
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int, int])
for i in range(len(l)):
for j in range(len(l)):
res = fn(i,j)
@@ -449,9 +429,9 @@
def test_unichr_ne(self):
l = list(u'Hello world')
- def f(i=int,j=int):
+ def f(i, j):
return l[i] != l[j]
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int, int])
for i in range(len(l)):
for j in range(len(l)):
res = fn(i,j)
@@ -459,37 +439,34 @@
def test_unichr_ord(self):
l = list(u'Hello world')
- def f(i=int):
- return ord(l[i])
- fn = self.getcompiled(f)
+ def f(i):
+ return ord(l[i])
+ fn = self.getcompiled(f, [int])
for i in range(len(l)):
res = fn(i)
assert res == f(i)
def test_unichr_unichr(self):
l = list(u'Hello world')
- def f(i=int, j=int):
+ def f(i, j):
return l[i] == unichr(j)
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int, int])
for i in range(len(l)):
for j in range(len(l)):
res = fn(i, ord(l[j]))
assert res == f(i, ord(l[j]))
- def test_slice_long(self):
- "the parent's test_slice_long() makes no sense here"
-
def test_int_overflow(self):
- fn = self.getcompiled(snippet.add_func)
+ fn = self.getcompiled(snippet.add_func, [int])
raises(OverflowError, fn, sys.maxint)
def test_int_floordiv_ovf_zer(self):
- fn = self.getcompiled(snippet.div_func)
+ fn = self.getcompiled(snippet.div_func, [int])
raises(OverflowError, fn, -1)
raises(ZeroDivisionError, fn, 0)
def test_int_mul_ovf(self):
- fn = self.getcompiled(snippet.mul_func)
+ fn = self.getcompiled(snippet.mul_func, [int, int])
for y in range(-5, 5):
for x in range(-5, 5):
assert fn(x, y) == snippet.mul_func(x, y)
@@ -499,38 +476,38 @@
raises(OverflowError, fn, n, 5)
def test_int_mod_ovf_zer(self):
- fn = self.getcompiled(snippet.mod_func)
+ fn = self.getcompiled(snippet.mod_func, [int])
raises(OverflowError, fn, -1)
raises(ZeroDivisionError, fn, 0)
def test_int_rshift_val(self):
- fn = self.getcompiled(snippet.rshift_func)
+ fn = self.getcompiled(snippet.rshift_func, [int])
raises(ValueError, fn, -1)
def test_int_lshift_ovf_val(self):
- fn = self.getcompiled(snippet.lshift_func)
+ fn = self.getcompiled(snippet.lshift_func, [int])
raises(ValueError, fn, -1)
raises(OverflowError, fn, 1)
def test_int_unary_ovf(self):
- fn = self.getcompiled(snippet.unary_func)
+ fn = self.getcompiled(snippet.unary_func, [int])
for i in range(-3,3):
assert fn(i) == (-(i), abs(i-1))
raises (OverflowError, fn, -sys.maxint-1)
raises (OverflowError, fn, -sys.maxint)
# floats
- def test_float_operations(self):
+ def test_float_operations(self):
import math
- def func(x=float, y=float):
- z = x + y / 2.1 * x
+ def func(x, y):
+ z = x + y / 2.1 * x
z = math.fmod(z, 60.0)
z = pow(z, 2)
z = -z
- return int(z)
+ return int(z)
- fn = self.getcompiled(func)
- assert fn(5.0, 6.0) == func(5.0, 6.0)
+ fn = self.getcompiled(func, [float, float])
+ assert fn(5.0, 6.0) == func(5.0, 6.0)
def test_rpbc_bound_method_static_call(self):
class R:
@@ -555,39 +532,39 @@
def test_stringformatting(self):
- def fn(i=int):
+ def fn(i):
return "you said %d, you did"%i
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [int])
assert f(1) == fn(1)
def test_int2str(self):
- def fn(i=int):
+ def fn(i):
return str(i)
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [int])
assert f(1) == fn(1)
def test_float2str(self):
- def fn(i=float):
+ def fn(i):
return str(i)
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [float])
res = f(1.0)
assert type(res) is str and float(res) == 1.0
def test_uint_arith(self):
- def fn(i=r_uint):
+ def fn(i):
try:
return ~(i*(i+1))/(i-1)
except ZeroDivisionError:
return r_uint(91872331)
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [r_uint])
for value in range(15):
i = r_uint(value)
assert f(i) == fn(i)
def test_ord_returns_a_positive(self):
- def fn(i=int):
+ def fn(i):
return ord(chr(i))
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [int])
assert f(255) == 255
def test_hash_preservation(self):
@@ -613,7 +590,7 @@
assert res[1] == intmask(hash(c)+hash(d))
def test_list_basic_ops(self):
- def list_basic_ops(i=int, j=int):
+ def list_basic_ops(i, j):
l = [1,2,3]
l.insert(0, 42)
del l[1]
@@ -624,7 +601,7 @@
l += [5,6]
l[1] = i
return l[j]
- f = self.getcompiled(list_basic_ops)
+ f = self.getcompiled(list_basic_ops, [int, int])
for i in range(6):
for j in range(6):
assert f(i,j) == list_basic_ops(i,j)
@@ -638,28 +615,28 @@
assert f() == fn()
def test_range_idx(self):
- def fn(idx=int):
+ def fn(idx):
r = range(10, 37, 4)
try:
return r[idx]
except: raise
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [int])
assert f(0) == fn(0)
assert f(-1) == fn(-1)
raises(IndexError, f, 42)
def test_range_step(self):
- def fn(step=int):
+ def fn(step):
r = range(10, 37, step)
# we always raise on step = 0
return r[-2]
- f = self.getcompiled(fn)#, view=True)
+ f = self.getcompiled(fn, [int])
assert f(1) == fn(1)
assert f(3) == fn(3)
raises(ValueError, f, 0)
def test_range_iter(self):
- def fn(start=int, stop=int, step=int):
+ def fn(start, stop, step):
res = 0
if step == 0:
if stop >= start:
@@ -671,17 +648,17 @@
for i in r:
res = res * 51 + i
return res
- f = self.getcompiled(fn)
+ f = self.getcompiled(fn, [int, int, int])
for args in [2, 7, 0], [7, 2, 0], [10, 50, 7], [50, -10, -3]:
assert f(*args) == intmask(fn(*args))
def test_recursion_detection(self):
- def f(n=int, accum=int):
+ def f(n, accum):
if n == 0:
return accum
else:
return f(n-1, accum*n)
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f, [int, int])
assert fn(7, 1) == 5040
assert fn(7, 1) == 5040 # detection must work several times, too
assert fn(7, 1) == 5040
@@ -719,13 +696,13 @@
if x:
return f(x)
return 1
- def g(x=int):
+ def g(x):
try:
f(x)
except RuntimeError:
return 42
return 1
- fn = self.getcompiled(g)
+ fn = self.getcompiled(g, [int])
assert fn(0) == 1
assert fn(1) == 42
@@ -746,7 +723,7 @@
except Exception:
return 42
return x
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f)
res = fn()
assert res == 42
@@ -758,9 +735,9 @@
except TypeError:
return 42
return x
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f)
res = fn()
- assert res == 42
+ assert res == 42
def f():
d1 = r_dict(eq, raising_hash)
@@ -770,6 +747,6 @@
except TypeError:
return 42
return 0
- fn = self.getcompiled(f)
+ fn = self.getcompiled(f)
res = fn()
- assert res == 42
+ assert res == 42
Modified: pypy/branch/even-more-config3/pypy/translator/driver.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/driver.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/driver.py Wed Oct 11 13:58:56 2006
@@ -57,14 +57,42 @@
class TranslationDriver(SimpleTaskEngine):
def __init__(self, options=None, default_goal=None, disable=[],
- exe_name=None, extmod_name=None):
+ exe_name=None, extmod_name=None,
+ config=None):
SimpleTaskEngine.__init__(self)
self.log = log
+ if config is None:
+ from pypy.config.config import Config
+ from pypy.config.pypyoption import pypy_optiondescription
+ config = Config(pypy_optiondescription)
+ self.config = config
+
+ # YYY the option argument should disappear
if options is None:
options = _default_options
+ else:
+ # move options over to config
+
+ # YYY debug
+ # YYY fork_before
+ # YYY debug_transform
+ tconf = config.translation
+ tconf.gc = options.gc
+ tconf.thread = options.thread
+ tconf.stackless = options.stackless
+ tconf.backend = options.backend
+ tconf.type_system = options.type_system
+ tconf.insist = options.insist
+ tconf.lowmem = options.lowmem
+ tconf.backendopt.merge_if_blocks = options.merge_if_blocks
+ tconf.backendopt.raisingop2direct_call = (
+ options.raisingop2direct_call)
+
+
self.options = options
+
self.exe_name = exe_name
self.extmod_name = extmod_name
@@ -102,7 +130,7 @@
if task in ('rtype', 'backendopt', 'llinterpret'):
if ts:
if ts == postfix:
- expose_task(task, explicit_task)
+ expose_task(task, explicit_task)
else:
expose_task(explicit_task)
elif task in ('source', 'compile', 'run'):
@@ -118,13 +146,13 @@
def get_backend_and_type_system(self):
type_system = None
backend = None
- opts = self.options
- if opts.type_system:
- type_system = opts.type_system
- if opts.backend:
- backend = opts.backend
+ if self.config.translation.type_system:
+ type_system = self.config.translation.type_system
+ if self.config.translation.backend:
+ backend = self.config.translation.backend
ts = backend_to_typesystem(backend)
if type_system:
+ # YYY should be dead code
if ts != type_system:
raise ValueError, ("incosistent type-system and backend:"
" %s and %s" % (type_system, backend))
@@ -167,7 +195,7 @@
self.inputtypes = inputtypes
if policy is None:
- policy = annpolicy.AnnotatorPolicy()
+ policy = annpolicy.AnnotatorPolicy()
if standalone:
policy.allow_someobjects = False
self.policy = policy
@@ -176,10 +204,10 @@
if empty_translator:
# set verbose flags
- empty_translator.flags['verbose'] = True
+ empty_translator.config.translation.verbose = True
translator = empty_translator
else:
- translator = TranslationContext(verbose=True)
+ translator = TranslationContext(config=self.config, verbose=True)
self.entry_point = entry_point
self.translator = translator
@@ -206,7 +234,7 @@
policy = self.policy
self.log.info('with policy: %s.%s' % (policy.__class__.__module__, policy.__class__.__name__))
- annmodel.DEBUG = self.options.debug
+ annmodel.DEBUG = self.config.translation.debug
annotator = translator.buildannotator(policy=policy)
s = annotator.build_types(self.entry_point, self.inputtypes)
@@ -249,32 +277,29 @@
def task_rtype_lltype(self):
- opt = self.options
rtyper = self.translator.buildrtyper(type_system='lltype')
+ insist = not self.config.translation.insist
rtyper.specialize(dont_simplify_again=True,
- crash_on_first_typeerror=not opt.insist)
+ crash_on_first_typeerror=insist)
#
task_rtype_lltype = taskdef(task_rtype_lltype, ['annotate'], "RTyping")
RTYPE = 'rtype_lltype'
def task_rtype_ootype(self):
# Maybe type_system should simply be an option used in task_rtype
- opt = self.options
+ insist = not self.config.translation.insist
rtyper = self.translator.buildrtyper(type_system="ootype")
rtyper.specialize(dont_simplify_again=True,
- crash_on_first_typeerror=not opt.insist)
+ crash_on_first_typeerror=insist)
#
task_rtype_ootype = taskdef(task_rtype_ootype, ['annotate'], "ootyping")
OOTYPE = 'rtype_ootype'
def task_backendopt_lltype(self):
from pypy.translator.backendopt.all import backend_optimizations
- opt = self.options
- backend_optimizations(self.translator,
- raisingop2direct_call_all=opt.raisingop2direct_call,
- merge_if_blocks_to_switch=opt.merge_if_blocks)
+ backend_optimizations(self.translator)
#
- task_backendopt_lltype = taskdef(task_backendopt_lltype,
+ task_backendopt_lltype = taskdef(task_backendopt_lltype,
[RTYPE], "lltype back-end optimisations")
BACKENDOPT = 'backendopt_lltype'
@@ -301,14 +326,13 @@
insert_ll_stackcheck(self.translator)
task_stackcheckinsertion_lltype = taskdef(
- task_stackcheckinsertion_lltype,
- ['?'+BACKENDOPT, RTYPE, 'annotate'],
+ task_stackcheckinsertion_lltype,
+ ['?'+BACKENDOPT, RTYPE, 'annotate'],
"inserting stack checks")
STACKCHECKINSERTION = 'stackcheckinsertion_lltype'
def task_database_c(self):
translator = self.translator
- opt = self.options
if translator.annotator is not None:
translator.frozen = True
@@ -319,9 +343,8 @@
else:
from pypy.translator.c.genc import CExtModuleBuilder as CBuilder
cbuilder = CBuilder(self.translator, self.entry_point,
- gcpolicy = opt.gc,
- thread_enabled = getattr(opt, 'thread', False))
- cbuilder.stackless = opt.stackless
+ config=self.config)
+ cbuilder.stackless = self.config.translation.stackless
if not standalone: # xxx more messy
cbuilder.modulename = self.extmod_name
database = cbuilder.build_database()
@@ -329,7 +352,7 @@
self.cbuilder = cbuilder
self.database = database
#
- task_database_c = taskdef(task_database_c,
+ task_database_c = taskdef(task_database_c,
[STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE, '?annotate'],
"Creating database for generating c source")
@@ -403,14 +426,14 @@
def task_source_llvm(self):
translator = self.translator
- opts = self.options
if translator.annotator is None:
raise ValueError, "llvm requires annotation."
from pypy.translator.llvm import genllvm
# XXX Need more options for policies/llvm-backendoptions here?
- self.llvmgen = genllvm.GenLLVM(translator, self.options.gc, self.standalone)
+ self.llvmgen = genllvm.GenLLVM(translator, self.config.translation.gc,
+ self.standalone)
llvm_filename = self.llvmgen.gen_llvm_source(self.entry_point)
self.log.info("written: %s" % (llvm_filename,))
@@ -478,7 +501,8 @@
def task_source_js(self):
from pypy.translator.js.js import JS
self.gen = JS(self.translator, functions=[self.entry_point],
- stackless=self.options.stackless, use_debug=self.options.debug_transform)
+ stackless=self.config.translation.stackless,
+ use_debug=self.options.debug_transform)
filename = self.gen.write_source()
self.log.info("Wrote %s" % (filename,))
task_source_js = taskdef(task_source_js,
@@ -537,13 +561,12 @@
goals = self.backend_select_goals(goals)
return self._execute(goals, task_skip = self._maybe_skip())
- def from_targetspec(targetspec_dic, options=None, args=None, empty_translator=None,
+ def from_targetspec(targetspec_dic, options=None, args=None,
+ empty_translator=None,
disable=[],
default_goal=None):
if args is None:
args = []
- if options is None:
- options = _default_options
driver = TranslationDriver(options, default_goal, disable)
# patch some attributes of the os module to make sure they
Modified: pypy/branch/even-more-config3/pypy/translator/geninterplevel.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/geninterplevel.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/geninterplevel.py Wed Oct 11 13:58:56 2006
@@ -64,13 +64,6 @@
uniquemodulename, C_IDENTIFIER, NameManager
-# list of simplifcation passes needed by geninterp
-from pypy.translator.simplify import transform_ovfcheck, all_passes as needed_passes
-
-needed_passes = needed_passes[:]
-needed_passes.remove(transform_ovfcheck)
-
-
import pypy # __path__
import py.path
from pypy.tool.ansi_print import ansi_log
@@ -1487,7 +1480,7 @@
sys.path.remove(libdir)
entrypoint = dic
- t = TranslationContext(verbose=False, simplifying=needed_passes,
+ t = TranslationContext(verbose=False, simplifying=True,
do_imports_immediately=do_imports_immediately,
builtins_can_raise_exceptions=True,
list_comprehension_operations=False)
Modified: pypy/branch/even-more-config3/pypy/translator/interactive.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/interactive.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/interactive.py Wed Oct 11 13:58:56 2006
@@ -3,6 +3,8 @@
import autopath
from pypy.translator.translator import TranslationContext
from pypy.translator import driver
+from pypy.config.config import Config
+from pypy.config.pypyoption import pypy_optiondescription
DEFAULT_OPTIONS = driver.DEFAULT_OPTIONS.copy()
DEFAULT_OPTIONS.update({
@@ -18,8 +20,9 @@
graph = self.context.buildflowgraph(entry_point)
self.context._prebuilt_graphs[entry_point] = graph
- self.driver = driver.TranslationDriver(
- optparse.Values(defaults=DEFAULT_OPTIONS))
+ self.config = Config(pypy_optiondescription)
+
+ self.driver = driver.TranslationDriver(config=self.config)
# hook into driver events
driver_own_event = self.driver._event
@@ -93,27 +96,46 @@
if optname in ('policy', 'standalone'):
continue
if optname in self.frozen_options:
- if getattr(self.driver.options, optname) != value:
- raise Exception("inconsistent option supplied: %s" % optname)
+ if self.get_option(optname) != value:
+ raise Exception("inconsistent option supplied: %s" %
+ optname)
else:
- if not hasattr(self.driver.options, optname):
+ try:
+ self.get_option(optname)
+ except AttributeError:
raise TypeError('driver has no option %r' % (optname,))
- setattr(self.driver.options, optname, value)
+ self.set_option(optname, value)
self.frozen_options[optname] = True
+ def get_option(self, name):
+ # convenience function to look through the translation and
+ # translation.backendopt namespaces of the config object
+ try:
+ return getattr(self.config.translation, name)
+ except AttributeError:
+ return getattr(self.config.translation.backendopt, name)
+
+ def set_option(self, name, value):
+ try:
+ setattr(self.config.translation, name, value)
+ except AttributeError:
+ setattr(self.config.translation.backendopt, name, value)
+
def ensure_opt(self, name, value=None, fallback=None):
if value is not None:
self.update_options(None, {name: value})
elif fallback is not None and name not in self.frozen_options:
self.update_options(None, {name: fallback})
- val = getattr(self.driver.options, name)
+ val = self.get_option(name)
if val is None:
- raise Exception("the %r option should have been specified at this point" % name)
+ raise Exception(
+ "the %r option should have been specified at this point" %name)
return val
def ensure_type_system(self, type_system=None):
if type_system is None:
- backend = self.driver.options.backend
+ backend = self.config.translation.backend
+ # YYY the next two lines are unreachable now?
if backend is not None:
type_system = driver.backend_to_typesystem(backend)
return self.ensure_opt('type_system', type_system, 'lltype')
Modified: pypy/branch/even-more-config3/pypy/translator/test/test_driver.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/test/test_driver.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/test/test_driver.py Wed Oct 11 13:58:56 2006
@@ -1,6 +1,8 @@
import py
from pypy.translator.driver import TranslationDriver, DEFAULT_OPTIONS
+from pypy.config.config import Config
+from pypy.config.pypyoption import pypy_optiondescription
from py.compat import optparse
def cmpl(l1, l2):
@@ -11,7 +13,8 @@
return l1 == l2
def test_ctr():
- td = TranslationDriver()
+ config = Config(pypy_optiondescription, **{"translation.backend": "c"})
+ td = TranslationDriver(config=config)
assert cmpl(td.exposed,
['annotate', 'backendopt', 'llinterpret', 'rtype', 'source', 'compile', 'run'])
@@ -21,42 +24,43 @@
assert td.backend_select_goals(['rtype']) == ['rtype_lltype']
assert td.backend_select_goals(['rtype_lltype']) == ['rtype_lltype']
assert td.backend_select_goals(['backendopt']) == ['backendopt_lltype']
- assert td.backend_select_goals(['backendopt_lltype']) == ['backendopt_lltype']
+ assert td.backend_select_goals(['backendopt_lltype']) == [
+ 'backendopt_lltype']
- d = DEFAULT_OPTIONS.copy()
- d['backend'] = None
- td = TranslationDriver(options=optparse.Values(defaults=d))
+ config = Config(pypy_optiondescription)
+ td = TranslationDriver(config=config)
assert td.backend_select_goals(['compile_c']) == ['compile_c']
py.test.raises(Exception, td.backend_select_goals, ['compile'])
py.test.raises(Exception, td.backend_select_goals, ['rtype'])
- assert td.backend_select_goals(['rtype_lltype']) == ['rtype_lltype']
+ assert td.backend_select_goals(['rtype_lltype']) == ['rtype_lltype']
py.test.raises(Exception, td.backend_select_goals, ['backendopt'])
- assert td.backend_select_goals(['backendopt_lltype']) == ['backendopt_lltype']
-
+ assert td.backend_select_goals(['backendopt_lltype']) == [
+ 'backendopt_lltype']
assert cmpl(td.exposed,
['annotate', 'backendopt_lltype',
'backendopt_ootype',
'llinterpret_lltype',
- 'rtype_ootype', 'rtype_lltype',
- 'source_cl', 'source_js', 'source_squeak', 'source_cli', 'source_c',
- 'source_llvm', 'compile_cl', 'compile_cli', 'compile_c', 'compile_squeak',
- 'compile_llvm', 'compile_js', 'run_cl', 'run_squeak', 'run_llvm',
- 'run_c', 'run_js', 'run_cli'])
-
- d = DEFAULT_OPTIONS.copy()
- d['backend'] = None
- d['type_system'] = 'lltype'
- td = TranslationDriver(options=optparse.Values(defaults=d))
+ 'rtype_ootype', 'rtype_lltype', 'source_cl', 'source_js',
+ 'source_squeak', 'source_cli', 'source_c', 'source_llvm',
+ 'compile_cl', 'compile_cli', 'compile_c', 'compile_squeak',
+ 'compile_llvm', 'compile_js', 'run_cl', 'run_squeak',
+ 'run_llvm', 'run_c', 'run_js', 'run_cli'])
+
+ config = Config(pypy_optiondescription,
+ **{"translation.type_system": "lltype"})
+ td = TranslationDriver(config=config)
assert td.backend_select_goals(['compile_c']) == ['compile_c']
py.test.raises(Exception, td.backend_select_goals, ['compile'])
- assert td.backend_select_goals(['rtype_lltype']) == ['rtype_lltype']
- assert td.backend_select_goals(['rtype']) == ['rtype_lltype']
+ assert td.backend_select_goals(['rtype_lltype']) == ['rtype_lltype']
+ assert td.backend_select_goals(['rtype']) == ['rtype_lltype']
assert td.backend_select_goals(['backendopt']) == ['backendopt_lltype']
- assert td.backend_select_goals(['backendopt_lltype']) == ['backendopt_lltype']
+ assert td.backend_select_goals(['backendopt_lltype']) == [
+ 'backendopt_lltype']
assert cmpl(td.exposed,
- ['annotate', 'backendopt', 'llinterpret', 'rtype', 'source_c', 'source_llvm',
- 'compile_c', 'compile_llvm', 'run_llvm', 'run_c'])
+ ['annotate', 'backendopt', 'llinterpret', 'rtype', 'source_c',
+ 'source_llvm', 'compile_c', 'compile_llvm', 'run_llvm',
+ 'run_c'])
Modified: pypy/branch/even-more-config3/pypy/translator/translator.py
==============================================================================
--- pypy/branch/even-more-config3/pypy/translator/translator.py (original)
+++ pypy/branch/even-more-config3/pypy/translator/translator.py Wed Oct 11 13:58:56 2006
@@ -12,9 +12,9 @@
from pypy.tool.ansi_print import ansi_log
from pypy.tool.sourcetools import nice_repr_for_func
import py
-log = py.log.Producer("flowgraph")
-py.log.setconsumer("flowgraph", ansi_log)
-
+log = py.log.Producer("flowgraph")
+py.log.setconsumer("flowgraph", ansi_log)
+
class TranslationContext(object):
FLOWING_FLAGS = {
'verbose': False,
@@ -24,11 +24,18 @@
'list_comprehension_operations': False, # True, - not super-tested
}
- def __init__(self, **flowing_flags):
- self.flags = self.FLOWING_FLAGS.copy()
- self.flags.update(flowing_flags)
- if len(self.flags) > len(self.FLOWING_FLAGS):
- raise TypeError("unexpected keyword argument")
+ def __init__(self, config=None, **flowing_flags):
+ if config is None:
+ from pypy.config.config import Config
+ from pypy.config.pypyoption import pypy_optiondescription
+ config = Config(pypy_optiondescription)
+ # ZZZ should go away in the end
+ for attr in ['verbose', 'simplifying', 'do_imports_immediately',
+ 'builtins_can_raise_exceptions',
+ 'list_comprehension_operations']:
+ if attr in flowing_flags:
+ setattr(config.translation, attr, flowing_flags[attr])
+ self.config = config
self.annotator = None
self.rtyper = None
self.exceptiontransformer = None
@@ -47,18 +54,18 @@
if func in self._prebuilt_graphs:
graph = self._prebuilt_graphs.pop(func)
else:
- if self.flags.get('verbose'):
+ if self.config.translation.verbose:
log.start(nice_repr_for_func(func))
- space = FlowObjSpace()
- space.__dict__.update(self.flags) # xxx push flags there
+ space = FlowObjSpace(self.config)
if self.annotator:
+ # ZZZ
self.annotator.policy._adjust_space_config(space)
graph = space.build_flow(func)
- if self.flags.get('simplifying'):
+ if self.config.translation.simplifying:
simplify.simplify_graph(graph)
- if self.flags.get('list_comprehension_operations'):
+ if self.config.translation.list_comprehension_operations:
simplify.detect_list_comprehension(graph)
- if self.flags.get('verbose'):
+ if self.config.translation.verbose:
log.done(func.__name__)
self.graphs.append(graph) # store the graph in our list
return graph
More information about the Pypy-commit
mailing list