From arigo at codespeak.net Sat Jan 1 22:22:14 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 1 Jan 2005 22:22:14 +0100 (MET) Subject: [pypy-svn] r8026 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050101212214.191425A90E@thoth.codespeak.net> Author: arigo Date: Sat Jan 1 22:22:13 2005 New Revision: 8026 Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py Log: self.assertRaises_w() -> self.raises_w() This is the first PyPy-specific conversion done by utestconvert.py. It should be removed for when utestconvert.py is to become a general unittest->pytest converter. Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/utestconvert.py (original) +++ pypy/branch/src-pytest/pypy/tool/utestconvert.py Sat Jan 1 22:22:13 2005 @@ -23,6 +23,7 @@ d['failIfAlmostEqual'] = ('assert not round', ' ==', [2,3,4]) d['assertNotAlmostEqual'] = ('assert round', ' !=', [2,3,4]) d['failUnlessAlmostEquals'] = ('assert not round', ' !=', [2,3,4]) +d['assertRaises_w'] = ('self.raises_w', '', ['Any']) # the list of synonyms d['failUnlessRaises'] = d['assertRaises'] @@ -79,7 +80,7 @@ possible_args = d[old][2] # a list of the number of arguments the # unittest function could possibly take. - if new == 'raises': # just rename assertRaises & friends + if possible_args == ['Any']: # just rename assertRaises & friends return re.sub('self.'+old, new, block) message_pos = possible_args[-1] From arigo at codespeak.net Sat Jan 1 22:51:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 1 Jan 2005 22:51:47 +0100 (MET) Subject: [pypy-svn] r8027 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050101215147.44E2B5A90E@thoth.codespeak.net> Author: arigo Date: Sat Jan 1 22:51:46 2005 New Revision: 8027 Added: pypy/branch/src-pytest/pypy/tool/fiximport.py (contents, props changed) Removed: pypy/branch/src-pytest/pypy/tool/testit.py Log: A temporary tool to help conversion: fixes import lines, class names and bases, "if __name__ == '__main__'" part. Something should be done with setUp() and tearDown() methods, though what precisely is not clear yet (see app-level tests etc.) Added: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- (empty file) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Sat Jan 1 22:51:46 2005 @@ -0,0 +1,52 @@ +import sys + + +for fn in sys.argv[1:]: + print fn + lines = [] + f = file(fn, 'r') + while True: + line = f.readline() + if not line: + break + rline = line.rstrip() + if rline == 'from pypy.tool import testit': + continue + if (rline == "if __name__ == '__main__':" or + rline == 'if __name__ == "__main__":'): + tail = f.read() + if tail.strip() != 'testit.main()': + print ' * uncommon __main__ lines at the end' + break + if line.strip() == 'def setUp(self):': + print ' * setUp() ignored' + if line.strip() == 'def tearDown(self):': + print ' * tearDown() ignored' + if line.startswith('class '): + rest = line[6:].strip() + if rest.endswith('(testit.AppTestCase):'): + rest = rest[:-21].strip() + ':' + if not rest.startswith('AppTest'): + if not rest.startswith('Test'): + rest = 'Test'+rest + rest = 'App'+rest + elif rest.endswith('(testit.IntTestCase):'): + rest = rest[:-21].strip() + ':' + if not rest.startswith('Test'): + rest = 'Test'+rest + elif rest.endswith('(testit.TestCase):'): + rest = rest[:-18].strip() + ':' + if not rest.startswith('Test'): + rest = 'Test'+rest + else: + print ' * ignored class', rest + line = 'class ' + rest + '\n' + lines.append(line) + f.close() + + while lines and not lines[-1].strip(): + del lines[-1] + + f = file(fn, 'w') + f.writelines(lines) + f.close() Deleted: /pypy/branch/src-pytest/pypy/tool/testit.py ============================================================================== --- /pypy/branch/src-pytest/pypy/tool/testit.py Sat Jan 1 22:51:46 2005 +++ (empty file) @@ -1,407 +0,0 @@ -import autopath -import os, sys, unittest, re, warnings, unittest, traceback, StringIO -import fnmatch -from unittest import TestCase, TestLoader - -import pypy.interpreter.unittest_w -from pypy.tool.optik import make_option -from pypy.tool import optik, option, ppdb - -IntTestCase = pypy.interpreter.unittest_w.IntTestCase -AppTestCase = pypy.interpreter.unittest_w.AppTestCase -TestCase = IntTestCase - -class MyTestSuite(unittest.TestSuite): - def __call__(self, result): - """ execute the tests, invokes underlying unittest.__call__""" - - count = self.countTestCases() - if not count: - return result - - fm = getattr(self, 'frommodule', '') - - if fm and Options.verbose == 0: - sys.stderr.write('\n%s [%d]' %(fm, count)) - result = unittest.TestSuite.__call__(self, result) - return result - - def addTest(self, test, frommodule=None): - if test.countTestCases() > 0: - test.frommodule = frommodule - unittest.TestSuite.addTest(self, test) - - def __nonzero__(self): - return self.countTestCases() > 0 - -# register MyTestSuite to unittest -unittest.TestLoader.suiteClass = MyTestSuite - - -class MyTestResult(unittest.TestResult): - def __init__(self): - unittest.TestResult.__init__(self) - self.successes = [] - - def addError(self, test, err): - # XXX not nice: - from pypy.interpreter.baseobjspace import OperationError - if isinstance(err[1], OperationError) and test.space.full_exceptions: - if err[1].match(test.space, test.space.w_AssertionError): - self.addFailure(test, err) - return - unittest.TestResult.addError(self, test, err) - - def addSuccess(self, test): - self.successes.append(test) - - def addSkip(self, test): - self.testsRun -= 1 - - def addIgnored(self, test, err): - pass - - -class MyTextTestResult(unittest._TextTestResult): - ignored = 0 - trace_information = [] - - def record_trace(self, test): - # XXX hack for TraceObjSpace - try: - result = test.space.getresult() - except AttributeError: - pass - else: - self.trace_information.append((test, result)) - test.space.settrace() - - def addError(self, test, err): - self.record_trace(test) - from pypy.interpreter.baseobjspace import OperationError - if isinstance(err[1], OperationError) and test.space.full_exceptions: - if err[1].match(test.space, test.space.w_AssertionError): - self.addFailure(test, err) - return - unittest._TextTestResult.addError(self, test, err) - self.errors[-1] = (test, sys.exc_info()) - - def addFailure(self, test, err): - self.record_trace(test) - unittest._TextTestResult.addFailure(self, test, err) - self.failures[-1] = (test, sys.exc_info()) - - def addSkip(self, test): - self.testsRun -= 1 - if self.showAll: - self.stream.writeln("skipped") - elif self.dots: - self.stream.write('s') - - def addIgnored(self, test, err): - self.ignored += 1 - if self.showAll: - self.stream.writeln("ignored") - elif self.dots: - self.stream.write('i') - - def interact(self): - #efs = self.errors + self.failures - #from pypy.tool.testitpm import TestPM - #c = TestPM(efs) - #c.cmdloop() - for test, (exc_type, exc_value, exc_tb) in self.errors + self.failures: - import pdb; pdb.post_mortem(exc_tb) - - def printErrors(self): - if self.trace_information: - from pypy.tool.traceop import print_result - for test, trace in self.trace_information: - print_result(test.space, trace) - sys.stdout.flush() - if Options.interactive: - print - if self.errors or self.failures: - self.interact() - else: - unittest._TextTestResult.printErrors(self) - - def printErrorList(self, flavour, errors): - from pypy.interpreter.baseobjspace import OperationError - for test, err in errors: - t1, t2 = '', '' - if not Options.quiet: - self.stream.writeln(self.separator1) - self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) - self.stream.writeln(self.separator2) - t1 = ''.join(traceback.format_exception(*err)) - if isinstance(err[1], OperationError) and \ - test.space.full_exceptions: - if not Options.quiet: - t2 = '\nand at app-level:\n\n' - sio = StringIO.StringIO() - err[1].print_application_traceback(test.space, sio) - t2 += sio.getvalue() - self.stream.writeln("%s" % (t1 + t2,)) - - -class CtsTestRunner: - def _methodname(self, result): - "Return a normalized form of the method name for result." - # use private method, id() is not enough for us - return "%s.%s" % (result.__class__.__name__, - result._TestCase__testMethodName) - - def run(self, test): - import pickle - - result = MyTestResult() - try: - # discard output of test or suite - sys.stdout = sys.stderr = StringIO.StringIO() - test(result) - finally: - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ - - # load status from previous run if available - if os.path.exists('testcts.pickle'): - oldstatus = pickle.load(open('testcts.pickle', 'r')) - else: - oldstatus = {} - - # store status from this run - status = {} - for e in result.errors: - name = self._methodname(e[0]) - status[name] = 'ERROR' - for f in result.failures: - name = self._methodname(f[0]) - status[name] = 'FAILURE' - for s in result.successes: - name = self._methodname(s) - status[name] = 'success' - - # compare statuses from previous and this run - oldmethods = oldstatus.keys() - methods = status.keys() - allmethods = dict([(m, 1) for m in oldmethods+methods]).keys() - allmethods.sort() - - for m in allmethods: - is_old = (m in oldstatus) - is_new = (m in status) - # case: test was run previously _and_ now - if is_old and is_new: - old = oldstatus[m] - new = status[m] - if old != new: - # print all transitions - print "%s has changed from %s to %s" % (m, old, new) - elif new != "success": - # print old statuses only if they weren't successes - print "%s remains a %s" % (m, new) - # case: test was run previously but not now - elif is_old and not is_new: - print "%s was a %s but not run this time" % (m, oldstatus[m]) - # retain status from previous run - status[m] = oldstatus[m] - # case: test was not run previously but now - elif not is_old and is_new: - # print nothing, just keep the old status - pass - - # save result from this run - pickle.dump(status, open('testcts.pickle', 'w')) - - return result - - -class MyTextTestRunner(unittest.TextTestRunner): - def run(self, test): - result = unittest.TextTestRunner.run(self, test) - if result.ignored: - self.stream.writeln("(ignored=%d)" % result.ignored) - return result - - def _makeResult(self): - return MyTextTestResult(self.stream, self.descriptions, self.verbosity) - - -def testsuite_from_main(): - """Return test modules from __main__.""" - loader = unittest.TestLoader() - m = __import__('__main__') - return loader.loadTestsFromModule(m) - -def testsuite_from_dir(root, filterfunc=None, recursive=0, loader=None): - """ - Return test modules that optionally match filterfunc. - - All files matching the glob-pattern "test_*.py" are considered. - Additionally, their fully qualified python module path has - to be accepted by filterfunc (if it is not None). - """ - from py import path - root = path.local(root) - - if Options.verbose > 2: - print >> sys.stderr, "scanning for test files in", root - - if loader is None: - loader = unittest.TestLoader() - - def testfilefilter(p): - return p.check(file=1, fnmatch='test_*.py') - def recfilter(p): - return recursive and p.check(dotfile=0) - - suite = unittest.TestLoader.suiteClass() - - for testfn in root.visit(testfilefilter, recfilter): - # strip the leading pypy directory and the .py suffix - modpath = str(testfn)[len(autopath.pypydir)+1:-3] - modpath = 'pypy.' + modpath.replace(os.sep, '.') - if (filterfunc is None) or filterfunc(modpath): - try: - subsuite = loader.loadTestsFromName(modpath) - except: - print "skipping testfile (failed loading it)", modpath - else: - suite.addTest(subsuite, modpath) - return suite - -class Options(option.Options): - testreldir = 0 - runcts = 0 - spacename = '' - individualtime = 0 - interactive = 0 - trace_flag = 0 - #XXX what's the purpose of this? - def ensure_value(*args): - return 0 - ensure_value = staticmethod(ensure_value) - quiet = 0 - -class TestSkip(Exception): - pass - -def objspace(name='', new_flag=False): - if name and Options.spacename and name != Options.spacename: - raise TestSkip - if new_flag: - space = option.objspace(name, _spacecache={}) - else: - space = option.objspace(name) - if Options.trace_flag: - # XXX This really sucks as a means to turn on tracing for a sole unit - # test (esp at app level). I can't see an obvious way to do this - # better. Don't think it is worth any mental energy given the new - # testing framework is just around the corner. - from pypy.objspace.trace import create_trace_space - create_trace_space(space) - space.settrace() - return space - -def new_objspace(name=''): - return objspace(name=name, new_flag=True) - -class RegexFilterFunc: - """ - Stateful function to filter included/excluded strings via - a regular expression. - - An 'excluded' regular expressions has a '%' prependend. - """ - def __init__(self, *regex): - self.exclude = [] - self.include = [] - for x in regex: - if x.startswith('%'): - self.exclude.append(re.compile(x[1:]).search) - else: - self.include.append(re.compile(x).search) - - def __call__(self, arg): - for exclude in self.exclude: - if exclude(arg): - return - if not self.include: - return arg - for include in self.include: - if include(arg): - return arg - -def get_test_options(): - options = option.get_standard_options() - options.append(make_option( - '-p', action="store_true", dest="trace_flag", - help="augment object space with tracing capabilities")) - options.append(make_option( - '-r', action="store_true", dest="testreldir", - help="gather only tests relative to current dir")) - options.append(make_option( - '-t', action="store_true", dest="individualtime", - help="time each test individually")) - options.append(make_option( - '-i', action="store_true", dest="interactive", - help="enter an interactive mode on failure or error")) - options.append(make_option( - '-q', action="store_true", dest="quiet", - help="suppress some information (e.g. interpreter level exceptions)")) - options.append(make_option( - '-c', action="store_true", dest="runcts", - help="run CtsTestRunner (discards output and prints report " - "after testing)")) - return options - -def run_tests(suite): - for spacename in Options.spaces or ['']: - run_tests_on_space(suite, spacename) - -def run_tests_on_space(suite, spacename=''): - """Run the suite on the given space.""" - if Options.runcts: - runner = CtsTestRunner() # verbosity=Options.verbose+1) - else: - runner = MyTextTestRunner(verbosity=Options.verbose+1) - - if spacename: - Options.spacename = spacename - - warnings.defaultaction = Options.showwarning and 'default' or 'ignore' - #print >> sys.stderr, "running tests via", repr(objspace()) - runner.run(suite) - -def main(root=None): - """ - Test everything in the __main__ or in the given root - directory (recursive). - """ - args = option.process_options(get_test_options(), Options) - - filterfunc = RegexFilterFunc(*args) - if Options.testreldir: - root = os.path.abspath('.') - if root is None: - suite = testsuite_from_main() - else: - suite = testsuite_from_dir(root, filterfunc, 1) - if Options.individualtime and hasattr(suite, '_tests'): - for test in suite._tests: - if hasattr(test, '_tests'): - for subtest in test._tests: - run_tests(subtest) - else: - run_tests(test) - else: - run_tests(suite) - if Options.verbose: - from pypy.tool.udir import udir - print "testdata (unittestsession) directory was:", str(udir) - - -if __name__ == '__main__': - # test all of pypy - main(autopath.pypydir) From arigo at codespeak.net Sat Jan 1 22:56:58 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 1 Jan 2005 22:56:58 +0100 (MET) Subject: [pypy-svn] r8028 - pypy/branch/src-pytest/pypy/interpreter/test Message-ID: <20050101215658.EEDA15A90E@thoth.codespeak.net> Author: arigo Date: Sat Jan 1 22:56:58 2005 New Revision: 8028 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_code.py pypy/branch/src-pytest/pypy/interpreter/test/test_generator.py pypy/branch/src-pytest/pypy/interpreter/test/test_nestedscope.py pypy/branch/src-pytest/pypy/interpreter/test/test_pyframe.py pypy/branch/src-pytest/pypy/interpreter/test/test_raise.py pypy/branch/src-pytest/pypy/interpreter/test/test_special.py pypy/branch/src-pytest/pypy/interpreter/test/test_typedef.py Log: A batch of tests that are successfully converted. The other tests in this directory need more thinking. Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_code.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_code.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_code.py Sat Jan 1 22:56:58 2005 @@ -1,16 +1,15 @@ import autopath -from pypy.tool import testit import unittest -class AppTestCodeIntrospection(testit.AppTestCase): +class AppTestCodeIntrospection: def test_attributes(self): def f(): pass def g(x, *y, **z): "docstring" - self.assert_(hasattr(f.func_code, 'co_code')) - self.assert_(hasattr(g.func_code, 'co_code')) + assert hasattr(f.func_code, 'co_code') + assert hasattr(g.func_code, 'co_code') testcases = [ (f.func_code, {'co_name': 'f', @@ -47,10 +46,10 @@ # in PyPy, built-in functions have code objects # that emulate some attributes for code, expected in testcases: - self.assert_(hasattr(code, '__class__')) - self.assert_(not hasattr(code,'__dict__')) + assert hasattr(code, '__class__') + assert not hasattr(code,'__dict__') for key, value in expected.items(): - self.assertEquals(getattr(code, key), value) + assert getattr(code, key) == value def test_code(self): import sys, new @@ -74,7 +73,7 @@ ccode.co_cellvars) d = {} exec co in d - self.assertEquals(d['c'], 3) + assert d['c'] == 3 # test backwards-compatibility version with no freevars or cellvars co = new.code(ccode.co_argcount, ccode.co_nlocals, @@ -90,7 +89,4 @@ ccode.co_lnotab) d = {} exec co in d - self.assertEquals(d['c'], 3) - -if __name__ == '__main__': - testit.main() + assert d['c'] == 3 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_generator.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_generator.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_generator.py Sat Jan 1 22:56:58 2005 @@ -1,54 +1,49 @@ from __future__ import generators import autopath -from pypy.tool import testit -class AppTestGenerator(testit.AppTestCase): +class AppTestGenerator: def test_generator(self): def f(): yield 1 - self.assertEquals(f().next(), 1) + assert f().next() == 1 def test_generator2(self): def f(): yield 1 g = f() - self.assertEquals(g.next(), 1) - self.assertRaises(StopIteration, g.next) + assert g.next() == 1 + raises(StopIteration, g.next) def test_generator3(self): def f(): yield 1 g = f() - self.assertEquals(list(g), [1]) + assert list(g) == [1] def test_generator4(self): def f(): yield 1 g = f() - self.assertEquals([x for x in g], [1]) + assert [x for x in g] == [1] def test_generator_explicit_stopiteration(self): def f(): yield 1 raise StopIteration g = f() - self.assertEquals([x for x in g], [1]) + assert [x for x in g] == [1] def test_generator_propagate_stopiteration(self): def f(): it = iter([1]) while 1: yield it.next() g = f() - self.assertEquals([x for x in g], [1]) + assert [x for x in g] == [1] def test_generator_restart(self): def g(): i = me.next() yield i me = g() - self.assertRaises(ValueError, me.next) - - -if __name__ == '__main__': - testit.main() + raises(ValueError, me.next) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_nestedscope.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_nestedscope.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_nestedscope.py Sat Jan 1 22:56:58 2005 @@ -1,19 +1,18 @@ import autopath -from pypy.tool import testit -class AppTestNestedScope(testit.AppTestCase): +class AppTestNestedScope: def test_nested_scope(self): x = 42 def f(): return x - self.assertEquals(f(), 42) + assert f() == 42 def test_nested_scope2(self): x = 42 y = 3 def f(): return x - self.assertEquals(f(), 42) + assert f() == 42 def test_nested_scope3(self): x = 42 @@ -21,7 +20,7 @@ def g(): return x return g - self.assertEquals(f()(), 42) + assert f()() == 42 def test_nested_scope4(self): def f(): @@ -32,7 +31,7 @@ x = 4 b = g() return (a, b) - self.assertEquals(f(), (3, 4)) + assert f() == (3, 4) def test_nested_scope_locals(self): def f(): @@ -42,7 +41,7 @@ return locals() return g() d = f() - self.assertEquals(d, {'i':3}) + assert d == {'i':3} def test_deeply_nested_scope_locals(self): def f(): @@ -54,8 +53,5 @@ return locals(), h() return g() outer_locals, inner_locals = f() - self.assertEquals(inner_locals, {'i':3}) - self.assertEquals(len(outer_locals), 1, "len!=1 for %r" % (outer_locals,)) - -if __name__ == '__main__': - testit.main() + assert inner_locals == {'i':3} + assert len(outer_locals) == 1, "len!=1 for %r" % (outer_locals,) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_pyframe.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_pyframe.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_pyframe.py Sat Jan 1 22:56:58 2005 @@ -1,32 +1,31 @@ import autopath -from pypy.tool import testit -class AppTestPyFrame(testit.AppTestCase): +class AppTestPyFrame: # test for the presence of the attributes, not functionality def test_f_locals(self): import sys f = sys._getframe() - self.failUnless(f.f_locals is locals()) + assert f.f_locals is locals() def test_f_globals(self): import sys f = sys._getframe() - self.failUnless(f.f_globals is globals()) + assert f.f_globals is globals() def test_f_builtins(self): import sys, __builtin__ f = sys._getframe() - self.failUnless(f.f_builtins is __builtin__.__dict__) + assert f.f_builtins is __builtin__.__dict__ def test_f_code(self): def g(): import sys f = sys._getframe() return f.f_code - self.failUnless(g() is g.func_code) + assert g() is g.func_code def test_f_lineno(self): def g(): @@ -37,8 +36,4 @@ z = f.f_lineno return [x, y, z] origin = g.func_code.co_firstlineno - self.assertEquals(g(), [origin+3, origin+4, origin+5]) - - -if __name__ == '__main__': - testit.main() + assert g() == [origin+3, origin+4, origin+5] Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_raise.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_raise.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_raise.py Sat Jan 1 22:56:58 2005 @@ -1,65 +1,64 @@ import autopath -from pypy.tool import testit -class AppTestRaise(testit.AppTestCase): +class AppTestRaise: def test_control_flow(self): try: raise Exception - self.fail("exception failed to raise") + raise AssertionError, "exception failed to raise" except: pass else: - self.fail("exception executing else clause!") + raise AssertionError, "exception executing else clause!" def test_1arg(self): try: raise SystemError, 1 except Exception, e: - self.assertEquals(e.args[0], 1) + assert e.args[0] == 1 def test_2args(self): try: raise SystemError, (1, 2) except Exception, e: - self.assertEquals(e.args[0], 1) - self.assertEquals(e.args[1], 2) + assert e.args[0] == 1 + assert e.args[1] == 2 def test_instancearg(self): try: raise SystemError, SystemError(1, 2) except Exception, e: - self.assertEquals(e.args[0], 1) - self.assertEquals(e.args[1], 2) + assert e.args[0] == 1 + assert e.args[1] == 2 def test_more_precise_instancearg(self): try: raise Exception, SystemError(1, 2) except SystemError, e: - self.assertEquals(e.args[0], 1) - self.assertEquals(e.args[1], 2) + assert e.args[0] == 1 + assert e.args[1] == 2 def test_stringexc(self): a = "hello world" try: raise a except a, e: - self.assertEquals(e, None) + assert e == None try: raise a, "message" except a, e: - self.assertEquals(e, "message") + assert e == "message" def test_builtin_exc(self): try: [][0] except IndexError, e: - self.assert_(isinstance(e, IndexError)) + assert isinstance(e, IndexError) def test_raise_cls(self): def f(): raise IndexError - self.assertRaises(IndexError, f) + raises(IndexError, f) def test_raise_cls_catch(self): def f(r): @@ -67,8 +66,8 @@ raise r except LookupError: return 1 - self.assertRaises(Exception, f, Exception) - self.assertEquals(f(IndexError), 1) + raises(Exception, f, Exception) + assert f(IndexError) == 1 def test_raise_wrong(self): try: @@ -76,7 +75,7 @@ except TypeError: pass else: - self.fail("shouldn't be able to raise 1") + raise AssertionError, "shouldn't be able to raise 1" def test_raise_three_args(self): import sys @@ -88,14 +87,14 @@ raise exc_type,exc_val,exc_tb except: exc_type2,exc_val2,exc_tb2 = sys.exc_info() - self.assertEquals(exc_type,exc_type2) - self.assertEquals(exc_val,exc_val2) - self.assertEquals(exc_tb,exc_tb2) + assert exc_type ==exc_type2 + assert exc_val ==exc_val2 + assert exc_tb ==exc_tb2 def test_tuple_type(self): def f(): raise ((StopIteration, 123), 456, 789) - self.assertRaises(StopIteration, f) + raises(StopIteration, f) def test_userclass(self): class A: @@ -106,24 +105,21 @@ try: raise A except A, a: - self.assertEquals(a.x, None) + assert a.x == None try: raise A(42) except A, a: - self.assertEquals(a.x, 42) + assert a.x == 42 try: raise A, 42 except A, a: - self.assertEquals(a.x, 42) + assert a.x == 42 try: raise B except A, b: - self.assertEquals(type(b), B) + assert type(b) == B try: raise A, B(42) except B, b: - self.assertEquals(type(b), B) - self.assertEquals(b.x, 42) - -if __name__ == '__main__': - testit.main() + assert type(b) == B + assert b.x == 42 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_special.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_special.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_special.py Sat Jan 1 22:56:58 2005 @@ -1,18 +1,13 @@ import autopath -from pypy.tool import testit -class SpecialTestCase(testit.AppTestCase): +class AppTestSpecialTestCase: def test_Ellipsis(self): - self.assertEquals(Ellipsis, Ellipsis) - self.assertEquals(repr(Ellipsis), 'Ellipsis') + assert Ellipsis == Ellipsis + assert repr(Ellipsis) == 'Ellipsis' def test_NotImplemented(self): def f(): return NotImplemented - self.assertEquals(f(), NotImplemented) - self.assertEquals(repr(NotImplemented), 'NotImplemented') - -if __name__ == '__main__': - testit.main() - + assert f() == NotImplemented + assert repr(NotImplemented) == 'NotImplemented' Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_typedef.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_typedef.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_typedef.py Sat Jan 1 22:56:58 2005 @@ -1,10 +1,9 @@ import autopath -from pypy.tool import testit # this test isn't so much to test that the objspace interface *works* # -- it's more to test that it's *there* -class TestTraceBackAttributes(testit.AppTestCase): +class AppTestTraceBackAttributes: def test_newstring(self): import sys @@ -20,10 +19,7 @@ typ,val,tb = sys.exc_info() else: raise AssertionError, "should have raised" - self.assert_(hasattr(tb, 'tb_frame')) - self.assert_(hasattr(tb, 'tb_lasti')) - self.assert_(hasattr(tb, 'tb_lineno')) - self.assert_(hasattr(tb, 'tb_next')) - -if __name__ == '__main__': - testit.main() + assert hasattr(tb, 'tb_frame') + assert hasattr(tb, 'tb_lasti') + assert hasattr(tb, 'tb_lineno') + assert hasattr(tb, 'tb_next') From hpk at codespeak.net Mon Jan 3 00:38:21 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 3 Jan 2005 00:38:21 +0100 (MET) Subject: [pypy-svn] r8040 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050102233821.C0DBB5AA11@thoth.codespeak.net> Author: hpk Date: Mon Jan 3 00:38:21 2005 New Revision: 8040 Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py Log: fix error handling ... Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/pytestsupport.py (original) +++ pypy/branch/src-pytest/pypy/tool/pytestsupport.py Mon Jan 3 00:38:21 2005 @@ -86,7 +86,7 @@ try: source = runner.statement source = str(source).strip() - except py.path.NotFound: + except py.error.ENOENT: source = None if source: msg = exprinfo.interpret(source, runner, should_fail=True) From hpk at codespeak.net Mon Jan 3 01:54:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 3 Jan 2005 01:54:52 +0100 (MET) Subject: [pypy-svn] r8046 - pypy/branch/src-pytest/pypy/interpreter/test Message-ID: <20050103005452.DC7E25AA28@thoth.codespeak.net> Author: hpk Date: Mon Jan 3 01:54:52 2005 New Revision: 8046 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_class.py Log: hum, i am not sure why converting this test requires thinking (as hinted by arigo). the "self.test_metaclass_explicit()" call seems just superflous unless i am missing something. Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_class.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_class.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_class.py Mon Jan 3 01:54:52 2005 @@ -1,25 +1,21 @@ -import autopath -from pypy.tool import testit - class AppTestClass: def test_class(self): - self.test_metaclass_explicit() class C: pass - self.assertEquals(C.__class__, type) + assert C.__class__ == type c = C() - self.assertEquals(c.__class__, C) + assert c.__class__ == C def test_metaclass_explicit(self): class M(type): pass class C: __metaclass__ = M - self.assertEquals(C.__class__, M) + assert C.__class__ == M c = C() - self.assertEquals(c.__class__, C) + assert c.__class__ == C def test_metaclass_inherited(self): class M(type): @@ -28,9 +24,9 @@ __metaclass__ = M class C(B): pass - self.assertEquals(C.__class__, M) + assert C.__class__ == M c = C() - self.assertEquals(c.__class__, C) + assert c.__class__ == C def test_metaclass_global(self): d = {} @@ -46,30 +42,30 @@ exec metatest_text in d C = d['C'] M = d['M'] - self.assertEquals(C.__class__, M) + assert C.__class__ == M c = C() - self.assertEquals(c.__class__, C) + assert c.__class__ == C def test_method(self): class C: def meth(self): return 1 c = C() - self.assertEqual(c.meth(), 1) + assert c.meth() == 1 def test_method_exc(self): class C: def meth(self): raise RuntimeError c = C() - self.assertRaises(RuntimeError, c.meth) + raises(RuntimeError, c.meth) def test_class_attr(self): class C: a = 42 c = C() - self.assertEquals(c.a, 42) - self.assertEquals(C.a, 42) + assert c.a == 42 + assert C.a == 42 def test_class_attr_inherited(self): class C: @@ -77,42 +73,42 @@ class D(C): pass d = D() - self.assertEquals(d.a, 42) - self.assertEquals(D.a, 42) + assert d.a == 42 + assert D.a == 42 def test___new__(self): class A(object): pass - self.assert_(isinstance(A(), A)) - self.assert_(isinstance(object.__new__(A), A)) - self.assert_(isinstance(A.__new__(A), A)) + assert isinstance(A(), A) + assert isinstance(object.__new__(A), A) + assert isinstance(A.__new__(A), A) def test_int_subclass(self): class R(int): pass x = R(5) - self.assertEquals(type(x), R) - self.assertEquals(x, 5) - self.assertEquals(type(int(x)), int) - self.assertEquals(int(x), 5) + assert type(x) == R + assert x == 5 + assert type(int(x)) == int + assert int(x) == 5 def test_long_subclass(self): class R(long): pass x = R(5L) - self.assertEquals(type(x), R) - self.assertEquals(x, 5L) - self.assertEquals(type(long(x)), long) - self.assertEquals(long(x), 5L) + assert type(x) == R + assert x == 5L + assert type(long(x)) == long + assert long(x) == 5L def test_float_subclass(self): class R(float): pass x = R(5.5) - self.assertEquals(type(x), R) - self.assertEquals(x, 5.5) - self.assertEquals(type(float(x)), float) - self.assertEquals(float(x), 5.5) + assert type(x) == R + assert x == 5.5 + assert type(float(x)) == float + assert float(x) == 5.5 def test_meth_doc(self): class C: @@ -122,10 +118,10 @@ """this is a docstring""" pass c = C() - self.assertEquals(C.meth_no_doc.__doc__, None) - self.assertEquals(c.meth_no_doc.__doc__, None) - self.assertEquals(C.meth_doc.__doc__, """this is a docstring""") - self.assertEquals(c.meth_doc.__doc__, """this is a docstring""") + assert C.meth_no_doc.__doc__ == None + assert c.meth_no_doc.__doc__ == None + assert C.meth_doc.__doc__ == """this is a docstring""" + assert c.meth_doc.__doc__ == """this is a docstring""" def test_getattribute(self): class C: @@ -134,8 +130,5 @@ return 'two' return super(C, self).__getattribute__(attr) c = C() - self.assertEquals(c.one, "two") - self.assertRaises(AttributeError, getattr, c, "two") - -if __name__ == '__main__': - testit.main() + assert c.one == "two" + raises(AttributeError, getattr, c, "two") From alastair at codespeak.net Mon Jan 3 13:25:06 2005 From: alastair at codespeak.net (alastair at codespeak.net) Date: Mon, 3 Jan 2005 13:25:06 +0100 (MET) Subject: [pypy-svn] r8050 - pypy/trunk/doc/funding/negotiations Message-ID: <20050103122506.731B05AEB0@thoth.codespeak.net> Author: alastair Date: Mon Jan 3 13:25:05 2005 New Revision: 8050 Modified: pypy/trunk/doc/funding/negotiations/IST-2-004779-STP.cpf Log: Added HHUD's details to CPF. Only added what we were given by HHUD. There are fields missing. Modified: pypy/trunk/doc/funding/negotiations/IST-2-004779-STP.cpf ============================================================================== --- pypy/trunk/doc/funding/negotiations/IST-2-004779-STP.cpf (original) +++ pypy/trunk/doc/funding/negotiations/IST-2-004779-STP.cpf Mon Jan 3 13:25:05 2005 @@ -644,13 +644,13 @@ HHUD - - - - - + Universitaetstr. 1 + 40225 + DE + 40225 Duesseldorf + http://www.uni-duesseldorf.de/ - + HE @@ -658,7 +658,7 @@ - + DE 81 12222 416 @@ -669,12 +669,12 @@ - - + GOV + NAO - + NC @@ -1264,34 +1264,34 @@ 004779 PYPY 8 - - + Pallme Koenig + Ulf - - - - - - - - - - - - + M + +492118111000/1 + +4921114534 + ulf.pallme.koenig at verwaltung.uni-duesseldorf.de + Thole + Hermann + Dr. + M + +492118112245 + +492118111404 + droste at verwaltung.uni-duesseldorf.de + Lehrstuhl Praktische Informatik - - - - + Leuschel + Michael + Prof. + M - + mal at ecs.soton.ac.uk @@ -1302,9 +1302,9 @@ - - - + Chancellor + Vice Chancellor + Group Leader @@ -1547,9 +1547,9 @@ PYPY 8 Heinrich Heine Universitaet Duesseldorf - + Pallme Koenig - + Ulf @@ -2435,7 +2435,7 @@ DEUTSCHES FORSCHUNGSZENTRUM FUER KUENSTLICHE INTELLIGENZ GMBH ERWIN-SCHROEDINGER-STRASSE (BAU 57) KAISERSLAUTERN - DE + Germany DE148646973 Olthoff +49 631 2053210 @@ -2444,7 +2444,7 @@ Commerzbank Kaiserslautern Kaiserslautern - DE + Germany 540 400 42 1282995 From tismer at codespeak.net Tue Jan 4 22:35:07 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 4 Jan 2005 22:35:07 +0100 (MET) Subject: [pypy-svn] r8067 - pypy/trunk/src/pypy/translator Message-ID: <20050104213507.924D15A6D9@thoth.codespeak.net> Author: tismer Date: Tue Jan 4 22:35:07 2005 New Revision: 8067 Modified: pypy/trunk/src/pypy/translator/genrpy.py Log: this is an almost working implementation of restricted appspace to inter translation, now. Needs a little more stuff to generate the right functions (still mixed with C code) but will be there in coupla hours. Modified: pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- pypy/trunk/src/pypy/translator/genrpy.py (original) +++ pypy/trunk/src/pypy/translator/genrpy.py Tue Jan 4 22:35:07 2005 @@ -13,18 +13,45 @@ This module is very much under construction and not yet usable for much more than testing. """ - -from pypy.objspace.flow.model import traverse -from pypy.objspace.flow import FlowObjSpace -from pypy.objspace.flow.model import FunctionGraph, Block, Link, Variable, Constant +from __future__ import generators +import autopath, os, sys, exceptions +from pypy.objspace.flow.model import Variable, Constant, SpaceOperation +from pypy.objspace.flow.model import FunctionGraph, Block, Link from pypy.objspace.flow.model import last_exception, last_exc_value -from pypy.translator.simplify import simplify_graph -from pypy.interpreter.error import OperationError -from types import FunctionType +from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph +from pypy.translator.simplify import remove_direct_loops +from pypy.interpreter.pycode import CO_VARARGS +from pypy.annotation import model as annmodel +from types import FunctionType, CodeType + +from pypy.objspace.std.restricted_int import r_int, r_uint from pypy.translator.translator import Translator +from pypy.objspace.std import StdObjSpace + +from pypy.interpreter.gateway import app2interp, interp2app + + +# ____________________________________________________________ + +def c_string(s): + return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\"'),) + +def uniquemodulename(name, SEEN={}): + # never reuse the same module name within a Python session! + i = 0 + while True: + i += 1 + result = '%s_%d' % (name, i) + if result not in SEEN: + SEEN[result] = True + return result + +def go_figure_out_this_name(source): + # ahem + return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( + source, ) -import sys def ordered_blocks(graph): @@ -51,14 +78,16 @@ class GenRpy: - def __init__(self, f, translator, modname=None): + def __init__(self, f, translator, modname=None, f2=None, f2name=None): self.f = f + self.f2 = f2 + self.f2name = f2name self.translator = translator self.modname = (modname or - translator.functions[0].__name__) - self.rpynames = {Constant(None).key: 'w(None)', - Constant(False).key: 'w(False)', - Constant(True).key: 'w(True)', + uniquemodulename(translator.functions[0].__name__)) + self.rpynames = {Constant(None).key: 'space.w_None', + Constant(False).key: 'space.w_False', + Constant(True).key: 'space.w_True', } self.seennames = {} @@ -69,45 +98,30 @@ self.globaldecl = [] self.globalobjects = [] self.pendingfunctions = [] + self.debugstack = () # linked list of nested nameof() # special constructors: self.has_listarg = {} for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - self.current_globals = {} - self.glob_names = [] - self.glob_values = [] + self.space = StdObjSpace() # for introspection + # debugging + global _gen; _gen = self + self.gen_source() - - def adjust_namespace(self): - """ inspect the globals of self.current_func and build a searchable list - of the globals. - """ - g = self.current_func.func_globals - if g is self.current_globals: - return - self.current_globals = g - order = [(value, key) for key, value in g.items()] - order.sort() - self.glob_names = [key for value, key in order] - self.glob_values = [value for value, key in order] - - def find_global_name(self, obj): - for i in xrange(len(self.glob_values)): - if self.glob_values[i] is obj: - return self.glob_names[i] - return None - def nameof(self, obj): + def nameof(self, obj, debug=None): key = Constant(obj).key try: return self.rpynames[key] except KeyError: - #name = "w(%s)" % str(obj) - #self.rpynames[key] = name - #return name + if debug: + stackentry = debug, obj + else: + stackentry = obj + self.debugstack = (self.debugstack, stackentry) if (type(obj).__module__ != '__builtin__' and not isinstance(obj, type)): # skip user-defined metaclasses # assume it's a user defined thingy @@ -120,17 +134,20 @@ if meth: break else: - raise Exception, "nameof(%r) in %r" % (obj, self.current_func) + raise Exception, "nameof(%r)" % (obj,) name = meth(obj) + self.debugstack, x = self.debugstack + assert x is stackentry self.rpynames[key] = name return name def uniquename(self, basename): + basename = basename.translate(C_IDENTIFIER) n = self.seennames.get(basename, 0) self.seennames[basename] = n+1 if n == 0: self.globalobjects.append(basename) - self.globaldecl.append('static PyObject *%s;' % (basename,)) + self.globaldecl.append('# global object %s' % (basename,)) return basename else: return self.uniquename('%s_%d' % (basename, n)) @@ -139,7 +156,7 @@ if type(value) is not object: raise Exception, "nameof(%r) in %r" % (value, self.current_func) name = self.uniquename('g_object') - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*)&PyBaseObject_Type, ""))'%name) + self.initcode.append('%s = object()'%name) return name def nameof_module(self, value): @@ -149,38 +166,63 @@ value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value name = self.uniquename('mod%s'%value.__name__) - self.initcode.append('INITCHK(%s = PyImport_ImportModule("%s"))'%(name, value.__name__)) + self.initcode.append('import %s as %s' % (value.__name__, name)) return name def nameof_int(self, value): - return "w(%d)" % value + if value >= 0: + name = 'gi_%d' % value + else: + name = 'gim_%d' % abs(value) + name = self.uniquename(name) + self.initcode.append('%s = space.newint(%d)' % (name, value)) + return name def nameof_long(self, value): + # allow short longs only, meaning they + # must fit into a word. + assert (sys.maxint*2+1)&value==value, "your literal long is too long" # assume we want them in hex most of the time if value < 256L: - return "%dL" % value + s = "%dL" % value + else: + s = "0x%08xL" % value + if value >= 0: + name = 'glong_%s' % s else: - return "0x%08xL" % value + name = 'glongm_%d' % abs(value) + name = self.uniquename(name) + self.initcode.append('%s = space.wrap(%s) # XXX implement long!' % (name, s)) + return name def nameof_float(self, value): - return "w(%s)" % value - + name = 'gfloat_%s' % value + name = (name.replace('-', 'minus') + .replace('.', 'dot')) + name = self.uniquename(name) + self.initcode.append('%s = space.newfloat(%r)' % (name, value)) + return name + def nameof_str(self, value): - name = self.find_global_name(value) - if name: - return "w(%s)" % name - return "w(%s)" % repr(value) + if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']: + # non-printable string + namestr = repr(value)[1:-1] + else: + # printable string + namestr = value + if not namestr: + namestr = "_emptystr_" + name = self.uniquename('gs_' + namestr[:32]) + self.initcode.append('%s = space.newstring(%r)' % (name, value)) + return name def skipped_function(self, func): # debugging only! Generates a placeholder for missing functions # that raises an exception when called. name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('static PyMethodDef ml_%s = { "%s", &skipped, METH_VARARGS };' % (name, name)) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\tPy_INCREF(%s);' % name) - self.initcode.append('\tPyCFunction_GET_SELF(%s) = %s;' % (name, name)) + self.globaldecl.append('# global decl %s' % (name, name)) + self.initcode.append('# build func %s' % name) return name def nameof_function(self, func): @@ -198,9 +240,9 @@ print "skipped", printable_name return self.skipped_function(func) name = func.__name__ - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\t%s->ob_type = &PyGenCFunction_Type;' % name) + name = self.uniquename('gfunc_' + func.__name__) + f_name = 'f_' + name[6:] + self.initcode.append('%s = interp2app(%s)' % (name, f_name)) self.pendingfunctions.append(func) return name @@ -223,7 +265,7 @@ typ = self.nameof(meth.im_class) name = self.uniquename('gmeth_'+meth.im_func.__name__) self.initcode.append( - 'INITCHK(%s = gencfunc_descr_get(%s, %s, %s))'%( + '%s = 42# what?gencfunc_descr_get(%s, %s, %s))'%( name, func, ob, typ)) return name @@ -235,16 +277,13 @@ return False else: return "probably" # True - if attr in ann.getpbcattrs(pbc): - return True classdef = ann.getuserclasses().get(pbc.__class__) - if (classdef and - classdef.about_attribute(attr) != annmodel.SomeImpossibleValue()): + if classdef and classdef.about_attribute(attr) is not None: return True return False def later(self, gen): - self.latercode.append(gen) + self.latercode.append((gen, self.debugstack)) def nameof_instance(self, instance): name = self.uniquename('ginst_' + instance.__class__.__name__) @@ -254,24 +293,51 @@ content.sort() for key, value in content: if self.should_translate_attr(instance, key): - yield 'INITCHK(SETUP_INSTANCE_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) - self.initcode.append('INITCHK(SETUP_INSTANCE(%s, %s))' % ( + yield 'space.setattr(%s, %s, %s)' % ( + name, self.nameof(key), self.nameof(value)) + self.initcode.append('# how? INITCHK(SETUP_INSTANCE(%s, %s))' % ( name, cls)) self.later(initinstance()) return name def nameof_builtin_function_or_method(self, func): - return "w(%s)" % func.__name__ + if func.__self__ is None: + # builtin function + if hasattr(self.space, func.__name__): + return "space.%s" % func.__name__ + # where does it come from? Python2.2 doesn't have func.__module__ + for modname, module in sys.modules.items(): + if hasattr(module, '__file__'): + if (module.__file__.endswith('.py') or + module.__file__.endswith('.pyc') or + module.__file__.endswith('.pyo')): + continue # skip non-builtin modules + if func is getattr(module, func.__name__, None): + break + else: + raise Exception, '%r not found in any built-in module' % (func,) + name = self.uniquename('gbltin_' + func.__name__) + if modname == '__builtin__': + self.initcode.append('%s = space.getattr(space.w_builtin, %s)'% ( + name, self.nameof(func.__name__))) + else: + self.initcode.append('%s = space.getattr(%s, %s)' % ( + name, self.nameof(module), self.nameof(func.__name__))) + else: + # builtin (bound) method + name = self.uniquename('gbltinmethod_' + func.__name__) + self.initcode.append('%s = space.getattr(%s, %s)' % ( + name, self.nameof(func.__self__), self.nameof(func.__name__))) + return name def nameof_classobj(self, cls): if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): raise Exception, "%r should never be reached" % (cls,) - metaclass = "&PyType_Type" + metaclass = "space.w_type" if issubclass(cls, Exception): if cls.__module__ == 'exceptions': - return 'w(%s)'%cls.__name__ + return 'space.w_%s'%cls.__name__ #else: # # exceptions must be old-style classes (grr!) # metaclass = "&PyClass_Type" @@ -279,7 +345,7 @@ # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - metaclass = "&PyClass_Type" + metaclass = "space.type(space.w_Exception)" name = self.uniquename('gcls_' + cls.__name__) basenames = [self.nameof(base) for base in cls.__bases__] @@ -300,27 +366,64 @@ print value continue - yield 'INITCHK(SETUP_CLASS_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) + yield 'space.setattr(%s, %s, %s)' % ( + name, self.nameof(key), self.nameof(value)) - baseargs = ", ".join(basenames) - if baseargs: - baseargs = ', '+baseargs - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*) %s,' - %(name, metaclass)) - self.initcode.append('\t\t"s(%s){}", "%s"%s))' - %("O"*len(basenames), cls.__name__, baseargs)) + baseargs = ", ".join([self.nameof(basename) for basename in basenames]) + self.initcode.append('%s = space.call(%s, space.newtuple(\n' + ' [%s, space.newtuple([%s]), space.newdict([])]))' + %(name, metaclass, self.nameof(cls.__name__), baseargs)) self.later(initclassobj()) return name nameof_class = nameof_classobj # for Python 2.2 + typename_mapping = { + object: 'space.w_object', + int: 'space.w_int', + long: 'space.w_long', + bool: 'space.w_bool', + list: 'space.w_list', + tuple: 'space.w_tuple', + dict: 'space.w_dict', + str: 'space.w_str', + float: 'space.w_float', + type(Exception()): 'space.wrap(types.InstanceType)', + type: 'space.w_type', + complex:'space.wrap(types.ComplexType)', + unicode:'space.w_unicode', + file: 'space.wrap(file)', + type(None): 'space.wrap(types.NoneType)', + CodeType: 'space.wrap(types.CodeType)', + + ##r_int: 'space.w_int', + ##r_uint: 'space.w_int', + + # XXX we leak 5 references here, but that's the least of the + # problems with this section of code + # type 'builtin_function_or_method': + type(len): 'space.wrap(types.FunctionType)', + # type 'method_descriptor': + # XXX small problem here: + # XXX with space.eval, we get + # XXX but with wrap, we get + type(list.append): 'eval_helper(space, "list.append")', + # type 'wrapper_descriptor': + type(type(None).__repr__): 'eval_helper(space, ".type(None).__repr__")', + # type 'getset_descriptor': + # XXX here we get , + # while eval gives us + type(type.__dict__['__dict__']): 'eval_helper(space,'\ + ' "type(type.__dict__[\'__dict__\']))', + # type 'member_descriptor': + # XXX this does not work in eval! + type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", + } def nameof_type(self, cls): - return "w(%s)" % cls.__name__ ##?? if cls in self.typename_mapping: - return '(PyObject*) %s' % self.typename_mapping[cls] + return self.typename_mapping[cls] assert cls.__module__ != '__builtin__', \ "built-in class %r not found in typename_mapping" % (cls,) return self.nameof_classobj(cls) @@ -328,9 +431,8 @@ def nameof_tuple(self, tup): name = self.uniquename('g%dtuple' % len(tup)) args = [self.nameof(x) for x in tup] - args.insert(0, '%d' % len(tup)) args = ', '.join(args) - self.initcode.append('INITCHK(%s = PyTuple_Pack(%s))' % (name, args)) + self.initcode.append('%s = space.newtuple([%s])' % (name, args)) return name def nameof_list(self, lis): @@ -338,32 +440,23 @@ def initlist(): for i in range(len(lis)): item = self.nameof(lis[i]) - yield '\tPy_INCREF(%s);' % item - yield '\tPyList_SET_ITEM(%s, %d, %s);' % (name, i, item) - self.initcode.append('INITCHK(%s = PyList_New(%d))' % (name, len(lis))) + yield 'space.setitem(%s, %s, %s);' % ( + name, self.nameof(i), self.nameof(item)) + self.initcode.append('%s = space.newlist(%s)' % (name, self.nameof(0))) + self.initcode.append('%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) self.later(initlist()) return name def nameof_dict(self, dic): - name = self.find_global_name(dic) - if name: - return name - return 'space.newdict([w("sorry", "not yet"])' assert dic is not __builtins__ assert '__builtins__' not in dic, 'Seems to be the globals of %s' % ( dic.get('__name__', '?'),) name = self.uniquename('g%ddict' % len(dic)) def initdict(): for k in dic: - if type(k) is str: - yield ('\tINITCHK(PyDict_SetItemString' - '(%s, "%s", %s) >= 0)'%( - name, k, self.nameof(dic[k]))) - else: - yield ('\tINITCHK(PyDict_SetItem' - '(%s, %s, %s) >= 0)'%( - name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('INITCHK(%s = PyDict_New())' % (name,)) + yield ('space.setitem(%s, %s, %s)'%( + name, self.nameof(k), self.nameof(dic[k]))) + self.initcode.append('%s = space.newdict([])' % (name,)) self.later(initdict()) return name @@ -373,11 +466,9 @@ name = self.uniquename('gdescriptor_%s_%s' % ( md.__objclass__.__name__, md.__name__)) cls = self.nameof(md.__objclass__) - self.initcode.append('INITCHK(PyType_Ready((PyTypeObject*) %s) >= 0)' % - cls) - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - '((PyTypeObject*) %s)->tp_dict, "%s"))' % - (name, cls, md.__name__)) + # do I need to take the dict and then getitem??? + self.initcode.append('%s = space.getattr(%s, %s)' % + (name, cls, self.nameof(md.__name__))) return name nameof_getset_descriptor = nameof_member_descriptor nameof_method_descriptor = nameof_member_descriptor @@ -385,11 +476,11 @@ def nameof_file(self, fil): if fil is sys.stdin: - return 'PySys_GetObject("stdin")' + return '#XXX how: PySys_GetObject("stdin")' if fil is sys.stdout: - return 'PySys_GetObject("stdout")' + return '#XXX how: PySys_GetObject("stdout")' if fil is sys.stderr: - return 'PySys_GetObject("stderr")' + return '#XXX how: PySys_GetObject("stderr")' raise Exception, 'Cannot translate an already-open file: %r' % (fil,) def gen_source(self): @@ -399,79 +490,255 @@ 'entrypointname': self.translator.functions[0].__name__, 'entrypoint': self.nameof(self.translator.functions[0]), } - - # make sure + # header + print >> f, self.RPY_HEADER # function implementations while self.pendingfunctions: - func = self.current_func = self.pendingfunctions.pop() - self.adjust_namespace() + func = self.pendingfunctions.pop() self.gen_rpyfunction(func) # collect more of the latercode after each function while self.latercode: - #gen, self.debugstack = self.latercode.pop() - gen = self.latercode.pop() + gen, self.debugstack = self.latercode.pop() #self.initcode.extend(gen) -- eats TypeError! bad CPython! for line in gen: self.initcode.append(line) self.debugstack = () - #self.gen_global_declarations() - print >> f + self.gen_global_declarations() # footer - # maybe not needed - return - print >> f, self.C_INIT_HEADER % info + print >> f, self.RPY_INIT_HEADER % info if self.f2name is not None: - print >> f, '#include "%s"' % self.f2name - for codeline in self.initcode: - print >> f, '\t' + codeline - print >> f, self.C_INIT_FOOTER % info + print >> f, ' execfile("%s")' % self.f2name + for codelines in self.initcode: + for codeline in codelines.split("\n"): + print >> f, " %s" % codeline + print >> f, self.RPY_INIT_FOOTER % info + + def gen_global_declarations(self): + g = self.globaldecl + if g: + f = self.f + print >> f, '# global declaration%s' % ('s'*(len(g)>1)) + for line in g: + print >> f, line + print >> f + del g[:] + g = self.globalobjects + for name in g: + pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) + del g[:] + if self.f2 is not None: + for line in self.initcode: + print >> self.f2, line + del self.initcode[:] def gen_rpyfunction(self, func): - local_names = {} + f = self.f + body = list(self.rpyfunction_body(func)) + name_of_defaults = [self.nameof(x, debug=('Default argument of', func)) + for x in (func.func_defaults or ())] + self.gen_global_declarations() + + # print header + cname = self.nameof(func) + assert cname.startswith('gfunc_') + f_name = 'f_' + cname[6:] + + # collect all the local variables + graph = self.translator.getflowgraph(func) + localslst = [] + def visit(node): + if isinstance(node, Block): + localslst.extend(node.getvariables()) + traverse(visit, graph) + localnames = [a.name for a in uniqueitems(localslst)] + + # collect all the arguments + if func.func_code.co_flags & CO_VARARGS: + vararg = graph.getargs()[-1] + positional_args = graph.getargs()[:-1] + else: + vararg = None + positional_args = graph.getargs() + min_number_of_args = len(positional_args) - len(name_of_defaults) + + fast_args = [a.name for a in positional_args] + if vararg is not None: + fast_args.append(str(vararg)) + fast_name = 'fast' + f_name + + fast_set = dict(zip(fast_args, fast_args)) + + declare_fast_args = [('PyObject *' + a) for a in fast_args] + if declare_fast_args: + declare_fast_args = 'TRACE_ARGS ' + ', '.join(declare_fast_args) + else: + declare_fast_args = 'TRACE_ARGS_VOID' + fast_function_header = ('static PyObject *\n' + '%s(%s)' % (fast_name, declare_fast_args)) + + print >> f, fast_function_header + ';' # forward + print >> f + + print >> f, 'static PyObject *' + print >> f, '%s(PyObject* self, PyObject* args, PyObject* kwds)' % ( + f_name,) + print >> f, '{' + print >> f, '\tFUNCTION_HEAD(%s, %s, args, %s, __FILE__, __LINE__ - 2)' % ( + c_string('%s(%s)' % (cname, ', '.join(name_of_defaults))), + cname, + '(%s)' % (', '.join(map(c_string, name_of_defaults) + ['NULL']),), + ) + + kwlist = ['"%s"' % name for name in + func.func_code.co_varnames[:func.func_code.co_argcount]] + kwlist.append('0') + print >> f, '\tstatic char* kwlist[] = {%s};' % (', '.join(kwlist),) + + if fast_args: + print >> f, '\tPyObject *%s;' % (', *'.join(fast_args)) + print >> f + + print >> f, '\tFUNCTION_CHECK()' + + # argument unpacking + if vararg is not None: + print >> f, '\t%s = PyTuple_GetSlice(args, %d, INT_MAX);' % ( + vararg, len(positional_args)) + print >> f, '\tif (%s == NULL)' % (vararg,) + print >> f, '\t\tFUNCTION_RETURN(NULL)' + print >> f, '\targs = PyTuple_GetSlice(args, 0, %d);' % ( + len(positional_args),) + print >> f, '\tif (args == NULL) {' + print >> f, '\t\tERR_DECREF(%s)' % (vararg,) + print >> f, '\t\tFUNCTION_RETURN(NULL)' + print >> f, '\t}' + tail = """{ +\t\tERR_DECREF(args) +\t\tERR_DECREF(%s) +\t\tFUNCTION_RETURN(NULL); +\t} +\tPy_DECREF(args);""" % vararg + else: + tail = '\n\t\tFUNCTION_RETURN(NULL)' + for i in range(len(name_of_defaults)): + print >> f, '\t%s = %s;' % ( + positional_args[min_number_of_args+i], + name_of_defaults[i]) + fmt = 'O'*min_number_of_args + if min_number_of_args < len(positional_args): + fmt += '|' + 'O'*(len(positional_args)-min_number_of_args) + lst = ['args', 'kwds', + '"%s:%s"' % (fmt, func.__name__), + 'kwlist', + ] + lst += ['&' + a.name for a in positional_args] + print >> f, '\tif (!PyArg_ParseTupleAndKeywords(%s))' % ', '.join(lst), + print >> f, tail + + call_fast_args = list(fast_args) + if call_fast_args: + call_fast_args = 'TRACE_CALL ' + ', '.join(call_fast_args) + else: + call_fast_args = 'TRACE_CALL_VOID' + print >> f, '\treturn %s(%s);' % (fast_name, call_fast_args) + print >> f, '}' + print >> f + + print >> f, fast_function_header + print >> f, '{' + + fast_locals = [arg for arg in localnames if arg not in fast_set] + if fast_locals: + print >> f, '\tPyObject *%s;' % (', *'.join(fast_locals),) + print >> f + + # generate an incref for each input argument + # skipped + + # print the body + for line in body: + print >>f, line + + # print the PyMethodDef + # skipped + + if not self.translator.frozen: + # this is only to keep the RAM consumption under control + del self.translator.flowgraphs[func] + Variable.instances.clear() + + def rpyfunction_body(self, func): + try: + graph = self.translator.getflowgraph(func) + except Exception, e: + print 20*"*", e + print func + raise + # not needed, tuple assignment + # remove_direct_loops(graph) + checkgraph(graph) + + blocknum = {} + allblocks = [] + localnames = {} def expr(v, wrapped = True): if isinstance(v, Variable): n = v.name if n.startswith("v") and n[1:].isdigit(): - ret = local_names.get(v.name) + ret = localnames.get(v.name) if not ret: if wrapped: - local_names[v.name] = ret = "w_%d" % len(local_names) + localnames[v.name] = ret = "w_%d" % len(localnames) else: - local_names[v.name] = ret = "v%d" % len(local_names) + localnames[v.name] = ret = "v%d" % len(localnames) return ret - return v.name elif isinstance(v, Constant): - return self.nameof(v.value) + return self.nameof(v.value, + debug=('Constant in the graph of',func)) else: - #raise TypeError, "expr(%r)" % (v,) - # XXX how do I resolve these? - return "space.%s" % str(v) + raise TypeError, "expr(%r)" % (v,) def arglist(args): res = [expr(arg) for arg in args] return ", ".join(res) def oper(op): - print op.opname, op.args if op.opname == "simple_call": v = op.args[0] - if isinstance(v, Constant) and self.find_global_name(v.value): - fmt = "%s = %s(space, %s)" + exv = expr(v) + if exv.startswith("space.") and not exv.startswith("space.w_"): + # it is a space method + fmt = "%s = %s(%s)" else: - fmt = "%s = space.call(%s, space.newtuple([%s]))" - return fmt % (expr(op.result), expr(op.args[0]), arglist(op.args[1:])) + if isinstance(v, Constant) and v.value in self.translator.flowgraphs: + fmt = "%s = %s(space, %s)" + else: + fmt = "%s = space.call(%s, space.newtuple([%s]))" + return fmt % (expr(op.result), expr(v), arglist(op.args[1:])) if op.opname in self.has_listarg: fmt = "%s = %s([%s])" else: fmt = "%s = %s(%s)" # specialcase is_true - if op.opname == "is_true": - return fmt % (expr(op.result, False), expr(op.opname), arglist(op.args)) - return fmt % (expr(op.result), expr(op.opname), arglist(op.args)) + wrapped = op.opname != "is_true" + oper = "space.%s" % op.opname + return fmt % (expr(op.result, wrapped), oper, arglist(op.args)) + + def large_assignment(left, right, margin=65): + expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) + pieces = expr.split(",") + res = [pieces.pop(0)] + for piece in pieces: + if len(res[-1])+len(piece)+1 > margin: + res[-1] += "," + res.append(piece) + else: + res[-1] += (","+piece) + return res def gen_link(link, linklocalvars=None): "Generate the code to jump across the given Link." @@ -484,7 +751,12 @@ src = expr(a1) left.append(expr(a2)) right.append(src) - yield "%s = %s" % (", ".join(left), ", ".join(right)) + txt = "%s = %s" % (", ".join(left), ", ".join(right)) + if len(txt) <= 65: # arbitrary + yield txt + else: + for line in large_assignment(left, right): + yield line goto = blocknum[link.target] yield 'goto = %d' % goto if goto <= blocknum[block]: @@ -496,22 +768,21 @@ graph = t.getflowgraph(func) start = graph.startblock - blocks = ordered_blocks(graph) - nblocks = len(blocks) + allblocks = ordered_blocks(graph) + nblocks = len(allblocks) blocknum = {} - for block in blocks: + for block in allblocks: blocknum[block] = len(blocknum)+1 # create function declaration name = func.__name__ # change this args = [expr(var) for var in start.inputargs] argstr = ", ".join(args) - print >> f, "def %s(space, %s):" % (name, argstr) - print >> f, " w = space.wrap" - print >> f, " goto = %d # startblock" % blocknum[start] - print >> f, " while True:" - + yield "def %s(space, %s):" % (name, argstr) + yield " goto = %d # startblock" % blocknum[start] + yield " while True:" + def render_block(block): catch_exception = block.exitswitch == Constant(last_exception) regular_op = len(block.operations) - catch_exception @@ -548,13 +819,20 @@ yield " %s" % op # we must catch the exception raised by the last operation, # which goes to the last err%d_%d label written above. + # Since we only have OperationError, we need to select: + yield "except OperationError, e:" + q = "if" for link in block.exits[1:]: assert issubclass(link.exitcase, Exception) - yield "except OperationError, e:" + # Exeption classes come unwrapped in link.exitcase + yield " %s space.issubtype(e.w_type, %s):" % (q, + self.nameof(link.exitcase)) + q = "elif" for op in gen_link(link, { Constant(last_exception): 'e.w_type', Constant(last_exc_value): 'e.w_value'}): - yield " %s" % op + yield " %s" % op + yield " else:raise # unhandled case, should not happen" else: # block ending in a switch on a value exits = list(block.exits) @@ -576,12 +854,36 @@ for op in gen_link(exits[-1]): yield " %s" % op - for block in blocks: + for block in allblocks: blockno = blocknum[block] - print >> f - print >> f, " if goto == %d:" % blockno + yield "" + yield " if goto == %d:" % blockno for line in render_block(block): - print >> f, " %s" % line + yield " %s" % line + +# ____________________________________________________________ + + RPY_HEADER = '#!/bin/env python\n# -*- coding: LATIN-1 -*-' + + RPY_SEP = "#*************************************************************" + + RPY_INIT_HEADER = RPY_SEP + ''' + +# something needed here? MODULE_INITFUNC(%(modname)s) +''' + + RPY_INIT_FOOTER = ''' +# entry point: %(entrypointname)s, %(entrypoint)s) +''' + +# a translation table suitable for str.translate() to remove +# non-C characters from an identifier +C_IDENTIFIER = ''.join([(('0' <= chr(i) <= '9' or + 'a' <= chr(i) <= 'z' or + 'A' <= chr(i) <= 'Z') and chr(i) or '_') + for i in range(256)]) + + def somefunc(arg): pass @@ -645,34 +947,45 @@ def test_mod(): return app_mod__String_ANY("-%s-", ["hallo"]) -entry_point = (f, ff, fff, app_str_decode__String_ANY_ANY, test_mod, test_md5) [-2] +def test_join(): + return " ".join(["hi", "there"]) + +entry_point = (f, ff, fff, app_str_decode__String_ANY_ANY, test_mod, test_md5, test_join) [5] import os, sys from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) appdir = os.path.join(autopath.pypydir, 'appspace') -try: - hold = sys.path[:] +if appdir not in sys.path: sys.path.insert(0, appdir) - t = Translator(entry_point, verbose=False, simplifying=True) - if 0: - gen = GenRpy(sys.stdout, t) - else: - fil= file("d:/tmp/look.py", "w") - gen = GenRpy(fil, t) - print >> fil, \ +t = Translator(entry_point, verbose=False, simplifying=True) +if 0: + gen = GenRpy(sys.stdout, t) +else: + fil= file("d:/tmp/look.py", "w") + gen = GenRpy(fil, t) + print >> fil, \ """ from pypy.objspace.std import StdObjSpace space = StdObjSpace() -space.simple_call = space.call test_mod(space) """ - fil.close() -finally: - sys.path[:] = hold + fil.close() + #t.simplify() #t.view() # debugging graph = t.getflowgraph() ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab + +## testing how to call things +def f(space, w_a, w_b): + return space.add(w_a, w_b) + +space = gen.space +w = space.wrap +gw_f = interp2app(f) +w_gw_f = w(gw_f) +res = space.call(w_gw_f, space.newlist([w(2), w(3)])) +print res \ No newline at end of file From tismer at codespeak.net Tue Jan 4 22:44:19 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 4 Jan 2005 22:44:19 +0100 (MET) Subject: [pypy-svn] r8068 - pypy/trunk/src/pypy/translator Message-ID: <20050104214419.B1FE85A6D9@thoth.codespeak.net> Author: tismer Date: Tue Jan 4 22:44:19 2005 New Revision: 8068 Modified: pypy/trunk/src/pypy/translator/genrpy.py Log: wrap imported module Modified: pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- pypy/trunk/src/pypy/translator/genrpy.py (original) +++ pypy/trunk/src/pypy/translator/genrpy.py Tue Jan 4 22:44:19 2005 @@ -166,7 +166,8 @@ value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value name = self.uniquename('mod%s'%value.__name__) - self.initcode.append('import %s as %s' % (value.__name__, name)) + self.initcode.append('import %s as _tmp' % value.__name__) + self.initcode.append('%s = space.wrap(_tmp)' % (name)) return name From tismer at codespeak.net Wed Jan 5 17:35:48 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Wed, 5 Jan 2005 17:35:48 +0100 (MET) Subject: [pypy-svn] r8078 - pypy/trunk/src/pypy/interpreter Message-ID: <20050105163548.30CFC5ACEF@thoth.codespeak.net> Author: tismer Date: Wed Jan 5 17:35:47 2005 New Revision: 8078 Modified: pypy/trunk/src/pypy/interpreter/pyopcode.py Log: changed LOAD_GLOBAL to support the flow space better. In case of a NameError, where the space does not define NameError, we raise a real NameError with a message. Modified: pypy/trunk/src/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/pyopcode.py (original) +++ pypy/trunk/src/pypy/interpreter/pyopcode.py Wed Jan 5 17:35:47 2005 @@ -525,8 +525,13 @@ if not e.match(f.space, f.space.w_KeyError): raise message = "global name '%s' is not defined" % varname - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) + try: + w_exc_type = f.space.w_NameError + w_exc_value = f.space.wrap(message) + except AttributeError: + # object space does not support it, so crash really + raise NameError, (message + + ", but %s has no NameError!" % f.space) raise OperationError(w_exc_type, w_exc_value) f.valuestack.push(w_value) From tismer at codespeak.net Wed Jan 5 17:38:40 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Wed, 5 Jan 2005 17:38:40 +0100 (MET) Subject: [pypy-svn] r8079 - pypy/trunk/src/pypy/appspace Message-ID: <20050105163840.2792C5ACEF@thoth.codespeak.net> Author: tismer Date: Wed Jan 5 17:38:39 2005 New Revision: 8079 Modified: pypy/trunk/src/pypy/appspace/_formatting.py Log: found a typo by running genrpy over the file :-)) Modified: pypy/trunk/src/pypy/appspace/_formatting.py ============================================================================== --- pypy/trunk/src/pypy/appspace/_formatting.py (original) +++ pypy/trunk/src/pypy/appspace/_formatting.py Wed Jan 5 17:38:39 2005 @@ -225,7 +225,7 @@ class FloatFFormatter(FloatFormatter): def _format(self, v): if v/1e25 > 1e25: - return floatGFormatter('g', self.flags, self.width, + return FloatGFormatter('g', self.flags, self.width, self.prec, self.value).format() ds, k = flonum2digits(v) digits = self.fDigits(ds, k) From hpk at codespeak.net Fri Jan 7 12:45:29 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 7 Jan 2005 12:45:29 +0100 (MET) Subject: [pypy-svn] r8125 - pypy/trunk/doc Message-ID: <20050107114529.6C03027B4A@code1.codespeak.net> Author: hpk Date: Fri Jan 7 12:45:29 2005 New Revision: 8125 Modified: pypy/trunk/doc/readme.txt Log: trying to fix some links (documentation generation needs to be cleaned up to allow testing links locally) Modified: pypy/trunk/doc/readme.txt ============================================================================== --- pypy/trunk/doc/readme.txt (original) +++ pypy/trunk/doc/readme.txt Fri Jan 7 12:45:29 2005 @@ -89,6 +89,6 @@ --------------------------------------------------------------------------------- .. _this: http://docutils.sourceforge.net/docs/rst/quickref.html -.. _ObjectSpace: /pypy/doc/objspace/objspace.txt -.. _ObjectSpaceInterface: /pypy/doc/objspace/objspaceinterface.txt +.. _ObjectSpace: objspace/objspace.html +.. _ObjectSpaceInterface: objspace/objspaceinterface.html From pedronis at codespeak.net Fri Jan 7 14:19:53 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 7 Jan 2005 14:19:53 +0100 (MET) Subject: [pypy-svn] r8131 - pypy/trunk/src/pypy/translator/tool Message-ID: <20050107131953.288AF27B55@code1.codespeak.net> Author: pedronis Date: Fri Jan 7 14:19:53 2005 New Revision: 8131 Modified: pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py Log: get rid of deprecated .get with changed return value. use property directly. test_ctrans.py passes again. Modified: pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py ============================================================================== --- pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py (original) +++ pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py Fri Jan 7 14:19:53 2005 @@ -54,7 +54,7 @@ lastdir = path.local() os.chdir(str(dirpath)) try: - modname = cfile.get('purebasename') + modname = cfile.purebasename if debug: print "modname", modname c = stdoutcapture.Capture(mixed_out_err = True) try: From pedronis at codespeak.net Fri Jan 7 16:03:52 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 7 Jan 2005 16:03:52 +0100 (MET) Subject: [pypy-svn] r8143 - pypy/trunk/src/pypy/translator/java/test Message-ID: <20050107150352.91D7C27B4F@code1.codespeak.net> Author: pedronis Date: Fri Jan 7 16:03:52 2005 New Revision: 8143 Added: pypy/trunk/src/pypy/translator/java/test/__init__.py Log: needed to make test_all happy. Added: pypy/trunk/src/pypy/translator/java/test/__init__.py ============================================================================== From pedronis at codespeak.net Fri Jan 7 16:53:18 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 7 Jan 2005 16:53:18 +0100 (MET) Subject: [pypy-svn] r8145 - pypy/trunk/src/pypy/translator/java Message-ID: <20050107155318.28F6C27B4F@code1.codespeak.net> Author: pedronis Date: Fri Jan 7 16:53:17 2005 New Revision: 8145 Modified: pypy/trunk/src/pypy/translator/java/genjava.py Log: some jvm (the spec perhaps) require main to be public. Modified: pypy/trunk/src/pypy/translator/java/genjava.py ============================================================================== --- pypy/trunk/src/pypy/translator/java/genjava.py (original) +++ pypy/trunk/src/pypy/translator/java/genjava.py Fri Jan 7 16:53:17 2005 @@ -74,7 +74,7 @@ entrypoint = self.nameof(self.translator.functions[0]) f = self.jdir.join('test.java').open('w') print >> f, 'class test extends PyObject {' - print >> f, ' static void main(String[] argv) {' + print >> f, ' static public void main(String[] argv) {' print >> f, ' PyObject result = %s.op_call_%d(%s);' % ( entrypoint, len(inputargs), ', '.join([self.nameof(x) for x in inputargs])) From hpk at codespeak.net Sat Jan 8 13:54:46 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 13:54:46 +0100 (MET) Subject: [pypy-svn] r8163 - in pypy/branch/src-pytest/pypy: . interpreter interpreter/test Message-ID: <20050108125446.B6AE627B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 13:54:46 2005 New Revision: 8163 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py Log: ported interpreter/test_eval.py to pytest and therefore: - fixed and cleaned up the pypy conftest.py test configuration. It now uses the new setup/teardown hooks on Items thus simplifying the create-space-magic a bit. We might want to think about cleaner semantics where exactly "space" gets created and bound. - baseobjspace now has a _isequal(w_1, w_2) helper which returns an interpreter-level boolean, to simplify testing at interp-level: assert space._iseq(w_1, w_2) Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 13:54:46 2005 @@ -78,7 +78,21 @@ class PyPyItem(py.test.Item): # All PyPy test items catch and display OperationErrors specially. - def execute_in_space(self, space, target, *args): + + #def setup_module(self, mod): + # if hasattr(mod, 'objspacename'): + # mod.space = getttestobjspace(mod.objspacename) + # super(PyPyItem, self).setup_module(mod) + + def setup_method(self, method): + base = getattr(method, 'im_self', method) + name = getattr(base, 'objspacename', None) + if name is None: + name = method.im_func.func_globals.get('objspacename', None) + base.space = gettestobjspace(name) + super(PyPyItem, self).setup_method(method) + + def execute_appex(self, space, target, *args): try: target(*args) except OperationError, e: @@ -90,7 +104,7 @@ if 'space' in co.co_varnames[:co.co_argcount]: name = target.func_globals.get('objspacename', None) space = gettestobjspace(name) - self.execute_in_space(space, target, space, *args) + self.execute_appex(space, target, space, *args) else: target(*args) @@ -100,26 +114,19 @@ name = target.func_globals.get('objspacename', None) space = gettestobjspace(name) func = app2interp_temp(target, target.__name__) - self.execute_in_space(space, func, space) + self.execute_appex(space, func, space) class IntTestMethod(PyPyItem): def execute(self, target, *args): - name = target.func_globals.get('objspacename', None) - if name is None: - name = getattr(target.im_class, 'objspacename', None) - instance = target.im_self - instance.space = space = gettestobjspace(name) - self.execute_in_space(space, target, *args) + space = target.im_self.space + self.execute_appex(space, target, *args) class AppTestMethod(PyPyItem): def execute(self, target, *args): assert not args - name = target.func_globals.get('objspacename', None) - if name is None: - name = getattr(target.im_class, 'objspacename', None) - space = gettestobjspace(name) + space = target.im_self.space func = app2interp_temp(target.im_func, target.__name__) - self.execute_in_space(space, func, space, space.w_None) + self.execute_appex(space, func, space, space.w_None) class AppClassCollector(py.test.collect.Class): Item = AppTestMethod Modified: pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py Sat Jan 8 13:54:46 2005 @@ -119,6 +119,10 @@ # w_id_x = self.id(w_x) # w_id_y = self.id(w_y) # return self.eq(w_id_x, w_id_y) + # + def _isequal(self, w_obj1, w_obj2): + """ only for shortcutting purposes. """ + return self.is_true(self.eq(w_obj1, w_obj2)) def not_(self, w_obj): return self.wrap(not self.is_true(w_obj)) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py Sat Jan 8 13:54:46 2005 @@ -1,13 +1,11 @@ import autopath -from pypy.tool import testit from pypy.interpreter.eval import Frame, UNDEFINED from pypy.interpreter.pycode import PyCode -class TestFrame(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() +class TestFrame: + def setup_method(self, method): def c(x, y, *args): pass code = PyCode()._from_code(c.func_code) @@ -15,26 +13,27 @@ def test_fast2locals(self): w = self.space.wrap + space = self.space self.f.fast2locals() - self.assertEqual_w(self.f.w_locals, self.space.newdict([])) + assert space._isequal(self.f.w_locals, self.space.newdict([])) self.f.fastlocals_w[0] = w(5) self.f.fast2locals() - self.assertEqual_w(self.f.w_locals, self.space.newdict([ - (w('x'), w(5))])) + assert space._isequal(self.f.w_locals, self.space.newdict([ + (w('x'), w(5))])) self.f.fastlocals_w[2] = w(7) self.f.fast2locals() - self.assertEqual_w(self.f.w_locals, self.space.newdict([ + assert space._isequal(self.f.w_locals, self.space.newdict([ (w('x'), w(5)), (w('args'), w(7))])) def sameList(self, l1, l2): - self.assertEqual(len(l1), len(l2)) + assert len(l1) == len(l2) for w_1, w_2 in zip(l1, l2): - self.failIf((w_1 is UNDEFINED) != (w_2 is UNDEFINED)) + assert not ((w_1 is UNDEFINED) != (w_2 is UNDEFINED)) if w_1 is not UNDEFINED: - self.assertEqual_w(w_1, w_2) + assert self.space._isequal(w_1, w_2) def test_locals2fast(self): w = self.space.wrap @@ -53,6 +52,3 @@ self.f.locals2fast() self.sameList(self.f.fastlocals_w, [w(5), UNDEFINED, w(7), UNDEFINED, UNDEFINED]) - -if __name__ == '__main__': - testit.main() From hpk at codespeak.net Sat Jan 8 14:08:24 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 14:08:24 +0100 (MET) Subject: [pypy-svn] r8164 - in pypy/branch/src-pytest/pypy/interpreter: . test Message-ID: <20050108130824.8E1AF27B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 14:08:24 2005 New Revision: 8164 Modified: pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py Log: rename "space._isequal" to "space.eq_w", reusing our various uses of "_w" to indicate that something special regarding wrappings is going on (it returns an interpreter-level boolean). Modified: pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py Sat Jan 8 14:08:24 2005 @@ -120,8 +120,8 @@ # w_id_y = self.id(w_y) # return self.eq(w_id_x, w_id_y) # - def _isequal(self, w_obj1, w_obj2): - """ only for shortcutting purposes. """ + def eq_w(self, w_obj1, w_obj2): + """ return interp-level boolean of eq(w_obj1, w_obj2). """ return self.is_true(self.eq(w_obj1, w_obj2)) def not_(self, w_obj): Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_eval.py Sat Jan 8 14:08:24 2005 @@ -12,19 +12,19 @@ self.f = Frame(self.space, code, numlocals=5) def test_fast2locals(self): - w = self.space.wrap space = self.space + w = space.wrap self.f.fast2locals() - assert space._isequal(self.f.w_locals, self.space.newdict([])) + assert space.eq_w(self.f.w_locals, self.space.newdict([])) self.f.fastlocals_w[0] = w(5) self.f.fast2locals() - assert space._isequal(self.f.w_locals, self.space.newdict([ + assert space.eq_w(self.f.w_locals, self.space.newdict([ (w('x'), w(5))])) self.f.fastlocals_w[2] = w(7) self.f.fast2locals() - assert space._isequal(self.f.w_locals, self.space.newdict([ + assert space.eq_w(self.f.w_locals, self.space.newdict([ (w('x'), w(5)), (w('args'), w(7))])) @@ -33,7 +33,7 @@ for w_1, w_2 in zip(l1, l2): assert not ((w_1 is UNDEFINED) != (w_2 is UNDEFINED)) if w_1 is not UNDEFINED: - assert self.space._isequal(w_1, w_2) + assert self.space.eq_w(w_1, w_2) def test_locals2fast(self): w = self.space.wrap From hpk at codespeak.net Sat Jan 8 14:16:28 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 14:16:28 +0100 (MET) Subject: [pypy-svn] r8165 - pypy/branch/src-pytest/pypy/interpreter/test Message-ID: <20050108131628.AE73927B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 14:16:28 2005 New Revision: 8165 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py Log: use py.code.Source for nicer inlining of source code in the tests, get rid of textwrap here. Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py Sat Jan 8 14:16:28 2005 @@ -1,5 +1,4 @@ -import autopath -import textwrap +import py class TestInterpreter: def codetest(self, source, functionname, args): @@ -9,6 +8,8 @@ from pypy.interpreter import pyframe, gateway, module space = self.space + source = str(py.code.Source(source).strip()) + compile = space.builtin.compile w = space.wrap w_code = compile(w(source), w(''), w('exec'), w(0), w(0)) @@ -39,36 +40,36 @@ # del cls.space def test_exception_trivial(self): - x = self.codetest(''' -def f(): - try: - raise Exception() - except Exception, e: - return 1 - return 2 -''', 'f', []) + x = self.codetest('''\ + def f(): + try: + raise Exception() + except Exception, e: + return 1 + return 2 + ''', 'f', []) assert x == 1 def test_exception(self): x = self.codetest(''' -def f(): - try: - raise Exception, 1 - except Exception, e: - return e.args[0] -''', 'f', []) + def f(): + try: + raise Exception, 1 + except Exception, e: + return e.args[0] + ''', 'f', []) assert x == 1 def test_finally(self): code = ''' -def f(a): - try: - if a: - raise Exception - a = -12 - finally: - return a -''' + def f(a): + try: + if a: + raise Exception + a = -12 + finally: + return a + ''' assert self.codetest(code, 'f', [0]) == -12 assert self.codetest(code, 'f', [1]) == 1 @@ -81,29 +82,29 @@ def test_except2(self): x = self.codetest(''' -def f(): - try: - z = 0 - try: - "x"+1 - except TypeError, e: - z = 5 - raise e - except TypeError: - return z -''', 'f', []) + def f(): + try: + z = 0 + try: + "x"+1 + except TypeError, e: + z = 5 + raise e + except TypeError: + return z + ''', 'f', []) assert x == 5 def test_except3(self): code = ''' -def f(v): - z = 0 - try: - z = 1//v - except ZeroDivisionError, e: - z = "infinite result" - return z -''' + def f(v): + z = 0 + try: + z = 1//v + except ZeroDivisionError, e: + z = "infinite result" + return z + ''' assert self.codetest(code, 'f', [2]) == 0 assert self.codetest(code, 'f', [0]) == "infinite result" ess = "TypeError: unsupported operand type" @@ -114,32 +115,32 @@ def test_break(self): code = ''' -def f(n): - total = 0 - for i in range(n): - try: - if i == 4: - break - finally: - total += i - return total -''' + def f(n): + total = 0 + for i in range(n): + try: + if i == 4: + break + finally: + total += i + return total + ''' assert self.codetest(code, 'f', [4]) == 1+2+3 assert self.codetest(code, 'f', [9]) == 1+2+3+4 def test_continue(self): code = ''' -def f(n): - total = 0 - for i in range(n): - try: - if i == 4: - continue - finally: - total += 100 - total += i - return total -''' + def f(n): + total = 0 + for i in range(n): + try: + if i == 4: + continue + finally: + total += 100 + total += i + return total + ''' assert self.codetest(code, 'f', [4]) == 1+2+3+400 assert self.codetest(code, 'f', [9]) == ( 1+2+3 + 5+6+7+8+900) @@ -155,70 +156,70 @@ assert arg is not None return real_call_function(w_obj, *arg_w) self.space.call_function = safe_call_function - code = textwrap.dedent(''' + code = ''' def f(): import sys - ''') + ''' self.codetest(code, 'f', []) def test_extended_arg(self): longexpr = 'x = x or ' + '-x' * 2500 code = ''' -def f(x): - %s - %s - %s - %s - %s - %s - %s - %s - %s - %s - while x: - x -= 1 # EXTENDED_ARG is for the JUMP_ABSOLUTE at the end of the loop - return x -''' % ((longexpr,)*10) + def f(x): + %s + %s + %s + %s + %s + %s + %s + %s + %s + %s + while x: + x -= 1 # EXTENDED_ARG is for the JUMP_ABSOLUTE at the end of the loop + return x + ''' % ((longexpr,)*10) assert self.codetest(code, 'f', [3]) == 0 def test_call_star_starstar(self): - code = ''' -def f1(n): - return n*2 -def f38(n): - f = f1 - r = [ - f(n, *[]), - f(n), - apply(f, (n,)), - apply(f, [n]), - f(*(n,)), - f(*[n]), - f(n=n), - f(**{'n': n}), - apply(f, (n,), {}), - apply(f, [n], {}), - f(*(n,), **{}), - f(*[n], **{}), - f(n, **{}), - f(n, *[], **{}), - f(n=n, **{}), - f(n=n, *[], **{}), - f(*(n,), **{}), - f(*[n], **{}), - f(*[], **{'n':n}), - ] - return r -''' + code = '''\ + def f1(n): + return n*2 + def f38(n): + f = f1 + r = [ + f(n, *[]), + f(n), + apply(f, (n,)), + apply(f, [n]), + f(*(n,)), + f(*[n]), + f(n=n), + f(**{'n': n}), + apply(f, (n,), {}), + apply(f, [n], {}), + f(*(n,), **{}), + f(*[n], **{}), + f(n, **{}), + f(n, *[], **{}), + f(n=n, **{}), + f(n=n, *[], **{}), + f(*(n,), **{}), + f(*[n], **{}), + f(*[], **{'n':n}), + ] + return r + ''' assert self.codetest(code, 'f38', [117]) == [234]*19 def test_star_arg(self): - code = textwrap.dedent(''' + code = ''' def f(x, *y): return y def g(u, v): return f(u, *v) - ''') + ''' assert self.codetest(code, 'g', [12, ()]) == () assert self.codetest(code, 'g', [12, (3,4)]) == (3,4) assert self.codetest(code, 'g', [12, []]) == () From hpk at codespeak.net Sat Jan 8 14:31:43 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 14:31:43 +0100 (MET) Subject: [pypy-svn] r8166 - in pypy/branch/src-pytest/pypy: . interpreter tool Message-ID: <20050108133143.5978227B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 14:31:43 2005 New Revision: 8166 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py pypy/branch/src-pytest/pypy/tool/pytestsupport.py Log: ok, moved the eq_w to pytestsupport for now just as raises_w. Although i think that eq_w would be generally useful as a shortcut. Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 14:31:43 2005 @@ -38,6 +38,7 @@ space.setitem(space.w_builtins, space.wrap('raises'), space.wrap(pytestsupport.app_raises)) space.raises_w = pytestsupport.raises_w.__get__(space) + space.eq_w = pytestsupport.eq_w.__get__(space) return space # Modified: pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/baseobjspace.py Sat Jan 8 14:31:43 2005 @@ -119,10 +119,6 @@ # w_id_x = self.id(w_x) # w_id_y = self.id(w_y) # return self.eq(w_id_x, w_id_y) - # - def eq_w(self, w_obj1, w_obj2): - """ return interp-level boolean of eq(w_obj1, w_obj2). """ - return self.is_true(self.eq(w_obj1, w_obj2)) def not_(self, w_obj): return self.wrap(not self.is_true(w_obj)) Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/pytestsupport.py (original) +++ pypy/branch/src-pytest/pypy/tool/pytestsupport.py Sat Jan 8 14:31:43 2005 @@ -155,3 +155,7 @@ except py.test.Item.ExceptionFailure, e: e.tbindex = getattr(e, 'tbindex', -1) - 1 raise + +def eq_w(space, w_obj1, w_obj2): + """ return interp-level boolean of eq(w_obj1, w_obj2). """ + return space.is_true(space.eq(w_obj1, w_obj2)) From hpk at codespeak.net Sat Jan 8 14:33:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 14:33:08 +0100 (MET) Subject: [pypy-svn] r8167 - pypy/branch/src-pytest/pypy/interpreter/test Message-ID: <20050108133308.6E0E327B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 14:33:08 2005 New Revision: 8167 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_objspace.py Log: converted another test Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_objspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_objspace.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_objspace.py Sat Jan 8 14:33:08 2005 @@ -1,31 +1,24 @@ import autopath -from pypy.tool import testit +from py.test import raises # this test isn't so much to test that the objspace interface *works* # -- it's more to test that it's *there* -class TestObjSpace(testit.TestCase): - - def setUp(self): - self.space = testit.objspace() - - def tearDown(self): - pass - +class TestObjSpace: def test_newstring(self): w = self.space.wrap s = 'abc' chars_w = [w(ord(c)) for c in s] - self.assertEqual_w(w(s), self.space.newstring(chars_w)) + self.space.eq_w(w(s), self.space.newstring(chars_w)) def test_newstring_fail(self): w = self.space.wrap s = 'abc' not_chars_w = [w(c) for c in s] - self.assertRaises_w(self.space.w_TypeError, + self.space.raises_w(self.space.w_TypeError, self.space.newstring, not_chars_w) - self.assertRaises_w(self.space.w_ValueError, + self.space.raises_w(self.space.w_ValueError, self.space.newstring, [w(-1)]) @@ -33,7 +26,7 @@ w = self.space.wrap l = range(10) w_l = self.space.newlist([w(i) for i in l]) - self.assertEqual_w(w_l, w(l)) + self.space.eq_w(w_l, w(l)) def test_newdict(self): w = self.space.wrap @@ -41,13 +34,13 @@ items_w = [(w(k), w(v)) for (k, v) in items] d = dict(items) w_d = self.space.newdict(items_w) - self.assertEqual_w(w_d, w(d)) + self.space.eq_w(w_d, w(d)) def test_newtuple(self): w = self.space.wrap t = tuple(range(10)) w_t = self.space.newtuple([w(i) for i in t]) - self.assertEqual_w(w_t, w(t)) + self.space.eq_w(w_t, w(t)) def test_is_true(self): w = self.space.wrap @@ -55,64 +48,58 @@ false = (1==0) w_true = w(true) w_false = w(false) - self.failUnless(self.space.is_true(w_true)) - self.failIf(self.space.is_true(w_false)) + assert self.space.is_true(w_true) + assert not self.space.is_true(w_false) def test_is_(self): w_l = self.space.newlist([]) w_m = self.space.newlist([]) - self.assertEqual(self.space.is_(w_l, w_l), self.space.w_True) - self.assertEqual(self.space.is_(w_l, w_m), self.space.w_False) + assert self.space.is_(w_l, w_l) == self.space.w_True + assert self.space.is_(w_l, w_m) == self.space.w_False def test_newbool(self): - self.assertEqual(self.space.newbool(0), self.space.w_False) - self.assertEqual(self.space.newbool(1), self.space.w_True) + assert self.space.newbool(0) == self.space.w_False + assert self.space.newbool(1) == self.space.w_True def test_unpackiterable(self): w = self.space.wrap l = [w(1), w(2), w(3), w(4)] w_l = self.space.newlist(l) - self.assertEqual(self.space.unpackiterable(w_l), l) - self.assertEqual(self.space.unpackiterable(w_l, 4), l) - self.assertRaises(ValueError, self.space.unpackiterable, w_l, 3) - self.assertRaises(ValueError, self.space.unpackiterable, w_l, 5) + assert self.space.unpackiterable(w_l) == l + assert self.space.unpackiterable(w_l, 4) == l + raises(ValueError, self.space.unpackiterable, w_l, 3) + raises(ValueError, self.space.unpackiterable, w_l, 5) def test_unpacktuple(self): w = self.space.wrap l = [w(1), w(2), w(3), w(4)] w_l = self.space.newtuple(l) - self.assertEqual(self.space.unpacktuple(w_l), l) - self.assertEqual(self.space.unpacktuple(w_l, 4), l) - self.assertRaises(ValueError, self.space.unpacktuple, w_l, 3) - self.assertRaises(ValueError, self.space.unpacktuple, w_l, 5) + assert self.space.unpacktuple(w_l) == l + assert self.space.unpacktuple(w_l, 4) == l + raises(ValueError, self.space.unpacktuple, w_l, 3) + raises(ValueError, self.space.unpacktuple, w_l, 5) def test_exception_match(self): - self.failUnless(self.space.exception_match(self.space.w_ValueError, - self.space.w_ValueError)) - self.failUnless(self.space.exception_match(self.space.w_IndexError, - self.space.w_LookupError)) - self.failIf(self.space.exception_match(self.space.w_ValueError, - self.space.w_LookupError)) - -class ModuleMinimalTest(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() + assert self.space.exception_match(self.space.w_ValueError, + self.space.w_ValueError) + assert self.space.exception_match(self.space.w_IndexError, + self.space.w_LookupError) + assert not self.space.exception_match(self.space.w_ValueError, + self.space.w_LookupError) +class TestModuleMinimal: def test_sys_exists(self): w_sys = self.space.get_builtin_module('sys') - self.assert_(self.space.is_true(w_sys)) + assert self.space.is_true(w_sys) def test_import_exists(self): space = self.space w_builtin = space.get_builtin_module('__builtin__') - self.assert_(space.is_true(w_builtin)) + assert space.is_true(w_builtin) w_name = space.wrap('__import__') w_import = self.space.getattr(w_builtin, w_name) - self.assert_(space.is_true(w_import)) + assert space.is_true(w_import) def test_sys_import(self): from pypy.interpreter.main import run_string run_string('import sys', space=self.space) - -if __name__ == '__main__': - testit.main() From hpk at codespeak.net Sat Jan 8 14:42:49 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 14:42:49 +0100 (MET) Subject: [pypy-svn] r8168 - in pypy/branch/src-pytest/pypy/tool: . test Message-ID: <20050108134249.A7DD527B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 14:42:49 2005 New Revision: 8168 Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py pypy/branch/src-pytest/pypy/tool/test/test_pytestsupport.py Log: fixed pytestsupport: an explicit "raise AssertionError('...')" does not invoke app_normalize_exception. Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/pytestsupport.py (original) +++ pypy/branch/src-pytest/pypy/tool/pytestsupport.py Sat Jan 8 14:42:49 2005 @@ -77,10 +77,10 @@ space.call_args(w_parent_init, __args__.prepend(w_self)) framestack = space.getexecutioncontext().framestack frame = framestack.top(0) - # Argh! we see app-level helpers in the frame stack! + # Argh! we may see app-level helpers in the frame stack! # that's very probably very bad... - assert frame.code.co_name == 'app_normalize_exception' - frame = framestack.top(1) + if frame.code.co_name == 'app_normalize_exception': + frame = framestack.top(1) runner = AppFrame(frame) try: Modified: pypy/branch/src-pytest/pypy/tool/test/test_pytestsupport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/test/test_pytestsupport.py (original) +++ pypy/branch/src-pytest/pypy/tool/test/test_pytestsupport.py Sat Jan 8 14:42:49 2005 @@ -37,3 +37,13 @@ assert space.unwrap(space.str(e.w_value)) == 'assert 42 == 43' else: assert False, "got no exception!" + +def app_test_exception(): + try: + raise AssertionError("42") + except AssertionError: + pass + else: + raise AssertionError, "app level AssertionError mixup!" + + From hpk at codespeak.net Sat Jan 8 15:05:38 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 15:05:38 +0100 (MET) Subject: [pypy-svn] r8169 - in pypy/branch/src-pytest/pypy: . interpreter/test Message-ID: <20050108140538.2A68127B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 15:05:37 2005 New Revision: 8169 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/interpreter/test/test_exceptcomp.py pypy/branch/src-pytest/pypy/interpreter/test/test_exec.py pypy/branch/src-pytest/pypy/interpreter/test/test_extmodule.py pypy/branch/src-pytest/pypy/interpreter/test/test_function.py pypy/branch/src-pytest/pypy/interpreter/test/test_gateway.py pypy/branch/src-pytest/pypy/interpreter/test/test_main.py pypy/branch/src-pytest/pypy/interpreter/test/test_module.py Log: ported all the rest of the interpreter tests moved create-space-magic to setup_class because there doesn't appear to be a use case for doing it at setup_method time but there is one (in test_module) for having it already at class-level. Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 15:05:37 2005 @@ -85,13 +85,13 @@ # mod.space = getttestobjspace(mod.objspacename) # super(PyPyItem, self).setup_module(mod) - def setup_method(self, method): - base = getattr(method, 'im_self', method) - name = getattr(base, 'objspacename', None) + def setup_class(self, cls): + name = getattr(cls, 'objspacename', None) if name is None: - name = method.im_func.func_globals.get('objspacename', None) - base.space = gettestobjspace(name) - super(PyPyItem, self).setup_method(method) + m = __import__(cls.__module__) + name = getattr(m, 'objspacename', None) + cls.space = gettestobjspace(name) + super(PyPyItem, self).setup_class(cls) def execute_appex(self, space, target, *args): try: Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_exceptcomp.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_exceptcomp.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_exceptcomp.py Sat Jan 8 15:05:37 2005 @@ -3,12 +3,8 @@ New for PyPy - Could be incorporated into CPython regression tests. """ import autopath -from pypy.tool import testit -class TestExceptionComp(testit.AppTestCase): - - def setUp(self): - self.space = testit.objspace() +class AppTestExceptionComp: ### XXX - String exceptions depreciated? ## def test_string(self): @@ -133,6 +129,3 @@ pass except: self.fail("Exception does not match self in deeply nested tuple.") - -if __name__ == "__main__": - testit.main() Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_exec.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_exec.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_exec.py Sat Jan 8 15:05:37 2005 @@ -3,45 +3,41 @@ New for PyPy - Could be incorporated into CPython regression tests. """ import autopath -from pypy.tool import testit -class TestExecStmt(testit.AppTestCase): - - def setUp(self): - self.space = testit.objspace() +class AppTestExecStmt: def test_string(self): g = {} l = {} exec "a = 3" in g, l - self.failUnlessEqual(l['a'], 3) + assert not l['a'] != 3 def test_localfill(self): g = {} exec "a = 3" in g - self.failUnlessEqual(g['a'], 3) + assert not g['a'] != 3 def test_builtinsupply(self): g = {} exec "pass" in g - self.failUnless(g.has_key('__builtins__')) + assert g.has_key('__builtins__') def test_invalidglobal(self): def f(): exec 'pass' in 1 - self.failUnlessRaises(TypeError,f) + raises(TypeError,f) def test_invalidlocal(self): def f(): exec 'pass' in {}, 2 - self.failUnlessRaises(TypeError,f) + raises(TypeError,f) def test_codeobject(self): co = compile("a = 3", '', 'exec') g = {} l = {} exec co in g, l - self.failUnlessEqual(l['a'], 3) + assert not l['a'] != 3 ## # Commented out as PyPy give errors using open() ## # ["Not availible in restricted mode"] @@ -54,23 +50,20 @@ def test_implicit(self): a = 4 exec "a = 3" - self.failUnlessEqual(a,3) + assert not a !=3 def test_tuplelocals(self): g = {} l = {} exec ("a = 3", g, l) - self.failUnlessEqual(l['a'], 3) + assert not l['a'] != 3 def test_tupleglobals(self): g = {} exec ("a = 3", g) - self.failUnlessEqual(g['a'], 3) + assert not g['a'] != 3 def test_exceptionfallthrough(self): def f(): exec 'raise TypeError' in {} - self.failUnlessRaises(TypeError,f) - -if __name__ == "__main__": - testit.main() + raises(TypeError,f) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_extmodule.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_extmodule.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_extmodule.py Sat Jan 8 15:05:37 2005 @@ -1,34 +1,25 @@ import autopath import os -from pypy.tool import testit from pypy.interpreter.extmodule import BuiltinModule - -class TestBuiltinModule(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() - +class TestBuiltinModule: def test_foomodule(self): space = self.space sourcefile = os.path.join(autopath.this_dir, 'foomodule.py') m = BuiltinModule(space, 'foo', sourcefile=sourcefile) w = space.wrap w_m = space.wrap(m) - self.assertEqual_w(space.getattr(w_m, w('__name__')), w('foo')) - self.assertEqual_w(space.getattr(w_m, w('__file__')), w(sourcefile)) + self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo')) + self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile)) # check app-level definitions - self.assertEqual_w(m.w_foo, space.w_Ellipsis) - self.assertEqual_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) - self.assertEqual_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) - self.assertEqual_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) - self.assertEqual_w(space.getattr(w_m, w('foo2')), w('hello')) - self.assertEqual_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) + self.space.eq_w(m.w_foo, space.w_Ellipsis) + self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) + self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) + self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) + self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello')) + self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) # check interp-level definitions - self.assertEqual_w(m.w_foo2, w('hello')) - self.assertEqual_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) - self.assertEqual_w(m.fortytwo, w(42)) - - -if __name__ == '__main__': - testit.main() + self.space.eq_w(m.w_foo2, w('hello')) + self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) + self.space.eq_w(m.fortytwo, w(42)) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_function.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_function.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_function.py Sat Jan 8 15:05:37 2005 @@ -1,165 +1,163 @@ import autopath -from pypy.tool import testit import unittest from pypy.interpreter.function import Function, Method from pypy.interpreter.pycode import PyCode from pypy.interpreter.argument import Arguments -class AppTestFunctionIntrospection(testit.AppTestCase): +class AppTestFunctionIntrospection: def test_attributes(self): def f(): pass - self.assert_(hasattr(f, 'func_code')) - self.assertEquals(f.func_defaults, None) - self.assertEquals(f.func_dict, {}) - self.assertEquals(type(f.func_globals), dict) + assert hasattr(f, 'func_code') + assert f.func_defaults == None + assert f.func_dict == {} + assert type(f.func_globals) == dict #self.assertEquals(f.func_closure, None) XXX - self.assertEquals(f.func_doc, None) - self.assertEquals(f.func_name, 'f') + assert f.func_doc == None + assert f.func_name == 'f' def test_code_is_ok(self): def f(): pass - self.assert_(not hasattr(f.func_code, '__dict__')) + assert not hasattr(f.func_code, '__dict__') def test_underunder_attributes(self): def f(): pass - self.assertEquals(f.__name__, 'f') - self.assertEquals(f.__doc__, None) - self.assert_(f.__name__ == f.func_name) - self.assert_(f.__doc__ == f.func_doc) - self.assert_(f.__dict__ is f.func_dict) - self.assert_(hasattr(f, '__class__')) + assert f.__name__ == 'f' + assert f.__doc__ == None + assert f.__name__ == f.func_name + assert f.__doc__ == f.func_doc + assert f.__dict__ is f.func_dict + assert hasattr(f, '__class__') def test_write_doc(self): def f(): "hello" - self.assertEquals(f.__doc__, 'hello') + assert f.__doc__ == 'hello' f.__doc__ = 'good bye' - self.assertEquals(f.__doc__, 'good bye') + assert f.__doc__ == 'good bye' del f.__doc__ - self.assertEquals(f.__doc__, None) + assert f.__doc__ == None def test_write_func_doc(self): def f(): "hello" - self.assertEquals(f.func_doc, 'hello') + assert f.func_doc == 'hello' f.func_doc = 'good bye' - self.assertEquals(f.func_doc, 'good bye') + assert f.func_doc == 'good bye' del f.func_doc - self.assertEquals(f.func_doc, None) + assert f.func_doc == None -class AppTestFunction(testit.AppTestCase): +class AppTestFunction: def test_simple_call(self): def func(arg1, arg2): return arg1, arg2 res = func(23,42) - self.assertEquals(res[0], 23) - self.assertEquals(res[1], 42) + assert res[0] == 23 + assert res[1] == 42 def test_simple_varargs(self): def func(arg1, *args): return arg1, args res = func(23,42) - self.assertEquals(res[0], 23) - self.assertEquals(res[1], (42,)) + assert res[0] == 23 + assert res[1] == (42,) def test_simple_kwargs(self): def func(arg1, **kwargs): return arg1, kwargs res = func(23, value=42) - self.assertEquals(res[0], 23) - self.assertEquals(res[1], {'value': 42}) + assert res[0] == 23 + assert res[1] == {'value': 42} def test_kwargs_sets_wrong_positional_raises(self): def func(arg1): pass - self.assertRaises(TypeError, func, arg2=23) + raises(TypeError, func, arg2=23) def test_kwargs_sets_positional(self): def func(arg1): return arg1 res = func(arg1=42) - self.assertEquals(res, 42) + assert res == 42 def test_kwargs_sets_positional_mixed(self): def func(arg1, **kw): return arg1, kw res = func(arg1=42, something=23) - self.assertEquals(res[0], 42) - self.assertEquals(res[1], {'something': 23}) + assert res[0] == 42 + assert res[1] == {'something': 23} def test_kwargs_sets_positional_mixed(self): def func(arg1, **kw): return arg1, kw res = func(arg1=42, something=23) - self.assertEquals(res[0], 42) - self.assertEquals(res[1], {'something': 23}) + assert res[0] == 42 + assert res[1] == {'something': 23} def test_kwargs_sets_positional_twice(self): def func(arg1, **kw): return arg1, kw - self.assertRaises( + raises( TypeError, func, 42, {'arg1': 23}) def test_default_arg(self): def func(arg1,arg2=42): return arg1, arg2 res = func(arg1=23) - self.assertEquals(res[0], 23) - self.assertEquals(res[1], 42) + assert res[0] == 23 + assert res[1] == 42 def test_defaults_keyword_overrides(self): def func(arg1=42, arg2=23): return arg1, arg2 res = func(arg1=23) - self.assertEquals(res[0], 23) - self.assertEquals(res[1], 23) + assert res[0] == 23 + assert res[1] == 23 def test_defaults_keyword_override_but_leaves_empty_positional(self): def func(arg1,arg2=42): return arg1, arg2 - self.assertRaises(TypeError, func, arg2=23) + raises(TypeError, func, arg2=23) def test_kwargs_disallows_same_name_twice(self): def func(arg1, **kw): return arg1, kw - self.assertRaises(TypeError, func, 42, **{'arg1': 23}) + raises(TypeError, func, 42, **{'arg1': 23}) def test_kwargs_confusing_name(self): def func(self): # 'self' conflicts with the interp-level return self*7 # argument to call_function() res = func(self=6) - self.assertEquals(res, 42) + assert res == 42 def test_get(self): def func(self): return self obj = object() meth = func.__get__(obj, object) - self.assertEquals(meth(), obj) + assert meth() == obj def test_call_builtin(self): s = 'hello' - self.assertRaises(TypeError, len) - self.assertEquals(len(s), 5) - self.assertRaises(TypeError, len, s, s) - self.assertRaises(TypeError, len, s, s, s) - self.assertEquals(len(*[s]), 5) - self.assertEquals(len(s, *[]), 5) - self.assertRaises(TypeError, len, some_unknown_keyword=s) - self.assertRaises(TypeError, len, s, some_unknown_keyword=s) - self.assertRaises(TypeError, len, s, s, some_unknown_keyword=s) - -class AppTestMethod(testit.AppTestCase): + raises(TypeError, len) + assert len(s) == 5 + raises(TypeError, len, s, s) + raises(TypeError, len, s, s, s) + assert len(*[s]) == 5 + assert len(s, *[]) == 5 + raises(TypeError, len, some_unknown_keyword=s) + raises(TypeError, len, s, some_unknown_keyword=s) + raises(TypeError, len, s, s, some_unknown_keyword=s) +class AppTestMethod: def test_get(self): def func(self): return self class Object(object): pass obj = Object() # Create bound method from function obj.meth = func.__get__(obj, Object) - self.assertEquals(obj.meth(), obj) + assert obj.meth() == obj # Create bound method from method meth2 = obj.meth.__get__(obj, Object) - self.assertEquals(meth2(), obj) + assert meth2() == obj def test_get_get(self): # sanxiyn's test from email @@ -169,13 +167,12 @@ C.m = m D.m = C.m c = C() - self.assertEquals(c.m(), c) + assert c.m() == c d = D() - self.assertEquals(d.m(), d) + assert d.m() == d -class TestMethod(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() +class TestMethod: + def setup_method(self, method): def c(self, bar): return bar code = PyCode()._from_code(c.func_code) @@ -185,21 +182,21 @@ space = self.space w_meth = self.fn.descr_function_get(space.wrap(5), space.type(space.wrap(5))) meth = space.unwrap(w_meth) - self.failUnless(isinstance(meth, Method)) + assert isinstance(meth, Method) def test_call(self): space = self.space w_meth = self.fn.descr_function_get(space.wrap(5), space.type(space.wrap(5))) meth = space.unwrap(w_meth) w_result = meth.call_args(Arguments(space, [space.wrap(42)])) - self.assertEquals(space.unwrap(w_result), 42) + assert space.unwrap(w_result) == 42 def test_fail_call(self): space = self.space w_meth = self.fn.descr_function_get(space.wrap(5), space.type(space.wrap(5))) meth = space.unwrap(w_meth) args = Arguments(space, [space.wrap("spam"), space.wrap("egg")]) - self.assertRaises_w(self.space.w_TypeError, meth.call_args, args) + self.space.raises_w(self.space.w_TypeError, meth.call_args, args) def test_method_get(self): space = self.space @@ -213,25 +210,22 @@ # Check method returned from func.__get__() w_meth1 = func.descr_function_get(obj1, space.type(obj1)) meth1 = space.unwrap(w_meth1) - self.failUnless(isinstance(meth1, Method)) - self.assertEquals(meth1.call_args(args), obj1) + assert isinstance(meth1, Method) + assert meth1.call_args(args) == obj1 # Check method returned from method.__get__() # --- meth1 is already bound so meth1.__get__(*) is meth1. w_meth2 = meth1.descr_method_get(obj2, space.type(obj2)) meth2 = space.unwrap(w_meth2) - self.failUnless(isinstance(meth2, Method)) - self.assertEquals(meth2.call_args(args), obj1) + assert isinstance(meth2, Method) + assert meth2.call_args(args) == obj1 # Check method returned from unbound_method.__get__() w_meth3 = func.descr_function_get(None, space.type(obj2)) meth3 = space.unwrap(w_meth3) w_meth4 = meth3.descr_method_get(obj2, space.w_None) meth4 = space.unwrap(w_meth4) - self.failUnless(isinstance(meth4, Method)) - self.assertEquals(meth4.call_args(args), obj2) + assert isinstance(meth4, Method) + assert meth4.call_args(args) == obj2 # Check method returned from unbound_method.__get__() # --- with an incompatible class w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_None) - self.assert_(space.is_true(space.is_(w_meth5, w_meth3))) - -if __name__ == '__main__': - testit.main() + assert space.is_true(space.is_(w_meth5, w_meth3)) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_gateway.py Sat Jan 8 15:05:37 2005 @@ -1,33 +1,29 @@ import autopath -from pypy.tool import testit from pypy.interpreter import gateway -class TestBuiltinCode(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() - +class TestBuiltinCode: def test_signature(self): def c(space, w_x, w_y, *hello_w): pass code = gateway.BuiltinCode(c) - self.assertEqual(code.signature(), (['x', 'y'], 'hello', None)) + assert code.signature() == (['x', 'y'], 'hello', None) def d(self, w_boo): pass code = gateway.BuiltinCode(d) - self.assertEqual(code.signature(), (['self', 'boo'], None, None)) + assert code.signature() == (['self', 'boo'], None, None) def e(space, w_x, w_y, __args__): pass code = gateway.BuiltinCode(e) - self.assertEqual(code.signature(), (['x', 'y'], 'args', 'keywords')) + assert code.signature() == (['x', 'y'], 'args', 'keywords') def test_call(self): def c(space, w_x, w_y, *hello_w): u = space.unwrap w = space.wrap - self.assertEquals(len(hello_w), 2) - self.assertEquals(u(hello_w[0]), 0) - self.assertEquals(u(hello_w[1]), True) + assert len(hello_w) == 2 + assert u(hello_w[0]) == 0 + assert u(hello_w[1]) == True return w((u(w_x) - u(w_y) + len(hello_w))) code = gateway.BuiltinCode(c) w = self.space.wrap @@ -37,7 +33,7 @@ (w('hello'), self.space.newtuple([w(0), w(True)])), ]) w_result = code.exec_code(self.space, w_dict, w_dict) - self.assertEqual_w(w_result, w(102)) + self.space.eq_w(w_result, w(102)) def test_call_args(self): def c(space, w_x, w_y, __args__): @@ -55,19 +51,16 @@ (w('keywords'), self.space.newdict([(w('boo'), w(10))])), ]) w_result = code.exec_code(self.space, w_dict, w_dict) - self.assertEqual_w(w_result, w(1020)) - + self.space.eq_w(w_result, w(1020)) -class TestGateway(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() +class TestGateway: def test_app2interp(self): w = self.space.wrap def app_g3(a, b): return a+b g3 = gateway.app2interp_temp(app_g3) - self.assertEqual_w(g3(self.space, w('foo'), w('bar')), w('foobar')) + self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar')) def test_interp2app(self): space = self.space @@ -76,12 +69,12 @@ return space.add(w_a, w_b) app_g3 = gateway.interp2app_temp(g3) w_app_g3 = space.wrap(app_g3) - self.assertEqual_w( + self.space.eq_w( space.call(w_app_g3, space.newtuple([w('foo'), w('bar')]), space.newdict([])), w('foobar')) - self.assertEqual_w( + self.space.eq_w( space.call_function(w_app_g3, w('foo'), w('bar')), w('foobar')) @@ -96,7 +89,7 @@ """ in g gateway.importall(g, temporary=True) g1 = g['g1'] - self.assertEqual_w(g1(self.space, w('bar')), w('foobar')) + self.space.eq_w(g1(self.space, w('bar')), w('foobar')) def test_exportall(self): w = self.space.wrap @@ -109,8 +102,4 @@ """ in g gateway.exportall(g, temporary=True) g1 = gateway.app2interp_temp(g['app_g1']) - self.assertEqual_w(g1(self.space, w('bar')), w('foobar')) - - -if __name__ == '__main__': - testit.main() + self.space.eq_w(g1(self.space, w('bar')), w('foobar')) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_main.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_main.py Sat Jan 8 15:05:37 2005 @@ -1,11 +1,9 @@ -import unittest import autopath from cStringIO import StringIO -from pypy.tool.udir import udir -from pypy.tool import testit +import py +from pypy.tool.udir import udir from pypy.interpreter.baseobjspace import OperationError - from pypy.interpreter import main testcode = """\ @@ -18,9 +16,7 @@ testresultoutput = '11\n' - -def checkoutput(expected_output,f,*args): - space = testit.objspace() +def checkoutput(space, expected_output,f,*args): w_sys = space.get_builtin_module("sys") w_oldout = space.getattr(w_sys, space.wrap("stdout")) capturefn = udir.join('capturefile') @@ -33,30 +29,26 @@ capturefile.close() return capturefn.read() == expected_output -testfn = 'tmp_hello_world.py' -class TestMain(testit.TestCase): +testfn = 'tmp_hello_world.py' - def setUp(self): - self.space = testit.objspace() +class TestMain: + def setup_class(cls): ofile = open(testfn, 'w') ofile.write(testcode) ofile.close() - def tearDown(self): + def teardown_class(cls): import os os.remove(testfn) def test_run_file(self): - self.assert_(checkoutput(testresultoutput,main.run_file,testfn)) + assert checkoutput(self.space, testresultoutput,main.run_file,testfn) def test_run_string(self): - self.assert_(checkoutput(testresultoutput, - main.run_string,testcode,testfn)) + assert checkoutput(self.space, testresultoutput, + main.run_string,testcode,testfn) def test_eval_string(self): w_x = main.eval_string('2+2', space=self.space) - self.assertEqual_w(w_x, self.space.wrap(4)) - -if __name__ == '__main__': - testit.main() + self.space.eq_w(w_x, self.space.wrap(4)) Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_module.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_module.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_module.py Sat Jan 8 15:05:37 2005 @@ -1,47 +1,39 @@ import autopath -from pypy.tool import testit from pypy.interpreter.module import Module - -class TestModule(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace() - self.m = Module(self.space, self.space.wrap('m')) +class TestModule: + def setup_class(cls): + cls.m = Module(cls.space, cls.space.wrap('m')) + def teardown_class(cls): + del cls.m def test_name(self): w = self.space.wrap w_m = w(self.m) - self.assertEqual_w(self.space.getattr(w_m, w('__name__')), w('m')) + self.space.eq_w(self.space.getattr(w_m, w('__name__')), w('m')) def test_attr(self): w = self.space.wrap w_m = w(self.m) self.space.setattr(w_m, w('x'), w(15)) - self.assertEqual_w(self.space.getattr(w_m, w('x')), w(15)) + self.space.eq_w(self.space.getattr(w_m, w('x')), w(15)) self.space.delattr(w_m, w('x')) - self.assertRaises_w(self.space.w_AttributeError, + self.space.raises_w(self.space.w_AttributeError, self.space.delattr, w_m, w('x')) -class Test_ModuleObject(testit.AppTestCase): - - def setUp(self): - self.space = testit.objspace() - +class AppTest_ModuleObject: def test_attr(self): m = __import__('__builtin__') m.x = 15 - self.assertEqual(m.x, 15) - self.assertEqual(getattr(m, 'x'), 15) + assert m.x == 15 + assert getattr(m, 'x') == 15 setattr(m, 'x', 23) - self.assertEqual(m.x, 23) - self.assertEqual(getattr(m, 'x'), 23) + assert m.x == 23 + assert getattr(m, 'x') == 23 del m.x - self.assertRaises(AttributeError, getattr, m, 'x') + raises(AttributeError, getattr, m, 'x') m.x = 15 delattr(m, 'x') - self.assertRaises(AttributeError, getattr, m, 'x') - self.assertRaises(AttributeError, delattr, m, 'x') - -if __name__ == '__main__': - testit.main() + raises(AttributeError, getattr, m, 'x') + raises(AttributeError, delattr, m, 'x') From hpk at codespeak.net Sat Jan 8 15:50:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 8 Jan 2005 15:50:50 +0100 (MET) Subject: [pypy-svn] r8170 - in pypy/branch/src-pytest/pypy: . interpreter/test tool Message-ID: <20050108145050.A9BEC27B71@code1.codespeak.net> Author: hpk Date: Sat Jan 8 15:50:50 2005 New Revision: 8170 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/interpreter/test/test_code.py pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py pypy/branch/src-pytest/pypy/tool/pytestsupport.py Log: - a couple of fixes for python2.2 - made a "skip" method available at app-level in order to be able to skip tests. Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 15:50:50 2005 @@ -37,6 +37,8 @@ pytestsupport.build_pytest_assertion(space)) space.setitem(space.w_builtins, space.wrap('raises'), space.wrap(pytestsupport.app_raises)) + space.setitem(space.w_builtins, space.wrap('skip'), + space.wrap(pytestsupport.app_skip)) space.raises_w = pytestsupport.raises_w.__get__(space) space.eq_w = pytestsupport.eq_w.__get__(space) return space Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_code.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_code.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_code.py Sat Jan 8 15:50:50 2005 @@ -52,7 +52,11 @@ assert getattr(code, key) == value def test_code(self): - import sys, new + import sys + try: + import new + except ImportError: + skip("could not import new module") if sys.pypy_objspaceclass == 'TrivialObjSpace': return # skip codestr = "global c\na = 1\nb = 2\nc = a + b\n" Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_interpreter.py Sat Jan 8 15:50:50 2005 @@ -8,7 +8,7 @@ from pypy.interpreter import pyframe, gateway, module space = self.space - source = str(py.code.Source(source).strip()) + source = str(py.code.Source(source).strip()) + '\n' compile = space.builtin.compile w = space.wrap Modified: pypy/branch/src-pytest/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/pytestsupport.py (original) +++ pypy/branch/src-pytest/pypy/tool/pytestsupport.py Sat Jan 8 15:50:50 2005 @@ -1,3 +1,4 @@ +from __future__ import generators import autopath import py from py.__impl__.magic import exprinfo @@ -145,6 +146,13 @@ app_raises = interp2app_temp(pypyraises) +def pypyskip(space, w_message): + """skip a test at app-level. """ + msg = space.unwrap(w_message) + py.test.skip(msg) + +app_skip = interp2app_temp(pypyskip) + def raises_w(space, w_ExpectedException, *args, **kwds): try: excinfo = py.test.raises(OperationError, *args, **kwds) From pedronis at codespeak.net Sat Jan 8 18:34:22 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 18:34:22 +0100 (MET) Subject: [pypy-svn] r8173 - pypy/branch/src-pytest/pypy/module/test Message-ID: <20050108173422.8396727B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 18:34:22 2005 New Revision: 8173 Modified: pypy/branch/src-pytest/pypy/module/test/test_apply.py pypy/branch/src-pytest/pypy/module/test/test_builtin.py pypy/branch/src-pytest/pypy/module/test/test_filter.py pypy/branch/src-pytest/pypy/module/test/test_functional.py pypy/branch/src-pytest/pypy/module/test/test_import.py pypy/branch/src-pytest/pypy/module/test/test_minmax.py pypy/branch/src-pytest/pypy/module/test/test_newstyleclasses.py pypy/branch/src-pytest/pypy/module/test/test_range.py pypy/branch/src-pytest/pypy/module/test/test_reduce.py pypy/branch/src-pytest/pypy/module/test/test_sysmodule.py pypy/branch/src-pytest/pypy/module/test/test_vars.py pypy/branch/src-pytest/pypy/module/test/test_zip.py Log: ported all of module/test tests, mostly automatically using utestconvert with PyPy additions and improved fiximport. Modified: pypy/branch/src-pytest/pypy/module/test/test_apply.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_apply.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_apply.py Sat Jan 8 18:34:22 2005 @@ -1,33 +1,27 @@ import autopath -from pypy.tool import testit # This is a very trivial series of tests. If apply is subtlely broken, # we will have to find out some other way. -class TestApply(testit.AppTestCase): +class AppTestApply: def test_trivial_listonly(self): def mymin(*args): return min(list(args)) - self.assertEqual(apply(mymin, [-1,-2,-3,-4]), -4) + assert apply(mymin, [-1,-2,-3,-4]) == -4 def test_trivial_dictonly(self): def mymin(*arr, **kwargs): return min(list(arr) + kwargs.values()) - self.assertEqual(apply(mymin, - [], {'null' : 0, 'one': 1, 'two' : 2}), + assert apply(mymin, + [], {'null' : 0, 'one': 1, 'two' : 2}) == ( 0) def test_trivial(self): def mymin(*arr, **kwargs): return min(list(arr) + kwargs.values()) - self.assertEqual(apply(mymin, + assert apply(mymin, [-1,-2,-3,-4], - {'null' : 0, 'one': 1, 'two' : 2}), + {'null' : 0, 'one': 1, 'two' : 2}) == ( (-4)) - -if __name__ == '__main__': - testit.main() - - Modified: pypy/branch/src-pytest/pypy/module/test/test_builtin.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_builtin.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_builtin.py Sat Jan 8 18:34:22 2005 @@ -1,47 +1,43 @@ import autopath -from pypy.tool import testit -class TestBuiltinApp(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace() - +class AppTestBuiltinApp: def test_import(self): m = __import__('pprint') - self.assertEquals(m.pformat({}), '{}') - self.assertEquals(m.__name__, "pprint") - self.assertRaises(ImportError, __import__, 'spamspam') - self.assertRaises(TypeError, __import__, 1, 2, 3, 4) + assert m.pformat({}) == '{}' + assert m.__name__ == "pprint" + raises(ImportError, __import__, 'spamspam') + raises(TypeError, __import__, 1, 2, 3, 4) def test_chr(self): - self.assertEquals(chr(65), 'A') - self.assertRaises(ValueError, chr, -1) - self.assertRaises(TypeError, chr, 'a') + assert chr(65) == 'A' + raises(ValueError, chr, -1) + raises(TypeError, chr, 'a') def test_intern(self): - self.assertRaises(TypeError, intern) - self.assertRaises(TypeError, intern, 1) + raises(TypeError, intern) + raises(TypeError, intern, 1) s = "never interned before" s2 = intern(s) - self.assertEquals(s, s2) + assert s == s2 s3 = s.swapcase() - self.assert_(s3 != s2) + assert s3 != s2 s4 = s3.swapcase() - self.assert_(intern(s4) is s2) + assert intern(s4) is s2 def test_globals(self): d = {"foo":"bar"} exec "def f(): return globals()" in d d2 = d["f"]() - self.assert_(d2 is d) + assert d2 is d def test_locals(self): def f(): return locals() def g(c=0, b=0, a=0): return locals() - self.assertEquals(f(), {}) - self.assertEquals(g(), {'a':0, 'b':0, 'c':0}) + assert f() == {} + assert g() == {'a':0, 'b':0, 'c':0} def test_dir(self): def f(): @@ -49,48 +45,48 @@ def g(c=0, b=0, a=0): return dir() def nosp(x): return [y for y in x if y[0]!='_'] - self.assertEquals(f(), []) - self.assertEquals(g(), ['a', 'b', 'c']) + assert f() == [] + assert g() == ['a', 'b', 'c'] class X: pass - self.assertEquals(nosp(dir(X)), []) + assert nosp(dir(X)) == [] class X: a = 23 c = 45 b = 67 - self.assertEquals(nosp(dir(X)), ['a', 'b', 'c']) + assert nosp(dir(X)) == ['a', 'b', 'c'] def test_vars(self): def f(): return vars() def g(c=0, b=0, a=0): return vars() - self.assertEquals(f(), {}) - self.assertEquals(g(), {'a':0, 'b':0, 'c':0}) + assert f() == {} + assert g() == {'a':0, 'b':0, 'c':0} def test_getattr(self): class a: i = 5 - self.assertEquals(getattr(a, 'i'), 5) - self.assertRaises(AttributeError, getattr, a, 'k') - self.assertEquals(getattr(a, 'k', 42), 42) + assert getattr(a, 'i') == 5 + raises(AttributeError, getattr, a, 'k') + assert getattr(a, 'k', 42) == 42 def test_sum(self): - self.assertEquals(sum([]),0) - self.assertEquals(sum([42]),42) - self.assertEquals(sum([1,2,3]),6) - self.assertEquals(sum([],5),5) - self.assertEquals(sum([1,2,3],4),10) + assert sum([]) ==0 + assert sum([42]) ==42 + assert sum([1,2,3]) ==6 + assert sum([],5) ==5 + assert sum([1,2,3],4) ==10 def test_type_selftest(self): - self.assert_(type(type) is type) + assert type(type) is type def test_iter_sequence(self): - self.assertRaises(TypeError,iter,3) + raises(TypeError,iter,3) x = iter(['a','b','c']) - self.assertEquals(x.next(),'a') - self.assertEquals(x.next(),'b') - self.assertEquals(x.next(),'c') - self.assertRaises(StopIteration,x.next) + assert x.next() =='a' + assert x.next() =='b' + assert x.next() =='c' + raises(StopIteration,x.next) def test_iter___iter__(self): # This test assumes that dict.keys() method returns keys in @@ -99,7 +95,7 @@ # it tests 4 calls to __iter__() in one assert. It could # be modified if better granularity on the assert is required. mydict = {'a':1,'b':2,'c':3} - self.assertEquals(list(iter(mydict)),mydict.keys()) + assert list(iter(mydict)) ==mydict.keys() def test_iter_callable_sentinel(self): class count(object): @@ -114,97 +110,99 @@ #self.assertRaises(TypeError,iter,[],5) #self.assertRaises(TypeError,iter,{},5) x = iter(count(),3) - self.assertEquals(x.next(),1) - self.assertEquals(x.next(),2) - self.assertRaises(StopIteration,x.next) + assert x.next() ==1 + assert x.next() ==2 + raises(StopIteration,x.next) def test_enumerate(self): seq = range(2,4) enum = enumerate(seq) - self.assertEquals(enum.next(), (0, 2)) - self.assertEquals(enum.next(), (1, 3)) - self.assertRaises(StopIteration, enum.next) + assert enum.next() == (0, 2) + assert enum.next() == (1, 3) + raises(StopIteration, enum.next) def test_xrange_args(self): x = xrange(2) - self.assertEquals(x.start, 0) - self.assertEquals(x.stop, 2) - self.assertEquals(x.step, 1) + assert x.start == 0 + assert x.stop == 2 + assert x.step == 1 x = xrange(2,10,2) - self.assertEquals(x.start, 2) - self.assertEquals(x.stop, 10) - self.assertEquals(x.step, 2) + assert x.start == 2 + assert x.stop == 10 + assert x.step == 2 - self.assertRaises(ValueError, xrange, 0, 1, 0) + raises(ValueError, xrange, 0, 1, 0) def test_xrange_up(self): x = xrange(2) - self.assertEquals(x.start, 0) - self.assertEquals(x.stop, 2) - self.assertEquals(x.step, 1) + assert x.start == 0 + assert x.stop == 2 + assert x.step == 1 iter_x = iter(x) - self.assertEquals(iter_x.next(), 0) - self.assertEquals(iter_x.next(), 1) - self.assertRaises(StopIteration, iter_x.next) + assert iter_x.next() == 0 + assert iter_x.next() == 1 + raises(StopIteration, iter_x.next) def test_xrange_down(self): x = xrange(4,2,-1) iter_x = iter(x) - self.assertEquals(iter_x.next(), 4) - self.assertEquals(iter_x.next(), 3) - self.assertRaises(StopIteration, iter_x.next) + assert iter_x.next() == 4 + assert iter_x.next() == 3 + raises(StopIteration, iter_x.next) def test_xrange_has_type_identity(self): - self.assertEquals(type(xrange(1)), type(xrange(1))) + assert type(xrange(1)) == type(xrange(1)) def test_xrange_len(self): x = xrange(33) - self.assertEquals(len(x), 33) + assert len(x) == 33 x = xrange(33,0,-1) - self.assertEquals(len(x), 33) + assert len(x) == 33 x = xrange(33,0) - self.assertEquals(len(x), 0) + assert len(x) == 0 x = xrange(0,33) - self.assertEquals(len(x), 33) + assert len(x) == 33 x = xrange(0,33,-1) - self.assertEquals(len(x), 0) + assert len(x) == 0 x = xrange(0,33,2) - self.assertEquals(len(x), 17) + assert len(x) == 17 x = xrange(0,32,2) - self.assertEquals(len(x), 16) + assert len(x) == 16 def test_xrange_indexing(self): x = xrange(0,33,2) - self.assertEquals(x[7], 14) - self.assertEquals(x[-7], 20) - self.assertRaises(IndexError, x.__getitem__, 17) - self.assertRaises(IndexError, x.__getitem__, -18) - self.assertRaises(TypeError, x.__getitem__, slice(0,3,1)) + assert x[7] == 14 + assert x[-7] == 20 + raises(IndexError, x.__getitem__, 17) + raises(IndexError, x.__getitem__, -18) + raises(TypeError, x.__getitem__, slice(0,3,1)) def test_cmp(self): - self.assertEquals(cmp(9,9), 0) - self.assert_(cmp(0,9) < 0) - self.assert_(cmp(9,0) > 0) + assert cmp(9,9) == 0 + assert cmp(0,9) < 0 + assert cmp(9,0) > 0 def test_return_None(self): - self.assertEquals(setattr(self, 'x', 11), None) - self.assertEquals(delattr(self, 'x'), None) + class X: pass + x = X() + assert setattr(x, 'x', 11) == None + assert delattr(x, 'x') == None # To make this test, we need autopath to work in application space. #self.assertEquals(execfile('emptyfile.py'), None) def test_divmod(self): - self.assertEquals(divmod(15,10),(1,5)) + assert divmod(15,10) ==(1,5) def test_callable(self): class Call: def __call__(self, a): return a+2 - self.failIf(not callable(Call()), + assert not not callable(Call()), ( "Builtin function 'callable' misreads callable object") - self.assert_(callable(int), + assert callable(int), ( "Builtin function 'callable' misreads int") def test_uncallable(self): @@ -215,55 +213,55 @@ class NoCall(object): pass a = NoCall() - self.failIf(callable(a), + assert not callable(a), ( "Builtin function 'callable' misreads uncallable object") a.__call__ = lambda: "foo" - self.failIf(callable(a), + assert not callable(a), ( "Builtin function 'callable' tricked by instance-__call__") def test_hash(self): - self.assertEquals(hash(23), hash(23)) - self.assertEquals(hash(2.3), hash(2.3)) - self.assertEquals(hash('23'), hash("23")) - self.assertEquals(hash((23,)), hash((23,))) - self.assertNotEquals(hash(22), hash(23)) - self.assertRaises(TypeError, hash, []) - self.assertRaises(TypeError, hash, {}) + assert hash(23) == hash(23) + assert hash(2.3) == hash(2.3) + assert hash('23') == hash("23") + assert hash((23,)) == hash((23,)) + assert hash(22) != hash(23) + raises(TypeError, hash, []) + raises(TypeError, hash, {}) def test_compile(self): co = compile('1+2', '?', 'eval') - self.assertEquals(eval(co), 3) - self.assertRaises(SyntaxError, compile, '-', '?', 'eval') - self.assertRaises(ValueError, compile, '"\\xt"', '?', 'eval') - self.assertRaises(ValueError, compile, '1+2', '?', 'maybenot') - self.assertRaises(TypeError, compile, '1+2', 12, 34) + assert eval(co) == 3 + raises(SyntaxError, compile, '-', '?', 'eval') + raises(ValueError, compile, '"\\xt"', '?', 'eval') + raises(ValueError, compile, '1+2', '?', 'maybenot') + raises(TypeError, compile, '1+2', 12, 34) def test_isinstance(self): - self.assert_(isinstance(5, int)) - self.assert_(isinstance(5, object)) - self.assert_(not isinstance(5, float)) - self.assert_(isinstance(True, (int, float))) - self.assert_(not isinstance(True, (type, float))) - self.assert_(isinstance(True, ((type, float), bool))) - self.assertRaises(TypeError, isinstance, 5, 6) - self.assertRaises(TypeError, isinstance, 5, (float, 6)) + assert isinstance(5, int) + assert isinstance(5, object) + assert not isinstance(5, float) + assert isinstance(True, (int, float)) + assert not isinstance(True, (type, float)) + assert isinstance(True, ((type, float), bool)) + raises(TypeError, isinstance, 5, 6) + raises(TypeError, isinstance, 5, (float, 6)) def test_issubclass(self): - self.assert_(issubclass(int, int)) - self.assert_(issubclass(int, object)) - self.assert_(not issubclass(int, float)) - self.assert_(issubclass(bool, (int, float))) - self.assert_(not issubclass(bool, (type, float))) - self.assert_(issubclass(bool, ((type, float), bool))) - self.assertRaises(TypeError, issubclass, 5, int) - self.assertRaises(TypeError, issubclass, int, 6) - self.assertRaises(TypeError, issubclass, int, (float, 6)) + assert issubclass(int, int) + assert issubclass(int, object) + assert not issubclass(int, float) + assert issubclass(bool, (int, float)) + assert not issubclass(bool, (type, float)) + assert issubclass(bool, ((type, float), bool)) + raises(TypeError, issubclass, 5, int) + raises(TypeError, issubclass, int, 6) + raises(TypeError, issubclass, int, (float, 6)) -class TestInternal(testit.IntTestCase): +class TestInternal: - def setUp(self): - self.space = space = testit.objspace() + def setup_method(self,method): + space = self.space def get_builtin(self, name): w = self.space.wrap @@ -286,11 +284,7 @@ self.space.call_function(w_execfile, space.wrap(fn), w_dict, space.w_None) w_value = space.getitem(w_dict, space.wrap('i')) - self.assertEqual_w(w_value, space.wrap(42)) + assert self.space.eq_w(w_value, space.wrap(42)) finally: import os os.remove(fn) - -if __name__ == '__main__': - testit.main() - Modified: pypy/branch/src-pytest/pypy/module/test/test_filter.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_filter.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_filter.py Sat Jan 8 18:34:22 2005 @@ -1,41 +1,37 @@ import autopath -from pypy.tool import testit # trivial functions for testing -class TestFilter(testit.AppTestCase): +class AppTestFilter: def test_filter_no_arguments(self): - self.assertRaises(TypeError, filter) + raises(TypeError, filter) def test_filter_no_function_no_seq(self): - self.assertRaises(TypeError, filter, None) + raises(TypeError, filter, None) def test_filter_function_no_seq(self): - self.assertRaises(TypeError, filter, lambda x: x>3) + raises(TypeError, filter, lambda x: x>3) def test_filter_function_too_many_args(self): - self.assertRaises(TypeError, filter, lambda x: x>3, [1], [2]) + raises(TypeError, filter, lambda x: x>3, [1], [2]) def test_filter_no_function_list(self): - self.assertEqual(filter(None, [1, 2, 3]), [1, 2, 3]) + assert filter(None, [1, 2, 3]) == [1, 2, 3] def test_filter_no_function_tuple(self): - self.assertEqual(filter(None, (1, 2, 3)), (1, 2, 3)) + assert filter(None, (1, 2, 3)) == (1, 2, 3) def test_filter_no_function_string(self): - self.assertEqual(filter(None, 'mystring'), 'mystring') + assert filter(None, 'mystring') == 'mystring' def test_filter_no_function_with_bools(self): - self.assertEqual(filter(None, (True, False, True)), (True, True)) + assert filter(None, (True, False, True)) == (True, True) def test_filter_list(self): - self.assertEqual(filter(lambda x: x>3, [1, 2, 3, 4, 5]), [4, 5]) + assert filter(lambda x: x>3, [1, 2, 3, 4, 5]) == [4, 5] def test_filter_tuple(self): - self.assertEqual(filter(lambda x: x>3, (1, 2, 3, 4, 5)), (4, 5)) + assert filter(lambda x: x>3, (1, 2, 3, 4, 5)) == (4, 5) def test_filter_string(self): - self.assertEqual(filter(lambda x: x>'a', 'xyzabcd'), 'xyzbcd') - -if __name__ == '__main__': - testit.main() + assert filter(lambda x: x>'a', 'xyzabcd') == 'xyzbcd' Modified: pypy/branch/src-pytest/pypy/module/test/test_functional.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_functional.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_functional.py Sat Jan 8 18:34:22 2005 @@ -1,97 +1,91 @@ import autopath -from pypy.tool import testit -class TestMap(testit.AppTestCase): +class AppTestMap: def test_trivial_map_one_seq(self): - self.assertEqual(map(lambda x: x+2, [1, 2, 3, 4]), [3, 4, 5, 6]) + assert map(lambda x: x+2, [1, 2, 3, 4]) == [3, 4, 5, 6] def test_trivial_map_two_seq(self): - self.assertEqual(map(lambda x,y: x+y, - [1, 2, 3, 4],[1, 2, 3, 4]), + assert map(lambda x,y: x+y, + [1, 2, 3, 4],[1, 2, 3, 4]) == ( [2, 4, 6, 8]) def test_trivial_map_sizes_dont_match_and_should(self): - self.assertRaises(TypeError, map, lambda x,y: x+y, [1, 2, 3, 4], [1, 2, 3]) + raises(TypeError, map, lambda x,y: x+y, [1, 2, 3, 4], [1, 2, 3]) def test_trivial_map_no_arguments(self): - self.assertRaises(TypeError, map) + raises(TypeError, map) def test_trivial_map_no_function_no_seq(self): - self.assertRaises(TypeError, map, None) + raises(TypeError, map, None) def test_trivial_map_no_fuction_one_seq(self): - self.assertEqual(map(None, [1, 2, 3]), [1, 2, 3]) + assert map(None, [1, 2, 3]) == [1, 2, 3] def test_trivial_map_no_function(self): - self.assertEqual(map(None, [1,2,3], [4,5,6], [7,8], [1]), + assert map(None, [1,2,3], [4,5,6], [7,8], [1]) == ( [(1, 4, 7, 1), (2, 5, 8, None), (3, 6, None, None)]) def test_map_identity1(self): a = ['1', 2, 3, 'b', None] b = a[:] - self.assertEqual(map(lambda x: x, a), a) - self.assertEqual(a, b) + assert map(lambda x: x, a) == a + assert a == b def test_map_None(self): a = ['1', 2, 3, 'b', None] b = a[:] - self.assertEqual(map(None, a), a) - self.assertEqual(a, b) + assert map(None, a) == a + assert a == b def test_map_badoperation(self): a = ['1', 2, 3, 'b', None] - self.assertRaises(TypeError, map, lambda x: x+1, a) + raises(TypeError, map, lambda x: x+1, a) def test_map_multiply_identity(self): a = ['1', 2, 3, 'b', None] b = [ 2, 3, 4, 5, 6] - self.assertEqual(map(None, a, b), [('1', 2), (2, 3), (3, 4), ('b', 5), (None, 6)]) + assert map(None, a, b) == [('1', 2), (2, 3), (3, 4), ('b', 5), (None, 6)] def test_map_multiply(self): a = [1, 2, 3, 4] b = [0, 1, 1, 1] - self.assertEqual(map(lambda x, y: x+y, a, b), [1, 2, 4, 5]) + assert map(lambda x, y: x+y, a, b) == [1, 2, 4, 5] def test_map_multiply(self): a = [1, 2, 3, 4, 5] b = [] - self.assertEqual(map(lambda x, y: x, a, b), a) + assert map(lambda x, y: x, a, b) == a -class TestZip(testit.AppTestCase): +class AppTestZip: def test_one_list(self): - self.assertEqual(zip([1,2,3]), [(1,), (2,), (3,)]) + assert zip([1,2,3]) == [(1,), (2,), (3,)] def test_three_lists(self): - self.assertEqual(zip([1,2,3], [1,2], [1,2,3]), [(1,1,1), (2,2,2)]) + assert zip([1,2,3], [1,2], [1,2,3]) == [(1,1,1), (2,2,2)] -class TestReduce(testit.TestCase): +class AppTestReduce: def test_None(self): - self.assertRaises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) + raises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) def test_sum(self): - self.assertEqual(reduce(lambda x, y: x+y, [1,2,3,4], 0), 10) - self.assertEqual(reduce(lambda x, y: x+y, [1,2,3,4]), 10) + assert reduce(lambda x, y: x+y, [1,2,3,4], 0) == 10 + assert reduce(lambda x, y: x+y, [1,2,3,4]) == 10 def test_minus(self): - self.assertEqual(reduce(lambda x, y: x-y, [10, 2, 8]), 0) - self.assertEqual(reduce(lambda x, y: x-y, [2, 8], 10), 0) + assert reduce(lambda x, y: x-y, [10, 2, 8]) == 0 + assert reduce(lambda x, y: x-y, [2, 8], 10) == 0 -class TestFilter(testit.AppTestCase): +class AppTestFilter: def test_None(self): - self.assertEqual(filter(None, ['a', 'b', 1, 0, None]), ['a', 'b', 1]) + assert filter(None, ['a', 'b', 1, 0, None]) == ['a', 'b', 1] def test_return_type(self): txt = "This is a test text" - self.assertEqual(filter(None, txt), txt) + assert filter(None, txt) == txt tup = ("a", None, 0, [], 1) - self.assertEqual(filter(None, tup), ("a", 1)) + assert filter(None, tup) == ("a", 1) def test_function(self): - self.assertEqual(filter(lambda x: x != "a", "a small text"), " smll text") - -if __name__ == '__main__': - testit.main() - - + assert filter(lambda x: x != "a", "a small text") == " smll text" Modified: pypy/branch/src-pytest/pypy/module/test/test_import.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_import.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_import.py Sat Jan 8 18:34:22 2005 @@ -1,5 +1,4 @@ import autopath -from pypy.tool import testit from pypy.interpreter import gateway import os @@ -19,19 +18,18 @@ _teardown = gateway.app2interp_temp(_teardown,'teardown') -class TestImport(testit.AppTestCase): +class AppTestImport: - def setUp(self): # interpreter-level - testit.AppTestCase.setUp(self) - self.saved_modules = _setup(self.space) + def setup_class(cls): # interpreter-level + cls.saved_modules = _setup(cls.space) - def tearDown(self): # interpreter-level - _teardown(self.space,self.saved_modules) + def teardown_class(cls): # interpreter-level + _teardown(cls.space,cls.saved_modules) def test_import_bare_dir_fails(self): def imp(): import notapackage - self.assertRaises(ImportError,imp) + raises(ImportError,imp) def test_import_sys(self): import sys @@ -39,112 +37,108 @@ def test_import_a(self): import sys import a - self.assertEquals(a, sys.modules.get('a')) + assert a == sys.modules.get('a') def test_import_a_cache(self): import sys import a a0 = a import a - self.assertEquals(a, a0) + assert a == a0 def test_import_pkg(self): import sys import pkg - self.assertEquals(pkg, sys.modules.get('pkg')) + assert pkg == sys.modules.get('pkg') def test_import_dotted(self): import sys import pkg.a - self.assertEquals(pkg, sys.modules.get('pkg')) - self.assertEquals(pkg.a, sys.modules.get('pkg.a')) + assert pkg == sys.modules.get('pkg') + assert pkg.a == sys.modules.get('pkg.a') def test_import_dotted_cache(self): import sys import pkg.a - self.assertEquals(pkg, sys.modules.get('pkg')) - self.assertEquals(pkg.a, sys.modules.get('pkg.a')) + assert pkg == sys.modules.get('pkg') + assert pkg.a == sys.modules.get('pkg.a') pkg0 = pkg pkg_a0 = pkg.a import pkg.a - self.assertEquals(pkg, pkg0) - self.assertEquals(pkg.a, pkg_a0) + assert pkg == pkg0 + assert pkg.a == pkg_a0 def test_import_dotted2(self): import sys import pkg.pkg1.a - self.assertEquals(pkg, sys.modules.get('pkg')) - self.assertEquals(pkg.pkg1, sys.modules.get('pkg.pkg1')) - self.assertEquals(pkg.pkg1.a, sys.modules.get('pkg.pkg1.a')) + assert pkg == sys.modules.get('pkg') + assert pkg.pkg1 == sys.modules.get('pkg.pkg1') + assert pkg.pkg1.a == sys.modules.get('pkg.pkg1.a') def test_import_ambig(self): import sys import ambig - self.assertEquals(ambig, sys.modules.get('ambig')) - self.assert_(hasattr(ambig,'imapackage')) + assert ambig == sys.modules.get('ambig') + assert hasattr(ambig,'imapackage') def test_from_a(self): import sys from a import imamodule - self.assert_('a' in sys.modules) - self.assertEquals(imamodule, 1) + assert 'a' in sys.modules + assert imamodule == 1 def test_from_dotted(self): import sys from pkg.a import imamodule - self.assert_('pkg' in sys.modules) - self.assert_('pkg.a' in sys.modules) - self.assertEquals(imamodule, 1) + assert 'pkg' in sys.modules + assert 'pkg.a' in sys.modules + assert imamodule == 1 def test_from_pkg_import_module(self): import sys from pkg import a - self.assert_('pkg' in sys.modules) - self.assert_('pkg.a' in sys.modules) + assert 'pkg' in sys.modules + assert 'pkg.a' in sys.modules pkg = sys.modules.get('pkg') - self.assertEquals(a, pkg.a) + assert a == pkg.a aa = sys.modules.get('pkg.a') - self.assertEquals(a, aa) + assert a == aa def test_import_relative(self): from pkg import relative_a - self.assertEquals(relative_a.a.inpackage,1) + assert relative_a.a.inpackage ==1 def test_import_relative_back_to_absolute(self): from pkg import abs_b - self.assertEquals(abs_b.b.inpackage,0) + assert abs_b.b.inpackage ==0 import sys - self.assertEquals(sys.modules.get('pkg.b'),None) + assert sys.modules.get('pkg.b') ==None def test_import_pkg_relative(self): import pkg_relative_a - self.assertEquals(pkg_relative_a.a.inpackage,1) + assert pkg_relative_a.a.inpackage ==1 def test_import_relative_partial_success(self): def imp(): import pkg_r.inpkg - self.assertRaises(ImportError,imp) + raises(ImportError,imp) def test_import_Globals_Are_None(self): import sys m = __import__('sys') - self.assertEquals(sys, m) + assert sys == m n = __import__('sys', None, None, ['']) - self.assertEquals(sys, n) + assert sys == n def test_import_relative_back_to_absolute2(self): from pkg import abs_x_y import sys - self.assertEquals(abs_x_y.x.__name__,'x') - self.assertEquals(abs_x_y.x.y.__name__,'x.y') + assert abs_x_y.x.__name__ =='x' + assert abs_x_y.x.y.__name__ =='x.y' # grrr XXX not needed probably... #self.assertEquals(sys.modules.get('pkg.x'),None) #self.assert_('pkg.x.y' not in sys.modules) def test_substituting_import(self): from pkg_substituting import mod - self.assertEquals(mod.__name__,'pkg_substituting.mod') - - -if __name__ == '__main__': - testit.main() + assert mod.__name__ =='pkg_substituting.mod' Modified: pypy/branch/src-pytest/pypy/module/test/test_minmax.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_minmax.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_minmax.py Sat Jan 8 18:34:22 2005 @@ -1,71 +1,67 @@ import autopath -from pypy.tool import testit -class TestMin(testit.AppTestCase): +class AppTestMin: def test_min_notseq(self): - self.assertRaises(TypeError, min, 1) + raises(TypeError, min, 1) def test_min_usual(self): - self.assertEqual(min(1, 2, 3), 1) + assert min(1, 2, 3) == 1 def test_min_floats(self): - self.assertEqual(min(0.1, 2.7, 14.7), 0.1) + assert min(0.1, 2.7, 14.7) == 0.1 # write fixed point if that becomes a type. def test_min_chars(self): - self.assertEqual(min('a', 'b', 'c'), 'a') + assert min('a', 'b', 'c') == 'a' # write a unicode test when unicode works. def test_min_strings(self): - self.assertEqual(min('aaa', 'bbb', 'c'), 'aaa') + assert min('aaa', 'bbb', 'c') == 'aaa' # write an imaginary test when we have complex numbers # XXX we have no mixed comparison operator yet on StdObjSpace def _test_min_mixed(self): - self.assertEqual(min('1', 2, 3, 'aa'), 2) + assert min('1', 2, 3, 'aa') == 2 def test_min_noargs(self): - self.assertRaises(TypeError, min) + raises(TypeError, min) def test_min_empty(self): - self.assertRaises(ValueError, min, []) + raises(ValueError, min, []) -class TestMax(testit.AppTestCase): +class AppTestMax: def test_max_notseq(self): - self.assertRaises(TypeError, max, 1) + raises(TypeError, max, 1) def test_max_usual(self): - self.assertEqual(max(1, 2, 3), 3) + assert max(1, 2, 3) == 3 def test_max_floats(self): - self.assertEqual(max(0.1, 2.7, 14.7), 14.7) + assert max(0.1, 2.7, 14.7) == 14.7 # write fixed point if that becomes a type. def test_max_chars(self): - self.assertEqual(max('a', 'b', 'c'), 'c') + assert max('a', 'b', 'c') == 'c' # write a unicode test when unicode works. def test_max_strings(self): - self.assertEqual(max('aaa', 'bbb', 'c'), 'c') + assert max('aaa', 'bbb', 'c') == 'c' # write an imaginary test when we have complex numbers # XXX we have no mixed comparison operator yet on StdObjSpace def _test_max_mixed(self): - self.assertEqual(max('1', 2, 3, 'aa'), 'aa') + assert max('1', 2, 3, 'aa') == 'aa' def test_max_noargs(self): - self.assertRaises(TypeError, max) + raises(TypeError, max) def test_max_empty(self): - self.assertRaises(ValueError, max, []) - -if __name__ == '__main__': - testit.main() + raises(ValueError, max, []) Modified: pypy/branch/src-pytest/pypy/module/test/test_newstyleclasses.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_newstyleclasses.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_newstyleclasses.py Sat Jan 8 18:34:22 2005 @@ -1,11 +1,7 @@ import autopath -from pypy.tool import testit - -class TestBuiltinApp(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace() +class AppTestBuiltinApp: def test_staticmethod(self): class C: def f(a, b): @@ -16,10 +12,10 @@ c = C() d = D() - self.assertEquals(c.f("abc", "def"), "abcdef") - self.assertEquals(C.f("abc", "def"), "abcdef") - self.assertEquals(d.f("abc", "def"), "abcdef") - self.assertEquals(D.f("abc", "def"), "abcdef") + assert c.f("abc", "def") == "abcdef" + assert C.f("abc", "def") == "abcdef" + assert d.f("abc", "def") == "abcdef" + assert D.f("abc", "def") == "abcdef" def test_classmethod(self): class C: @@ -31,10 +27,10 @@ c = C() d = D() - self.assertEquals(c.f("abc"), (C, "abc")) - self.assertEquals(C.f("abc"), (C, "abc")) - self.assertEquals(d.f("abc"), (D, "abc")) - self.assertEquals(D.f("abc"), (D, "abc")) + assert c.f("abc") == (C, "abc") + assert C.f("abc") == (C, "abc") + assert d.f("abc") == (D, "abc") + assert D.f("abc") == (D, "abc") def test_property_simple(self): @@ -44,9 +40,9 @@ def _del(self): raise KeyError name = property(_get, _set, _del) a1 = a() - self.assertEquals(a1.name, 42) - self.assertRaises(AttributeError, setattr, a1, 'name', 42) - self.assertRaises(KeyError, delattr, a1, 'name') + assert a1.name == 42 + raises(AttributeError, setattr, a1, 'name', 42) + raises(KeyError, delattr, a1, 'name') def test_super(self): class A(object): @@ -62,17 +58,14 @@ def f(self): return 'D' + super(D,self).f() d = D() - self.assertEquals(d.f(), "DBCA") - self.assertEquals(D.__mro__, (D, B, C, A, object)) + assert d.f() == "DBCA" + assert D.__mro__ == (D, B, C, A, object) def test_super_metaclass(self): class xtype(type): def __init__(self, name, bases, dict): super(xtype, self).__init__(name, bases, dict) A = xtype('A', (), {}) - self.assert_(isinstance(A, xtype)) + assert isinstance(A, xtype) a = A() - self.assert_(isinstance(a, A)) - -if __name__ == '__main__': - testit.main() + assert isinstance(a, A) Modified: pypy/branch/src-pytest/pypy/module/test/test_range.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_range.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_range.py Sat Jan 8 18:34:22 2005 @@ -1,73 +1,67 @@ import autopath -from pypy.tool import testit -class TestRange(testit.AppTestCase): +class AppTestRange: def test_range_toofew(self): - self.assertRaises(TypeError, range) + raises(TypeError, range) def test_range_toomany(self): - self.assertRaises(TypeError, range, 1, 2, 3, 4) + raises(TypeError, range, 1, 2, 3, 4) def test_range_one(self): - self.assertEqual(range(1), [0]) + assert range(1) == [0] def test_range_posstartisstop(self): - self.assertEqual(range(1, 1), []) + assert range(1, 1) == [] def test_range_negstartisstop(self): - self.assertEqual(range(-1, -1), []) + assert range(-1, -1) == [] def test_range_zero(self): - self.assertEqual(range(0), []) + assert range(0) == [] def test_range_twoargs(self): - self.assertEqual(range(1, 2), [1]) + assert range(1, 2) == [1] def test_range_decreasingtwoargs(self): - self.assertEqual(range(3, 1), []) + assert range(3, 1) == [] def test_range_negatives(self): - self.assertEqual(range(-3), []) + assert range(-3) == [] def test_range_decreasing_negativestep(self): - self.assertEqual(range(5, -2, -1), [5, 4, 3, 2, 1, 0 , -1]) + assert range(5, -2, -1) == [5, 4, 3, 2, 1, 0 , -1] def test_range_posfencepost1(self): - self.assertEqual(range (1, 10, 3), [1, 4, 7]) + assert range (1, 10, 3) == [1, 4, 7] def test_range_posfencepost2(self): - self.assertEqual(range (1, 11, 3), [1, 4, 7, 10]) + assert range (1, 11, 3) == [1, 4, 7, 10] def test_range_posfencepost3(self): - self.assertEqual(range (1, 12, 3), [1, 4, 7, 10]) + assert range (1, 12, 3) == [1, 4, 7, 10] def test_range_negfencepost1(self): - self.assertEqual(range (-1, -10, -3), [-1, -4, -7]) + assert range (-1, -10, -3) == [-1, -4, -7] def test_range_negfencepost2(self): - self.assertEqual(range (-1, -11, -3), [-1, -4, -7, -10]) + assert range (-1, -11, -3) == [-1, -4, -7, -10] def test_range_negfencepost3(self): - self.assertEqual(range (-1, -12, -3), [-1, -4, -7, -10]) + assert range (-1, -12, -3) == [-1, -4, -7, -10] def test_range_decreasing_negativelargestep(self): - self.assertEqual(range(5, -2, -3), [5, 2, -1]) + assert range(5, -2, -3) == [5, 2, -1] def test_range_increasing_positivelargestep(self): - self.assertEqual(range(-5, 2, 3), [-5, -2, 1]) + assert range(-5, 2, 3) == [-5, -2, 1] def test_range_zerostep(self): - self.assertRaises(ValueError, range, 1, 5, 0) + raises(ValueError, range, 1, 5, 0) """ def test_range_float(self): "How CPython does it - UGLY, ignored for now." - self.assertEqual(range(0.1, 2.0, 1.1), [0, 1]) + assert range(0.1, 2.0, 1.1) == [0, 1] """ - -if __name__ == '__main__': - testit.main() - - Modified: pypy/branch/src-pytest/pypy/module/test/test_reduce.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_reduce.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_reduce.py Sat Jan 8 18:34:22 2005 @@ -1,19 +1,13 @@ import autopath -from pypy.tool import testit -class TestReduce(testit.AppTestCase): +class AppTestReduce: def test_None(self): - self.assertRaises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) + raises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) def test_sum(self): - self.assertEqual(reduce(lambda x, y: x+y, [1,2,3,4], 0), 10) - self.assertEqual(reduce(lambda x, y: x+y, [1,2,3,4]), 10) + assert reduce(lambda x, y: x+y, [1,2,3,4], 0) == 10 + assert reduce(lambda x, y: x+y, [1,2,3,4]) == 10 def test_minus(self): - self.assertEqual(reduce(lambda x, y: x-y, [10, 2, 8]), 0) - self.assertEqual(reduce(lambda x, y: x-y, [2, 8], 10), 0) - -if __name__ == '__main__': - testit.main() - - + assert reduce(lambda x, y: x-y, [10, 2, 8]) == 0 + assert reduce(lambda x, y: x-y, [2, 8], 10) == 0 Modified: pypy/branch/src-pytest/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_sysmodule.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_sysmodule.py Sat Jan 8 18:34:22 2005 @@ -1,68 +1,63 @@ import autopath -from pypy.tool import testit -class SysTests(testit.TestCase): - def setUp(self): - self.space = testit.objspace() +class TestSysTests: + def setup_method(self,method): self.sys_w = self.space.get_builtin_module("sys") - def tearDown(self): - pass - def test_stdout_exists(self): s = self.space - self.failUnless_w(s.getattr(self.sys_w, s.wrap("stdout"))) + assert s.is_true(s.getattr(self.sys_w, s.wrap("stdout"))) -class AppSysTests(testit.AppTestCase): +class AppTestAppSysTests: def test_path_exists(self): import sys - self.failUnless(hasattr(sys, 'path'), "sys.path gone missing") + assert hasattr(sys, 'path'), "sys.path gone missing" def test_modules_exists(self): import sys - self.failUnless(hasattr(sys, 'modules'), "sys.modules gone missing") + assert hasattr(sys, 'modules'), "sys.modules gone missing" def test_dict_exists(self): import sys - self.failUnless(hasattr(sys, '__dict__'), "sys.__dict__ gone missing") + assert hasattr(sys, '__dict__'), "sys.__dict__ gone missing" def test_name_exists(self): import sys - self.failUnless(hasattr(sys, '__name__'), "sys.__name__ gone missing") + assert hasattr(sys, '__name__'), "sys.__name__ gone missing" def test_builtin_module_names_exists(self): import sys - self.failUnless(hasattr(sys, 'builtin_module_names'), + assert hasattr(sys, 'builtin_module_names'), ( "sys.builtin_module_names gone missing") def test_warnoptions_exists(self): import sys - self.failUnless(hasattr(sys, 'warnoptions'), + assert hasattr(sys, 'warnoptions'), ( "sys.warnoptions gone missing") def test_hexversion_exists(self): import sys - self.failUnless(hasattr(sys, 'hexversion'), + assert hasattr(sys, 'hexversion'), ( "sys.hexversion gone missing") def test_platform_exists(self): import sys - self.failUnless(hasattr(sys, 'platform'), "sys.platform gone missing") + assert hasattr(sys, 'platform'), "sys.platform gone missing" def test_sys_in_modules(self): import sys modules = sys.modules - self.failUnless('sys' in modules, "An entry for sys " + assert 'sys' in modules, ( "An entry for sys " "is not in sys.modules.") sys2 = sys.modules['sys'] - self.failUnless(sys is sys2, "import sys is not sys.modules[sys].") + assert sys is sys2, "import sys is not sys.modules[sys]." def test_builtin_in_modules(self): import sys modules = sys.modules - self.failUnless('__builtin__' in modules, "An entry for __builtin__ " + assert '__builtin__' in modules, ( "An entry for __builtin__ " "is not in sys.modules.") import __builtin__ builtin2 = sys.modules['__builtin__'] - self.failUnless(__builtin__ is builtin2, "import __builtin__ " + assert __builtin__ is builtin2, ( "import __builtin__ " "is not sys.modules[__builtin__].") def test_builtin_module_names(self): import sys names = sys.builtin_module_names - self.failUnless('sys' in names, + assert 'sys' in names, ( "sys is not listed as a builtin module.") - self.failUnless('__builtin__' in names, + assert '__builtin__' in names, ( "__builtin__ is not listed as a builtin module.") def test_sys_exc_info(self): @@ -75,11 +70,11 @@ raise Exception # 5 lines below the previous one except Exception,e2: exc_type2,exc_val2,tb2 = sys.exc_info() - self.assertEquals(exc_type,Exception) - self.assertEquals(exc_val,e) - self.assertEquals(exc_type2,Exception) - self.assertEquals(exc_val2,e2) - self.assertEquals(tb2.tb_lineno - tb.tb_lineno, 5) + assert exc_type ==Exception + assert exc_val ==e + assert exc_type2 ==Exception + assert exc_val2 ==e2 + assert tb2.tb_lineno - tb.tb_lineno == 5 def test_exc_info_normalization(self): import sys @@ -87,10 +82,6 @@ 1/0 except ZeroDivisionError: etype, val, tb = sys.exc_info() - self.assert_(isinstance(val, etype)) + assert isinstance(val, etype) else: - self.fail("ZeroDivisionError not caught") - -if __name__ == '__main__': - testit.main() - + raise AssertionError, "ZeroDivisionError not caught" Modified: pypy/branch/src-pytest/pypy/module/test/test_vars.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_vars.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_vars.py Sat Jan 8 18:34:22 2005 @@ -1,24 +1,18 @@ import autopath -from pypy.tool import testit -class TestVars(testit.AppTestCase): +class AppTestVars: def _test_vars_no_arguments(self): - self.assertEqual(vars(), locals()) + assert vars() == locals() def _test_vars_too_many_arguments(self): - self.assertRaises(TypeError, vars, 0, 1) + raises(TypeError, vars, 0, 1) def _test_vars_correct_arguments(self): class a: def __init__(self): self.res = 42 - self.assertEqual(vars(a), a.__dict__) + assert vars(a) == a.__dict__ a1 = a() - self.assertEqual(vars(a1), a1.__dict__) - self.assertEqual(vars(a1).get('res'),42) - -if __name__ == '__main__': - testit.main() - - + assert vars(a1) == a1.__dict__ + assert vars(a1).get('res') ==42 Modified: pypy/branch/src-pytest/pypy/module/test/test_zip.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_zip.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_zip.py Sat Jan 8 18:34:22 2005 @@ -1,37 +1,31 @@ import autopath -from pypy.tool import testit -class TestZip(testit.AppTestCase): +class AppTestZip: def test_zip_no_arguments(self): - self.assertRaises(TypeError, zip) + raises(TypeError, zip) def test_one_list(self): - self.assertEqual(zip([1, 2, 3]), [(1,), (2,), (3,)]) + assert zip([1, 2, 3]) == [(1,), (2,), (3,)] def test_three_lists_same_size(self): - self.assertEqual(zip([1, 2, 3], [3, 4, 5], [6, 7, 8]), + assert zip([1, 2, 3], [3, 4, 5], [6, 7, 8]) == ( [(1, 3, 6), (2, 4, 7), (3, 5, 8)]) def test_three_lists_different_sizes(self): - self.assertEqual(zip([1, 2], [3, 4, 5, 6], [6, 7, 8]), + assert zip([1, 2], [3, 4, 5, 6], [6, 7, 8]) == ( [(1, 3, 6), (2, 4, 7)]) def test_tuples(self): - self.assertEqual(zip((1, 2, 3)), [(1,), (2,), (3,)]) + assert zip((1, 2, 3)) == [(1,), (2,), (3,)] def test_string(self): - self.assertEqual(zip('hello'), [('h',), ('e',), ('l',), ('l',), ('o',)]) + assert zip('hello') == [('h',), ('e',), ('l',), ('l',), ('o',)] def test_strings(self): - self.assertEqual(zip('hello', 'bye'), + assert zip('hello', 'bye') == ( [('h', 'b'), ('e', 'y'), ('l', 'e')]) def test_mixed_types(self): - self.assertEqual(zip('hello', [1,2,3,4], (7,8,9,10)), + assert zip('hello', [1,2,3,4], (7,8,9,10)) == ( [('h', 1, 7), ('e', 2, 8), ('l', 3, 9), ('l', 4, 10)]) - -if __name__ == '__main__': - testit.main() - - From pedronis at codespeak.net Sat Jan 8 18:36:07 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 18:36:07 +0100 (MET) Subject: [pypy-svn] r8174 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050108173607.1B44327B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 18:36:06 2005 New Revision: 8174 Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py pypy/branch/src-pytest/pypy/tool/utestconvert.py Log: - improved fiximport, should be able to deal with most of ours setUp, tearDown - added more PyPy stuff to utestconvert: assertEqual_w --This line, and those below, will be ignored-- M tool/utestconvert.py M tool/fiximport.py Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/fiximport.py (original) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Sat Jan 8 18:36:06 2005 @@ -1,12 +1,92 @@ import sys +import re +import parser +blank_re=re.compile(r"\s*(#.*)?") +def get_indent(line): + indent = re.match(blank_re,line).group() + return indent, indent==line + +def read_whole_suite(intro_line): + base_indent, dummy = get_indent(intro_line) + lines = [] + cont = [] + parsing_prefix = "" + if len(base_indent) > 0: + parsing_prefix = "if 0:\n" + while True: + line = f.readline() + if not line: + break + indent, isblank = get_indent(line) + if isblank: + pass + elif cont: + cont.append(line) + try: + parser.suite(parsing_prefix+''.join(cont)) + except SyntaxError: + pass + else: + cont = [] + else: + if len(indent) <= len(base_indent): + pushback.append(line) + break + try: + parser.suite(parsing_prefix+line) + except SyntaxError: + cont = [line] + lines.append(line) + + return base_indent,lines + +pass_re = re.compile(r"^\s*pass\s*$") +getobjspace_re = r"testit\.objspace\((.*)\)" +setspace_re = r"self\.space\s*=\s*" + +def up_down_port(lines): + npass = 0 + nblank = 0 + objspace = None + n = -1 + for line in lines: + n += 1 + dummy, isblank = get_indent(line) + if isblank: + nblank += 1 + continue + if re.match(pass_re, line): + npass += 1 + continue + m = re.search(getobjspace_re, line) + if m: + objspace = m.group(1) + line = line[:m.start()]+"self.space"+line[m.end():] + line = re.sub(setspace_re,"",line) + if line.strip() == "self.space": + line = "" + nblank += 1 + lines[n] = line + + skip = npass+nblank == len(lines) + + return objspace,skip + for fn in sys.argv[1:]: print fn lines = [] + pushback = [] + kind = None f = file(fn, 'r') + + confused = False while True: - line = f.readline() + if pushback: + line = pushback.pop() + else: + line = f.readline() if not line: break rline = line.rstrip() @@ -17,11 +97,30 @@ tail = f.read() if tail.strip() != 'testit.main()': print ' * uncommon __main__ lines at the end' + confused = True break if line.strip() == 'def setUp(self):': - print ' * setUp() ignored' + base_indent,suite = read_whole_suite(line) + objspace,skip = up_down_port(suite) + #print suite + if objspace: + lines.append(base_indent+"objspacename = %s\n" % objspace) + lines.append("\n") + if not skip: + lines.append(base_indent+"def setup_method(self,method):\n") + lines.extend(suite) + continue if line.strip() == 'def tearDown(self):': - print ' * tearDown() ignored' + base_indent, suite = read_whole_suite(line) + unexpected,skip = up_down_port(suite) + if unexpected is not None: + print "* testit.objspace() in tearDown" + confused = True + #print suite + if not skip: + lines.append(base_indent+"def teardown_method(self,method):\n") + lines.extend(suite) + continue if line.startswith('class '): rest = line[6:].strip() if rest.endswith('(testit.AppTestCase):'): @@ -30,14 +129,17 @@ if not rest.startswith('Test'): rest = 'Test'+rest rest = 'App'+rest + kind = 'app-test' elif rest.endswith('(testit.IntTestCase):'): rest = rest[:-21].strip() + ':' if not rest.startswith('Test'): rest = 'Test'+rest + kind = 'test' elif rest.endswith('(testit.TestCase):'): rest = rest[:-18].strip() + ':' if not rest.startswith('Test'): rest = 'Test'+rest + kind = 'test' else: print ' * ignored class', rest line = 'class ' + rest + '\n' @@ -46,7 +148,11 @@ while lines and not lines[-1].strip(): del lines[-1] - - f = file(fn, 'w') - f.writelines(lines) - f.close() + + if confused: + print "** confused: file not changed" + else: + #sys.stdout.writelines(lines) + f = file(fn, 'w') + f.writelines(lines) + f.close() Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/utestconvert.py (original) +++ pypy/branch/src-pytest/pypy/tool/utestconvert.py Sat Jan 8 18:36:06 2005 @@ -23,7 +23,9 @@ d['failIfAlmostEqual'] = ('assert not round', ' ==', [2,3,4]) d['assertNotAlmostEqual'] = ('assert round', ' !=', [2,3,4]) d['failUnlessAlmostEquals'] = ('assert not round', ' !=', [2,3,4]) +# PyPy specific d['assertRaises_w'] = ('self.raises_w', '', ['Any']) +d['assertEqual_w'] = ('assert self.space.eq_w','',['Any']) # the list of synonyms d['failUnlessRaises'] = d['assertRaises'] From arigo at codespeak.net Sat Jan 8 18:47:34 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 8 Jan 2005 18:47:34 +0100 (MET) Subject: [pypy-svn] r8175 - pypy/branch/src-pytest/pypy Message-ID: <20050108174734.AEE9427B71@code1.codespeak.net> Author: arigo Date: Sat Jan 8 18:47:34 2005 New Revision: 8175 Modified: pypy/branch/src-pytest/pypy/conftest.py Log: fixed a bogus __import__(). Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 18:47:34 2005 @@ -90,7 +90,7 @@ def setup_class(self, cls): name = getattr(cls, 'objspacename', None) if name is None: - m = __import__(cls.__module__) + m = __import__(cls.__module__, {}, {}, ["objspacename"]) name = getattr(m, 'objspacename', None) cls.space = gettestobjspace(name) super(PyPyItem, self).setup_class(cls) From pedronis at codespeak.net Sat Jan 8 19:09:58 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 19:09:58 +0100 (MET) Subject: [pypy-svn] r8176 - pypy/branch/src-pytest/pypy/objspace/test Message-ID: <20050108180958.DF71527B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 19:09:58 2005 New Revision: 8176 Modified: pypy/branch/src-pytest/pypy/objspace/test/test_descriptor.py pypy/branch/src-pytest/pypy/objspace/test/test_traceobjspace.py Log: converted objspace/test tests Modified: pypy/branch/src-pytest/pypy/objspace/test/test_descriptor.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/test/test_descriptor.py (original) +++ pypy/branch/src-pytest/pypy/objspace/test/test_descriptor.py Sat Jan 8 19:09:58 2005 @@ -1,29 +1,25 @@ import autopath -from pypy.tool import testit -class Test_Descriptor(testit.AppTestCase): +class AppTest_Descriptor: def test_non_data_descr(self): class X(object): def f(self): return 42 x = X() - self.assertEquals(x.f(), 42) + assert x.f() == 42 x.f = 43 - self.assertEquals(x.f, 43) + assert x.f == 43 del x.f - self.assertEquals(x.f(), 42) + assert x.f() == 42 def test_member(self): import sys - self.assertEquals(sys.stdin.softspace, 0) - self.assertEquals(file.softspace.__get__(sys.stdin), 0) + assert sys.stdin.softspace == 0 + assert file.softspace.__get__(sys.stdin) == 0 sys.stdin.softspace = 1 - self.assertEquals(sys.stdin.softspace, 1) + assert sys.stdin.softspace == 1 file.softspace.__set__(sys.stdin, 0) - self.assertEquals(sys.stdin.softspace, 0) - self.assertRaises(TypeError, delattr, sys.stdin, 'softspace') - self.assertRaises(TypeError, file.softspace.__delete__, sys.stdin) - -if __name__ == '__main__': - testit.main() + assert sys.stdin.softspace == 0 + raises(TypeError, delattr, sys.stdin, 'softspace') + raises(TypeError, file.softspace.__delete__, sys.stdin) Modified: pypy/branch/src-pytest/pypy/objspace/test/test_traceobjspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/test/test_traceobjspace.py (original) +++ pypy/branch/src-pytest/pypy/objspace/test/test_traceobjspace.py Sat Jan 8 19:09:58 2005 @@ -1,16 +1,14 @@ import autopath -from pypy.tool import testit from pypy.objspace import trace from pypy.tool import pydis from pypy.interpreter import gateway -class Test_TraceObjSpace(testit.IntTestCase): +class Test_TraceObjSpace: - def setUp(self): - self.space = testit.objspace() + def setup_method(self,method): trace.create_trace_space(self.space) - def tearDown(self): + def teardown_method(self,method): self.space.reset_trace() def perform_trace(self, app_func): @@ -24,7 +22,7 @@ def test_traceobjspace_basic(self): tspace = self.space - self.assert_(tspace.is_true(tspace.w_builtins)) + assert tspace.is_true(tspace.w_builtins) #for name, value in vars(self.space).items(): # if not name.startswith('_'): # self.assert_(value is getattr(t, name)) @@ -35,21 +33,21 @@ pass res = self.perform_trace(app_f) disresult = pydis.pydis(app_f) - self.assertEquals(disresult.bytecodes, list(res.getbytecodes())) + assert disresult.bytecodes == list(res.getbytecodes()) def test_some_builtin1(self): def app_f(): len([1,2,3,4,5]) res = self.perform_trace(app_f) disresult = pydis.pydis(app_f) - self.assertEquals(len(disresult.bytecodes), len(list(res.getbytecodes()))) + assert len(disresult.bytecodes) == len(list(res.getbytecodes())) def test_some_builtin2(self): def app_f(): filter(None, []) # filter implemented in appspace -> has many more bytecodes res = self.perform_trace(app_f) disresult = pydis.pydis(app_f) - self.failUnless(len(disresult.bytecodes) < len(list(res.getbytecodes()))) + assert len(disresult.bytecodes) < len(list(res.getbytecodes())) def get_operation(self, iter, optype, name): for op in iter: @@ -66,9 +64,6 @@ ops = res.getoperations() op_start = self.get_operation(ops, trace.CallBegin, "add") args = [uw(x) for x in op_start.callinfo.args] - self.assertEquals(args, [1, 1]) + assert args == [1, 1] op_end = self.get_operation(ops, trace.CallFinished, "add") - self.assertEquals(uw(op_end.res), 2) - -if __name__ == '__main__': - testit.main() + assert uw(op_end.res) == 2 From pedronis at codespeak.net Sat Jan 8 20:06:17 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 20:06:17 +0100 (MET) Subject: [pypy-svn] r8177 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050108190617.A335027B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 20:06:17 2005 New Revision: 8177 Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py Log: now fiximport can be used as fiximport [-o] ... a proper objspacename = will be added at module level, and self.space=testit.objspace() forms removed or reported as problematic as appropriate. Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/fiximport.py (original) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Sat Jan 8 20:06:17 2005 @@ -73,14 +73,29 @@ skip = npass+nblank == len(lines) return objspace,skip + + +# option -o let you pick a default objspace wich will be enforced +# trough a module global objspacename = + +default_objspace = None + +if sys.argv[1].startswith('-o'): + default_objspace = sys.argv[1][2:] + files = sys.argv[2:] +else: + files = sys.argv[1:] + +print "-- default-objspace: %s" % default_objspace -for fn in sys.argv[1:]: +for fn in files: print fn lines = [] pushback = [] kind = None f = file(fn, 'r') + global_objspacename = False confused = False while True: if pushback: @@ -99,13 +114,23 @@ print ' * uncommon __main__ lines at the end' confused = True break + if default_objspace and not global_objspacename and (line.startswith('def ') or line.startswith('class ')): + lines.extend(["objspacename = %r\n" % default_objspace,"\n"]) + global_objspacename = True + if line.strip() == 'def setUp(self):': base_indent,suite = read_whole_suite(line) objspace,skip = up_down_port(suite) #print suite if objspace: - lines.append(base_indent+"objspacename = %s\n" % objspace) - lines.append("\n") + if default_objspace: + if eval(objspace) != default_objspace: + print "* default objspace mismatch: %s" % objspace + confused = True + continue + else: + lines.append(base_indent+"objspacename = %s\n" % objspace) + lines.append("\n") if not skip: lines.append(base_indent+"def setup_method(self,method):\n") lines.extend(suite) From pedronis at codespeak.net Sat Jan 8 20:08:49 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 20:08:49 +0100 (MET) Subject: [pypy-svn] r8178 - in pypy/branch/src-pytest/pypy: . objspace/flow/test Message-ID: <20050108190849.67D2427B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 20:08:49 2005 New Revision: 8178 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/objspace/flow/test/test_framestate.py pypy/branch/src-pytest/pypy/objspace/flow/test/test_model.py pypy/branch/src-pytest/pypy/objspace/flow/test/test_objspace.py Log: ported objspace/flow/test tests added logic to conftest.py that will not try for flow object space to enable app-level tests support which is not meaningful. Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sat Jan 8 20:08:49 2005 @@ -33,14 +33,15 @@ module = __import__("pypy.objspace.%s" % name, None, None, ["Space"]) space = module.Space() _spacecache[name] = space - space.setitem(space.w_builtins, space.wrap('AssertionError'), - pytestsupport.build_pytest_assertion(space)) - space.setitem(space.w_builtins, space.wrap('raises'), - space.wrap(pytestsupport.app_raises)) - space.setitem(space.w_builtins, space.wrap('skip'), - space.wrap(pytestsupport.app_skip)) - space.raises_w = pytestsupport.raises_w.__get__(space) - space.eq_w = pytestsupport.eq_w.__get__(space) + if name != 'flow': # not sensible for flow objspace case + space.setitem(space.w_builtins, space.wrap('AssertionError'), + pytestsupport.build_pytest_assertion(space)) + space.setitem(space.w_builtins, space.wrap('raises'), + space.wrap(pytestsupport.app_raises)) + space.setitem(space.w_builtins, space.wrap('skip'), + space.wrap(pytestsupport.app_skip)) + space.raises_w = pytestsupport.raises_w.__get__(space) + space.eq_w = pytestsupport.eq_w.__get__(space) return space # Modified: pypy/branch/src-pytest/pypy/objspace/flow/test/test_framestate.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/flow/test/test_framestate.py (original) +++ pypy/branch/src-pytest/pypy/objspace/flow/test/test_framestate.py Sat Jan 8 20:08:49 2005 @@ -1,15 +1,13 @@ import autopath -from pypy.tool import testit from pypy.objspace.flow.flowcontext import * from pypy.objspace.flow.model import * from pypy.interpreter.pycode import PyCode -class TestFrameState(testit.TestCase): - def setUp(self): - self.space = testit.objspace('flow') +objspacename = 'flow' +class TestFrameState: def getframe(self, func): space = self.space try: @@ -37,47 +35,47 @@ frame = self.getframe(self.func_simple) fs1 = FrameState(frame) fs2 = FrameState(frame) - self.assertEquals(fs1, fs2) + assert fs1 == fs2 def test_neq_hacked_framestate(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) frame.fastlocals_w[-1] = Variable() fs2 = FrameState(frame) - self.assertNotEquals(fs1, fs2) + assert fs1 != fs2 def test_union_on_equal_framestates(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) fs2 = FrameState(frame) - self.assertEquals(fs1.union(fs2), fs1) + assert fs1.union(fs2) == fs1 def test_union_on_hacked_framestates(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) frame.fastlocals_w[-1] = Variable() fs2 = FrameState(frame) - self.assertEquals(fs1.union(fs2), fs2) # fs2 is more general - self.assertEquals(fs2.union(fs1), fs2) # fs2 is more general + assert fs1.union(fs2) == fs2 # fs2 is more general + assert fs2.union(fs1) == fs2 # fs2 is more general def test_restore_frame(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) frame.fastlocals_w[-1] = Variable() fs1.restoreframe(frame) - self.assertEquals(fs1, FrameState(frame)) + assert fs1 == FrameState(frame) def test_copy(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) fs2 = fs1.copy() - self.assertEquals(fs1, fs2) + assert fs1 == fs2 def test_getvariables(self): frame = self.getframe(self.func_simple) fs1 = FrameState(frame) vars = fs1.getvariables() - self.assertEquals(len(vars), 1) + assert len(vars) == 1 def test_getoutputargs(self): frame = self.getframe(self.func_simple) @@ -87,7 +85,7 @@ outputargs = fs1.getoutputargs(fs2) # 'x' -> 'x' is a Variable # fastlocals_w[-1] -> fastlocals_w[-1] is Constant(None) - self.assertEquals(outputargs, [frame.fastlocals_w[0], Constant(None)]) + assert outputargs == [frame.fastlocals_w[0], Constant(None)] def test_union_different_constants(self): frame = self.getframe(self.func_simple) @@ -96,14 +94,4 @@ fs2 = FrameState(frame) fs3 = fs1.union(fs2) fs3.restoreframe(frame) - self.assert_(isinstance(frame.fastlocals_w[-1], Variable)) # generalized - -if __name__ == '__main__': - testit.main() - - - - - - - + assert isinstance(frame.fastlocals_w[-1], Variable) # generalized Modified: pypy/branch/src-pytest/pypy/objspace/flow/test/test_model.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/flow/test/test_model.py (original) +++ pypy/branch/src-pytest/pypy/objspace/flow/test/test_model.py Sat Jan 8 20:08:49 2005 @@ -1,12 +1,10 @@ import autopath -from pypy.tool import testit from pypy.objspace.flow.model import * -class TestModel(testit.TestCase): - def setUp(self): - self.space = testit.objspace('flow') +objspacename = 'flow' +class TestModel: def getflow(self, func): import inspect try: @@ -24,7 +22,7 @@ graph = self.getflow(self.simplefunc) l = flatten(graph) #print l - self.assertEquals(len(l), 4) + assert len(l) == 4 def test_class(self): graph = self.getflow(self.simplefunc) @@ -43,10 +41,10 @@ v = MyVisitor() traverse(v, graph) - self.assertEquals(len(v.blocks), 2) - self.assertEquals(len(v.links), 1) - self.assertEquals(v.graph, graph) - self.assertEquals(v.links[0], graph.startblock.exits[0]) + assert len(v.blocks) == 2 + assert len(v.links) == 1 + assert v.graph == graph + assert v.links[0] == graph.startblock.exits[0] def test_partial_class(self): graph = self.getflow(self.simplefunc) @@ -65,10 +63,10 @@ v = MyVisitor() traverse(v, graph) - self.assertEquals(len(v.blocks), 2) - self.assertEquals(len(v.links), 1) - self.assertEquals(v.graph, graph) - self.assertEquals(v.links[0], graph.startblock.exits[0]) + assert len(v.blocks) == 2 + assert len(v.links) == 1 + assert v.graph == graph + assert v.links[0] == graph.startblock.exits[0] def loop(x): x = abs(x) @@ -78,8 +76,4 @@ def test_loop(self): graph = self.getflow(self.simplefunc) l = flatten(graph) - self.assertEquals(len(l), 4) - - -if __name__ == '__main__': - testit.main() + assert len(l) == 4 Modified: pypy/branch/src-pytest/pypy/objspace/flow/test/test_objspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/flow/test/test_objspace.py (original) +++ pypy/branch/src-pytest/pypy/objspace/flow/test/test_objspace.py Sat Jan 8 20:08:49 2005 @@ -1,13 +1,11 @@ import autopath -from pypy.tool import testit from pypy.objspace.flow.model import Constant from pypy.interpreter.argument import Arguments -class TestFlowObjSpace(testit.TestCase): - def setUp(self): - self.space = testit.objspace('flow') +objspacename = 'flow' +class TestFlowObjSpace: def codetest(self, func): import inspect try: @@ -35,9 +33,9 @@ def test_nothing(self): x = self.codetest(self.nothing) - self.assertEquals(len(x.startblock.exits), 1) + assert len(x.startblock.exits) == 1 link, = x.startblock.exits - self.assertEquals(link.target, x.returnblock) + assert link.target == x.returnblock self.show(x) #__________________________________________________________ @@ -340,19 +338,16 @@ def test_specialcases(self): x = self.codetest(self.specialcases) - self.assertEquals(len(x.startblock.operations), 13) + assert len(x.startblock.operations) == 13 for op in x.startblock.operations: - self.assert_(op.opname in ['lt', 'le', 'eq', 'ne', - 'gt', 'ge', 'is_']) - self.assertEquals(len(op.args), 2) - self.assertEquals(op.args[0].value, 2) - self.assertEquals(op.args[1].value, 3) + assert op.opname in ['lt', 'le', 'eq', 'ne', + 'gt', 'ge', 'is_'] + assert len(op.args) == 2 + assert op.args[0].value == 2 + assert op.args[1].value == 3 DATA = {'x': 5, 'y': 6} def user_defined_function(): pass - -if __name__ == '__main__': - testit.main() From pedronis at codespeak.net Sat Jan 8 20:09:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 8 Jan 2005 20:09:47 +0100 (MET) Subject: [pypy-svn] r8179 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050108190947.1D45727B71@code1.codespeak.net> Author: pedronis Date: Sat Jan 8 20:09:46 2005 New Revision: 8179 Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py Log: typo. Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/fiximport.py (original) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Sat Jan 8 20:09:46 2005 @@ -75,7 +75,7 @@ return objspace,skip -# option -o let you pick a default objspace wich will be enforced +# option -o let you pick a default objspace which will be enforced # trough a module global objspacename = default_objspace = None From arigo at codespeak.net Sun Jan 9 15:28:17 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 9 Jan 2005 15:28:17 +0100 (MET) Subject: [pypy-svn] r8180 - pypy/branch/src-pytest/pypy Message-ID: <20050109142817.2B2F927B75@code1.codespeak.net> Author: arigo Date: Sun Jan 9 15:28:16 2005 New Revision: 8180 Modified: pypy/branch/src-pytest/pypy/conftest.py Log: Removed tabs in source. Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Sun Jan 9 15:28:16 2005 @@ -33,14 +33,14 @@ module = __import__("pypy.objspace.%s" % name, None, None, ["Space"]) space = module.Space() _spacecache[name] = space - if name != 'flow': # not sensible for flow objspace case - space.setitem(space.w_builtins, space.wrap('AssertionError'), + if name != 'flow': # not sensible for flow objspace case + space.setitem(space.w_builtins, space.wrap('AssertionError'), pytestsupport.build_pytest_assertion(space)) space.setitem(space.w_builtins, space.wrap('raises'), space.wrap(pytestsupport.app_raises)) space.setitem(space.w_builtins, space.wrap('skip'), space.wrap(pytestsupport.app_skip)) - space.raises_w = pytestsupport.raises_w.__get__(space) + space.raises_w = pytestsupport.raises_w.__get__(space) space.eq_w = pytestsupport.eq_w.__get__(space) return space From pedronis at codespeak.net Sun Jan 9 16:14:33 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sun, 9 Jan 2005 16:14:33 +0100 (MET) Subject: [pypy-svn] r8181 - in pypy/branch/src-pytest/pypy: module/test tool Message-ID: <20050109151433.C60DC27B80@code1.codespeak.net> Author: pedronis Date: Sun Jan 9 16:14:33 2005 New Revision: 8181 Modified: pypy/branch/src-pytest/pypy/module/test/test_builtin.py pypy/branch/src-pytest/pypy/module/test/test_import.py pypy/branch/src-pytest/pypy/tool/fiximport.py Log: oops, sorry, my Emacs on the my laptop was unexpectedly misconfigured and was using evil TABs Modified: pypy/branch/src-pytest/pypy/module/test/test_builtin.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_builtin.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_builtin.py Sun Jan 9 16:14:33 2005 @@ -38,7 +38,7 @@ return locals() assert f() == {} assert g() == {'a':0, 'b':0, 'c':0} - + def test_dir(self): def f(): return dir() @@ -62,9 +62,9 @@ return vars() assert f() == {} assert g() == {'a':0, 'b':0, 'c':0} - + def test_getattr(self): - class a: + class a: i = 5 assert getattr(a, 'i') == 5 raises(AttributeError, getattr, a, 'k') @@ -76,7 +76,7 @@ assert sum([1,2,3]) ==6 assert sum([],5) ==5 assert sum([1,2,3],4) ==10 - + def test_type_selftest(self): assert type(type) is type @@ -104,7 +104,7 @@ def __call__(self): self.value += 1 return self.value - # XXX Raising errors is quite slow -- + # XXX Raising errors is quite slow -- # uncomment these lines when fixed #self.assertRaises(TypeError,iter,3,5) #self.assertRaises(TypeError,iter,[],5) @@ -113,14 +113,14 @@ assert x.next() ==1 assert x.next() ==2 raises(StopIteration,x.next) - + def test_enumerate(self): seq = range(2,4) enum = enumerate(seq) assert enum.next() == (0, 2) assert enum.next() == (1, 3) raises(StopIteration, enum.next) - + def test_xrange_args(self): x = xrange(2) assert x.start == 0 @@ -132,7 +132,7 @@ assert x.stop == 10 assert x.step == 2 - raises(ValueError, xrange, 0, 1, 0) + raises(ValueError, xrange, 0, 1, 0) def test_xrange_up(self): x = xrange(2) @@ -186,8 +186,8 @@ assert cmp(9,0) > 0 def test_return_None(self): - class X: pass - x = X() + class X: pass + x = X() assert setattr(x, 'x', 11) == None assert delattr(x, 'x') == None # To make this test, we need autopath to work in application space. @@ -206,7 +206,7 @@ "Builtin function 'callable' misreads int") def test_uncallable(self): - # XXX TODO: I made the NoCall class explicitly newstyle to try and + # XXX TODO: I made the NoCall class explicitly newstyle to try and # remedy the failure in this test observed when running this with # the trivial objectspace, but the test _still_ fails then (it # doesn't fail with the standard objectspace, though). @@ -216,7 +216,7 @@ assert not callable(a), ( "Builtin function 'callable' misreads uncallable object") a.__call__ = lambda: "foo" - assert not callable(a), ( + assert not callable(a), ( "Builtin function 'callable' tricked by instance-__call__") def test_hash(self): @@ -257,7 +257,7 @@ raises(TypeError, issubclass, int, 6) raises(TypeError, issubclass, int, (float, 6)) - + class TestInternal: def setup_method(self,method): @@ -268,9 +268,9 @@ w_builtins = self.space.w_builtins w_obj = self.space.getitem(w_builtins, w(name)) return w_obj - + def test_execfile(self): - # we need cpython's tempfile currently to test + # we need cpython's tempfile currently to test from tempfile import mktemp fn = mktemp() f = open(fn, 'w') Modified: pypy/branch/src-pytest/pypy/module/test/test_import.py ============================================================================== --- pypy/branch/src-pytest/pypy/module/test/test_import.py (original) +++ pypy/branch/src-pytest/pypy/module/test/test_import.py Sun Jan 9 16:14:33 2005 @@ -21,14 +21,14 @@ class AppTestImport: def setup_class(cls): # interpreter-level - cls.saved_modules = _setup(cls.space) + cls.saved_modules = _setup(cls.space) def teardown_class(cls): # interpreter-level - _teardown(cls.space,cls.saved_modules) + _teardown(cls.space,cls.saved_modules) def test_import_bare_dir_fails(self): def imp(): - import notapackage + import notapackage raises(ImportError,imp) def test_import_sys(self): @@ -126,9 +126,9 @@ def test_import_Globals_Are_None(self): import sys m = __import__('sys') - assert sys == m + assert sys == m n = __import__('sys', None, None, ['']) - assert sys == n + assert sys == n def test_import_relative_back_to_absolute2(self): from pkg import abs_x_y @@ -138,7 +138,7 @@ # grrr XXX not needed probably... #self.assertEquals(sys.modules.get('pkg.x'),None) #self.assert_('pkg.x.y' not in sys.modules) - + def test_substituting_import(self): from pkg_substituting import mod assert mod.__name__ =='pkg_substituting.mod' Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/fiximport.py (original) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Sun Jan 9 16:14:33 2005 @@ -14,31 +14,31 @@ cont = [] parsing_prefix = "" if len(base_indent) > 0: - parsing_prefix = "if 0:\n" + parsing_prefix = "if 0:\n" while True: - line = f.readline() - if not line: - break - indent, isblank = get_indent(line) + line = f.readline() + if not line: + break + indent, isblank = get_indent(line) if isblank: - pass + pass elif cont: - cont.append(line) - try: - parser.suite(parsing_prefix+''.join(cont)) - except SyntaxError: - pass - else: - cont = [] + cont.append(line) + try: + parser.suite(parsing_prefix+''.join(cont)) + except SyntaxError: + pass + else: + cont = [] else: - if len(indent) <= len(base_indent): - pushback.append(line) - break - try: - parser.suite(parsing_prefix+line) - except SyntaxError: - cont = [line] - lines.append(line) + if len(indent) <= len(base_indent): + pushback.append(line) + break + try: + parser.suite(parsing_prefix+line) + except SyntaxError: + cont = [line] + lines.append(line) return base_indent,lines @@ -53,22 +53,22 @@ n = -1 for line in lines: n += 1 - dummy, isblank = get_indent(line) - if isblank: - nblank += 1 - continue - if re.match(pass_re, line): - npass += 1 - continue - m = re.search(getobjspace_re, line) - if m: - objspace = m.group(1) - line = line[:m.start()]+"self.space"+line[m.end():] - line = re.sub(setspace_re,"",line) - if line.strip() == "self.space": - line = "" - nblank += 1 - lines[n] = line + dummy, isblank = get_indent(line) + if isblank: + nblank += 1 + continue + if re.match(pass_re, line): + npass += 1 + continue + m = re.search(getobjspace_re, line) + if m: + objspace = m.group(1) + line = line[:m.start()]+"self.space"+line[m.end():] + line = re.sub(setspace_re,"",line) + if line.strip() == "self.space": + line = "" + nblank += 1 + lines[n] = line skip = npass+nblank == len(lines) @@ -76,7 +76,7 @@ # option -o let you pick a default objspace which will be enforced -# trough a module global objspacename = +# trough a module global objspacename = default_objspace = None @@ -87,7 +87,7 @@ files = sys.argv[1:] print "-- default-objspace: %s" % default_objspace - + for fn in files: print fn lines = [] @@ -99,9 +99,9 @@ confused = False while True: if pushback: - line = pushback.pop() - else: - line = f.readline() + line = pushback.pop() + else: + line = f.readline() if not line: break rline = line.rstrip() @@ -112,40 +112,40 @@ tail = f.read() if tail.strip() != 'testit.main()': print ' * uncommon __main__ lines at the end' - confused = True + confused = True break - if default_objspace and not global_objspacename and (line.startswith('def ') or line.startswith('class ')): - lines.extend(["objspacename = %r\n" % default_objspace,"\n"]) - global_objspacename = True + if default_objspace and not global_objspacename and (line.startswith('def ') or line.startswith('class ')): + lines.extend(["objspacename = %r\n" % default_objspace,"\n"]) + global_objspacename = True if line.strip() == 'def setUp(self):': base_indent,suite = read_whole_suite(line) - objspace,skip = up_down_port(suite) - #print suite - if objspace: - if default_objspace: - if eval(objspace) != default_objspace: - print "* default objspace mismatch: %s" % objspace - confused = True - continue - else: - lines.append(base_indent+"objspacename = %s\n" % objspace) - lines.append("\n") - if not skip: - lines.append(base_indent+"def setup_method(self,method):\n") - lines.extend(suite) - continue + objspace,skip = up_down_port(suite) + #print suite + if objspace: + if default_objspace: + if eval(objspace) != default_objspace: + print "* default objspace mismatch: %s" % objspace + confused = True + continue + else: + lines.append(base_indent+"objspacename = %s\n" % objspace) + lines.append("\n") + if not skip: + lines.append(base_indent+"def setup_method(self,method):\n") + lines.extend(suite) + continue if line.strip() == 'def tearDown(self):': base_indent, suite = read_whole_suite(line) unexpected,skip = up_down_port(suite) - if unexpected is not None: - print "* testit.objspace() in tearDown" - confused = True - #print suite - if not skip: - lines.append(base_indent+"def teardown_method(self,method):\n") - lines.extend(suite) - continue + if unexpected is not None: + print "* testit.objspace() in tearDown" + confused = True + #print suite + if not skip: + lines.append(base_indent+"def teardown_method(self,method):\n") + lines.extend(suite) + continue if line.startswith('class '): rest = line[6:].strip() if rest.endswith('(testit.AppTestCase):'): @@ -154,7 +154,7 @@ if not rest.startswith('Test'): rest = 'Test'+rest rest = 'App'+rest - kind = 'app-test' + kind = 'app-test' elif rest.endswith('(testit.IntTestCase):'): rest = rest[:-21].strip() + ':' if not rest.startswith('Test'): @@ -173,11 +173,11 @@ while lines and not lines[-1].strip(): del lines[-1] - - if confused: - print "** confused: file not changed" + + if confused: + print "** confused: file not changed" else: - #sys.stdout.writelines(lines) - f = file(fn, 'w') - f.writelines(lines) - f.close() + #sys.stdout.writelines(lines) + f = file(fn, 'w') + f.writelines(lines) + f.close() From pedronis at codespeak.net Sun Jan 9 19:04:27 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sun, 9 Jan 2005 19:04:27 +0100 (MET) Subject: [pypy-svn] r8186 - pypy/branch/src-pytest/pypy/objspace/std/test Message-ID: <20050109180427.975D027B75@code1.codespeak.net> Author: pedronis Date: Sun Jan 9 19:04:27 2005 New Revision: 8186 Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_floatobject.py Log: ported test_floatobject.py using utestconvert and fiximport. will look at the others objspace/std/test tomorrow. Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_floatobject.py Sun Jan 9 19:04:27 2005 @@ -1,16 +1,11 @@ import autopath from pypy.objspace.std import floatobject as fobj from pypy.objspace.std.objspace import FailedToImplement -from pypy.tool import testit -class TestW_FloatObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') +class TestW_FloatObject: - def tearDown(self): - pass - def _unwrap_nonimpl(self, func, *args, **kwds): """ make sure that the expected exception occurs, and unwrap it """ try: @@ -26,7 +21,7 @@ f1 = fobj.W_FloatObject(self.space, x) f2 = fobj.W_FloatObject(self.space, y) f3 = fobj.W_FloatObject(self.space, z) - self.assertEquals(self.space.w_TypeError, + assert self.space.w_TypeError == ( self._unwrap_nonimpl(fobj.pow__Float_Float_ANY, self.space, f1, f2, f3)) @@ -36,44 +31,37 @@ f1 = fobj.W_FloatObject(self.space, x) f2 = fobj.W_FloatObject(self.space, y) v = fobj.pow__Float_Float_ANY(self.space, f1, f2, self.space.w_None) - self.assertEquals(v.floatval, x ** y) + assert v.floatval == x ** y f1 = fobj.W_FloatObject(self.space, -1.23) f2 = fobj.W_FloatObject(self.space, -4.56) - self.assertEquals(self.space.w_ValueError, + assert self.space.w_ValueError == ( self._unwrap_nonimpl(fobj.pow__Float_Float_ANY, self.space, f1, f2, self.space.w_None)) -class AppFloatTest(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') - +class AppTestAppFloatTest: def test_negatives(self): - self.assert_(-1.1 < 0) - self.assert_(-0.1 < 0) + assert -1.1 < 0 + assert -0.1 < 0 def test_float_callable(self): - self.assertEquals(0.125, float(0.125)) + assert 0.125 == float(0.125) def test_float_int(self): - self.assertEquals(42.0, float(42)) + assert 42.0 == float(42) def test_float_string(self): - self.assertEquals(42.0, float("42")) + assert 42.0 == float("42") def test_round(self): - self.assertEquals(1.0, round(1.0)) - self.assertEquals(1.0, round(1.1)) - self.assertEquals(2.0, round(1.9)) - self.assertEquals(2.0, round(1.5)) - self.assertEquals(-2.0, round(-1.5)) - self.assertEquals(-2.0, round(-1.5)) - self.assertEquals(-2.0, round(-1.5, 0)) - self.assertEquals(-2.0, round(-1.5, 0)) - self.assertEquals(22.2, round(22.222222, 1)) - self.assertEquals(20.0, round(22.22222, -1)) - self.assertEquals(0.0, round(22.22222, -2)) - -if __name__ == '__main__': - testit.main() - + assert 1.0 == round(1.0) + assert 1.0 == round(1.1) + assert 2.0 == round(1.9) + assert 2.0 == round(1.5) + assert -2.0 == round(-1.5) + assert -2.0 == round(-1.5) + assert -2.0 == round(-1.5, 0) + assert -2.0 == round(-1.5, 0) + assert 22.2 == round(22.222222, 1) + assert 20.0 == round(22.22222, -1) + assert 0.0 == round(22.22222, -2) From tismer at codespeak.net Sun Jan 9 22:49:22 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sun, 9 Jan 2005 22:49:22 +0100 (MET) Subject: [pypy-svn] r8189 - pypy/trunk/src/pypy/appspace Message-ID: <20050109214922.9FED327B75@code1.codespeak.net> Author: tismer Date: Sun Jan 9 22:49:22 2005 New Revision: 8189 Modified: pypy/trunk/src/pypy/appspace/md5.py Log: needed to set the metatypes. With old-style classes, genrpy doesn't work, yet. Modified: pypy/trunk/src/pypy/appspace/md5.py ============================================================================== --- pypy/trunk/src/pypy/appspace/md5.py (original) +++ pypy/trunk/src/pypy/appspace/md5.py Sun Jan 9 22:49:22 2005 @@ -32,6 +32,7 @@ __date__ = '2004-11-17' __version__ = 0.91 # Modernised by J. Hall?n and L. Creighton for Pypy +__metaclass__ = type # or genrpy won't work import struct, copy From tismer at codespeak.net Sun Jan 9 22:50:59 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sun, 9 Jan 2005 22:50:59 +0100 (MET) Subject: [pypy-svn] r8190 - pypy/trunk/src/pypy/translator Message-ID: <20050109215059.E165B27B75@code1.codespeak.net> Author: tismer Date: Sun Jan 9 22:50:59 2005 New Revision: 8190 Modified: pypy/trunk/src/pypy/translator/genrpy.py Log: This implementation of appspace to interp level translation seems to work quite well. There are a couple of issues, which I need to discuss on the list. Modified: pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- pypy/trunk/src/pypy/translator/genrpy.py (original) +++ pypy/trunk/src/pypy/translator/genrpy.py Sun Jan 9 22:50:59 2005 @@ -10,9 +10,10 @@ that globals are constants, for instance. This definition is not exact and might change. -This module is very much under construction and not yet usable for much -more than testing. +This module appears to be already quite usable. +But I need to ask how we want to integrate it. """ + from __future__ import generators import autopath, os, sys, exceptions from pypy.objspace.flow.model import Variable, Constant, SpaceOperation @@ -23,11 +24,12 @@ from pypy.interpreter.pycode import CO_VARARGS from pypy.annotation import model as annmodel from types import FunctionType, CodeType - +from pypy.interpreter.error import OperationError from pypy.objspace.std.restricted_int import r_int, r_uint from pypy.translator.translator import Translator from pypy.objspace.std import StdObjSpace +from pypy.objspace.flow import FlowObjSpace from pypy.interpreter.gateway import app2interp, interp2app @@ -53,7 +55,6 @@ source, ) - def ordered_blocks(graph): # collect all blocks allblocks = [] @@ -76,14 +77,28 @@ # print ofs, txt, block return [block for ofs, txt, block in allblocks] +class UniqueList(list): + def __init__(self, *args, **kwds): + list.__init__(self, *args, **kwds) + self.dic = {} + def append(self, arg): + try: + self.dic[arg] + except KeyError: + self.dic[arg] = 1 + list.append(self, arg) + except TypeError: # not hashable + if arg not in self: + list.append(self, arg) + class GenRpy: def __init__(self, f, translator, modname=None, f2=None, f2name=None): self.f = f self.f2 = f2 self.f2name = f2name self.translator = translator - self.modname = (modname or + self.modname = self.trans_funcname(modname or uniquemodulename(translator.functions[0].__name__)) self.rpynames = {Constant(None).key: 'space.w_None', Constant(False).key: 'space.w_False', @@ -91,13 +106,15 @@ } self.seennames = {} - self.initcode = [] # list of lines for the module's initxxx() - self.latercode = [] # list of generators generating extra lines + u = UniqueList + self.initcode = u() # list of lines for the module's initxxx() + self.latercode = u() # list of generators generating extra lines # for later in initxxx() -- for recursive # objects self.globaldecl = [] self.globalobjects = [] self.pendingfunctions = [] + self.currentfunc = None self.debugstack = () # linked list of nested nameof() # special constructors: @@ -105,14 +122,105 @@ for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - self.space = StdObjSpace() # for introspection - + # XXX I guess it is cleaner to use the flow space? + # we just want to look into the operations, + # but we don't break into the implementation. + # Or should it be the base space, ARMIN? + #self.space = StdObjSpace() # for introspection + self.space = FlowObjSpace() # for introspection # debugging global _gen; _gen = self self.gen_source() - def nameof(self, obj, debug=None): + def expr(self, v, localnames, wrapped = True): + if isinstance(v, Variable): + n = v.name + if n.startswith("v") and n[1:].isdigit(): + ret = localnames.get(v.name) + if not ret: + if wrapped: + localnames[v.name] = ret = "w_%d" % len(localnames) + else: + localnames[v.name] = ret = "v%d" % len(localnames) + return ret + elif isinstance(v, Constant): + return self.nameof(v.value, + debug=('Constant in the graph of', self.currentfunc)) + else: + raise TypeError, "expr(%r)" % (v,) + + def arglist(self, args, localnames): + res = [self.expr(arg, localnames) for arg in args] + return ", ".join(res) + + def oper(self, op, localnames): + if op.opname == "simple_call": + v = op.args[0] + exv = self.expr(v, localnames) + if exv.startswith("space.") and not exv.startswith("space.w_"): + # it is a space method + fmt = "%(res)s = %(func)s(%(args)s)" + else: + # default for a spacecall: + fmt = ("_tup = space.newtuple([%(args)s])\n" + "%(res)s = space.call(%(func)s, _tup)") + # see if we can optimize for a fast call. + # we justdo the very simple ones. + if isinstance(v, Constant) and exv.startswith('gfunc_'): + func = v.value + if (not func.func_code.co_flags & CO_VARARGS) and ( + func.func_defaults is None): + fmt = "%(res)s = fastf_%(func)s(space, %(args)s)" + exv = exv[6:] + return fmt % {"res" : self.expr(op.result, localnames), + "func": exv, + "args": self.arglist(op.args[1:], localnames) } + if op.opname in self.has_listarg: + fmt = "%s = %s([%s])" + else: + fmt = "%s = %s(%s)" + # specialc ase is_true + wrapped = op.opname != "is_true" + oper = "space.%s" % op.opname + return fmt % (self.expr(op.result, localnames, wrapped), oper, + self.arglist(op.args, localnames)) + + def large_assignment(self,left, right, margin=65): + expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) + pieces = expr.split(",") + res = [pieces.pop(0)] + for piece in pieces: + if len(res[-1])+len(piece)+1 > margin: + res[-1] += "," + res.append(piece) + else: + res[-1] += (","+piece) + return res + + def gen_link(self, link, localvars, blocknum, block, linklocalvars=None): + "Generate the code to jump across the given Link." + linklocalvars = linklocalvars or {} + left, right = [], [] + for a1, a2 in zip(link.args, link.target.inputargs): + if a1 in linklocalvars: + src = linklocalvars[a1] + else: + src = self.expr(a1, localvars) + left.append(self.expr(a2, localvars)) + right.append(src) + txt = "%s = %s" % (", ".join(left), ", ".join(right)) + if len(txt) <= 65: # arbitrary + yield txt + else: + for line in self.large_assignment(left, right): + yield line + goto = blocknum[link.target] + yield 'goto = %d' % goto + if goto <= blocknum[block]: + yield 'continue' + + def nameof(self, obj, debug=None, namehint=None): key = Constant(obj).key try: return self.rpynames[key] @@ -135,7 +243,12 @@ break else: raise Exception, "nameof(%r)" % (obj,) - name = meth(obj) + + code=meth.im_func.func_code + if namehint and 'namehint' in code.co_varnames[:code.co_argcount]: + name = meth(obj, namehint=namehint) + else: + name = meth(obj) self.debugstack, x = self.debugstack assert x is stackentry self.rpynames[key] = name @@ -156,7 +269,7 @@ if type(value) is not object: raise Exception, "nameof(%r) in %r" % (value, self.current_func) name = self.uniquename('g_object') - self.initcode.append('%s = object()'%name) + self.initcode.append('m.%s = object()'%name) return name def nameof_module(self, value): @@ -165,9 +278,9 @@ value.__file__.endswith('.py') or value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value - name = self.uniquename('mod%s'%value.__name__) + name = self.uniquename('mod_%s'%value.__name__) self.initcode.append('import %s as _tmp' % value.__name__) - self.initcode.append('%s = space.wrap(_tmp)' % (name)) + self.initcode.append('m.%s = space.wrap(_tmp)' % (name)) return name @@ -177,12 +290,12 @@ else: name = 'gim_%d' % abs(value) name = self.uniquename(name) - self.initcode.append('%s = space.newint(%d)' % (name, value)) + self.initcode.append('m.%s = space.newint(%d)' % (name, value)) return name def nameof_long(self, value): # allow short longs only, meaning they - # must fit into a word. + # must fit into a machine word. assert (sys.maxint*2+1)&value==value, "your literal long is too long" # assume we want them in hex most of the time if value < 256L: @@ -194,7 +307,7 @@ else: name = 'glongm_%d' % abs(value) name = self.uniquename(name) - self.initcode.append('%s = space.wrap(%s) # XXX implement long!' % (name, s)) + self.initcode.append('m.%s = space.wrap(%s) # XXX implement long!' % (name, s)) return name def nameof_float(self, value): @@ -202,7 +315,7 @@ name = (name.replace('-', 'minus') .replace('.', 'dot')) name = self.uniquename(name) - self.initcode.append('%s = space.newfloat(%r)' % (name, value)) + self.initcode.append('m.%s = space.newfloat(%r)' % (name, value)) return name def nameof_str(self, value): @@ -215,7 +328,9 @@ if not namestr: namestr = "_emptystr_" name = self.uniquename('gs_' + namestr[:32]) - self.initcode.append('%s = space.newstring(%r)' % (name, value)) + # self.initcode.append('m.%s = space.newstring(%r)' % (name, value)) + # ick! very unhandy + self.initcode.append('m.%s = space.wrap(%r)' % (name, value)) return name def skipped_function(self, func): @@ -226,9 +341,12 @@ self.initcode.append('# build func %s' % name) return name - def nameof_function(self, func): + def trans_funcname(self, s): + return s.translate(C_IDENTIFIER) + + def nameof_function(self, func, namehint=''): printable_name = '(%s:%d) %s' % ( - func.func_globals.get('__name__', '?'), + self.trans_funcname(func.func_globals.get('__name__', '?')), func.func_code.co_firstlineno, func.__name__) if self.translator.frozen: @@ -240,10 +358,11 @@ func.func_doc.lstrip().startswith('NOT_RPYTHON')): print "skipped", printable_name return self.skipped_function(func) - name = func.__name__ - name = self.uniquename('gfunc_' + func.__name__) + name = self.uniquename('gfunc_' + self.trans_funcname( + namehint + func.__name__)) f_name = 'f_' + name[6:] - self.initcode.append('%s = interp2app(%s)' % (name, f_name)) + self.initcode.append('from pypy.interpreter.gateway import interp2app') + self.initcode.append('m.%s = space.wrap(interp2app(%s))' % (name, f_name)) self.pendingfunctions.append(func) return name @@ -252,22 +371,20 @@ func = sm.__get__(42.5) name = self.uniquename('gsm_' + func.__name__) functionname = self.nameof(func) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, functionname)) + self.initcode.append('m.%s = space.wrap(%s)' % (name, functionname)) return name def nameof_instancemethod(self, meth): if meth.im_self is None: # no error checking here - return self.nameof(meth.im_func) + return self.nameof(meth.im_func, namehint="%s_" % meth.im_class.__name__) else: ob = self.nameof(meth.im_self) func = self.nameof(meth.im_func) typ = self.nameof(meth.im_class) name = self.uniquename('gmeth_'+meth.im_func.__name__) self.initcode.append( - '%s = 42# what?gencfunc_descr_get(%s, %s, %s))'%( - name, func, ob, typ)) + '%s = space.getattr(%s, %s))'%(name, ob, func)) return name def should_translate_attr(self, pbc, attr): @@ -296,8 +413,18 @@ if self.should_translate_attr(instance, key): yield 'space.setattr(%s, %s, %s)' % ( name, self.nameof(key), self.nameof(value)) - self.initcode.append('# how? INITCHK(SETUP_INSTANCE(%s, %s))' % ( - name, cls)) + if isinstance(instance, Exception): + # specialcase for exception instances: wrap them directly + self.initcode.append('_ins = %s()\n' + 'm.%s = space.wrap(_ins)' % ( + instance.__class__.__name__, name)) + else: + # this seems to hardly work with the faked stuff + self.initcode.append('import types\n' + '_ins = space.wrap(types.InstanceType)\n' + '_tup = space.newtuple([%s])\n' + 'm.%s = space.call(_ins, _tup)' % ( + cls, name)) self.later(initinstance()) return name @@ -319,15 +446,15 @@ raise Exception, '%r not found in any built-in module' % (func,) name = self.uniquename('gbltin_' + func.__name__) if modname == '__builtin__': - self.initcode.append('%s = space.getattr(space.w_builtin, %s)'% ( + self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( name, self.nameof(func.__name__))) else: - self.initcode.append('%s = space.getattr(%s, %s)' % ( + self.initcode.append('m.%s = space.getattr(%s, %s)' % ( name, self.nameof(module), self.nameof(func.__name__))) else: # builtin (bound) method name = self.uniquename('gbltinmethod_' + func.__name__) - self.initcode.append('%s = space.getattr(%s, %s)' % ( + self.initcode.append('m.%s = space.getattr(%s, %s)' % ( name, self.nameof(func.__self__), self.nameof(func.__name__))) return name @@ -338,7 +465,10 @@ metaclass = "space.w_type" if issubclass(cls, Exception): if cls.__module__ == 'exceptions': - return 'space.w_%s'%cls.__name__ + if hasattr(self.space, "w_%s" % cls.__name__): + return 'space.w_%s'%cls.__name__ + else: + return 'space.wrap(%s)' % cls.__name__ #else: # # exceptions must be old-style classes (grr!) # metaclass = "&PyClass_Type" @@ -346,7 +476,12 @@ # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - metaclass = "space.type(space.w_Exception)" + self.initcode.append("import types\n" + "m.classtype = space.wrap(types.ClassType)\n") + # metaclass = "m.classtype" + # XXX I cannot instantiate these. + # XXX using type instead, since we still inherit from excpetion + # XXX what is the future of classes in pypy? name = self.uniquename('gcls_' + cls.__name__) basenames = [self.nameof(base) for base in cls.__bases__] @@ -360,20 +495,30 @@ continue # XXX some __NAMES__ are important... nicer solution sought #raise Exception, "unexpected name %r in class %s"%(key, cls) + + # redirect value through class interface, in order to + # get methods instead of functions. + value = getattr(cls, key) + if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: - print value + print "skipped staticmethod:", value continue if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: - print value + print "skippedfunction:", value continue yield 'space.setattr(%s, %s, %s)' % ( name, self.nameof(key), self.nameof(value)) - baseargs = ", ".join([self.nameof(basename) for basename in basenames]) - self.initcode.append('%s = space.call(%s, space.newtuple(\n' - ' [%s, space.newtuple([%s]), space.newdict([])]))' - %(name, metaclass, self.nameof(cls.__name__), baseargs)) + baseargs = ", ".join(basenames) + self.initcode.append('_dic = space.newdict([])\n' + '_bases = space.newtuple([%(bases)s])\n' + '_args = space.newtuple([%(name)s, _bases, _dic])\n' + 'm.%(klass)s = space.call(%(meta)s, _args)' + % {"bases": baseargs, + "klass": name, + "name" : self.nameof(cls.__name__), + "meta" : metaclass} ) self.later(initclassobj()) return name @@ -433,7 +578,7 @@ name = self.uniquename('g%dtuple' % len(tup)) args = [self.nameof(x) for x in tup] args = ', '.join(args) - self.initcode.append('%s = space.newtuple([%s])' % (name, args)) + self.initcode.append('m.%s = space.newtuple([%s])' % (name, args)) return name def nameof_list(self, lis): @@ -443,8 +588,8 @@ item = self.nameof(lis[i]) yield 'space.setitem(%s, %s, %s);' % ( name, self.nameof(i), self.nameof(item)) - self.initcode.append('%s = space.newlist(%s)' % (name, self.nameof(0))) - self.initcode.append('%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) + self.initcode.append('m.%s = space.newlist(%s)' % (name, self.nameof(0))) + self.initcode.append('m.%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) self.later(initlist()) return name @@ -457,7 +602,7 @@ for k in dic: yield ('space.setitem(%s, %s, %s)'%( name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('%s = space.newdict([])' % (name,)) + self.initcode.append('m.%s = space.newdict([])' % (name,)) self.later(initdict()) return name @@ -468,7 +613,7 @@ md.__objclass__.__name__, md.__name__)) cls = self.nameof(md.__objclass__) # do I need to take the dict and then getitem??? - self.initcode.append('%s = space.getattr(%s, %s)' % + self.initcode.append('m.%s = space.getattr(%s, %s)' % (name, cls, self.nameof(md.__name__))) return name nameof_getset_descriptor = nameof_member_descriptor @@ -477,18 +622,19 @@ def nameof_file(self, fil): if fil is sys.stdin: - return '#XXX how: PySys_GetObject("stdin")' + return '#XXX howto: PySys_GetObject("stdin")' if fil is sys.stdout: - return '#XXX how: PySys_GetObject("stdout")' + return '#XXX howto: PySys_GetObject("stdout")' if fil is sys.stderr: - return '#XXX how: PySys_GetObject("stderr")' + return '#XXX howto: PySys_GetObject("stderr")' raise Exception, 'Cannot translate an already-open file: %r' % (fil,) def gen_source(self): f = self.f info = { 'modname': self.modname, - 'entrypointname': self.translator.functions[0].__name__, + 'entrypointname': self.trans_funcname( + self.translator.functions[0].__name__), 'entrypoint': self.nameof(self.translator.functions[0]), } # header @@ -497,6 +643,7 @@ # function implementations while self.pendingfunctions: func = self.pendingfunctions.pop() + self.current_func = func self.gen_rpyfunction(func) # collect more of the latercode after each function while self.latercode: @@ -537,7 +684,8 @@ def gen_rpyfunction(self, func): f = self.f - body = list(self.rpyfunction_body(func)) + locals = {} + body = list(self.rpyfunction_body(func, locals)) name_of_defaults = [self.nameof(x, debug=('Default argument of', func)) for x in (func.func_defaults or ())] self.gen_global_declarations() @@ -554,7 +702,7 @@ if isinstance(node, Block): localslst.extend(node.getvariables()) traverse(visit, graph) - localnames = [a.name for a in uniqueitems(localslst)] + localnames = [self.expr(a, locals) for a in uniqueitems(localslst)] # collect all the arguments if func.func_code.co_flags & CO_VARARGS: @@ -565,69 +713,45 @@ positional_args = graph.getargs() min_number_of_args = len(positional_args) - len(name_of_defaults) - fast_args = [a.name for a in positional_args] + fast_args = [self.expr(a, locals) for a in positional_args] if vararg is not None: - fast_args.append(str(vararg)) + fast_args.append(self.expr(vararg, locals)) fast_name = 'fast' + f_name fast_set = dict(zip(fast_args, fast_args)) - declare_fast_args = [('PyObject *' + a) for a in fast_args] - if declare_fast_args: - declare_fast_args = 'TRACE_ARGS ' + ', '.join(declare_fast_args) - else: - declare_fast_args = 'TRACE_ARGS_VOID' - fast_function_header = ('static PyObject *\n' - '%s(%s)' % (fast_name, declare_fast_args)) - - print >> f, fast_function_header + ';' # forward - print >> f - - print >> f, 'static PyObject *' - print >> f, '%s(PyObject* self, PyObject* args, PyObject* kwds)' % ( - f_name,) - print >> f, '{' - print >> f, '\tFUNCTION_HEAD(%s, %s, args, %s, __FILE__, __LINE__ - 2)' % ( - c_string('%s(%s)' % (cname, ', '.join(name_of_defaults))), - cname, - '(%s)' % (', '.join(map(c_string, name_of_defaults) + ['NULL']),), - ) + # create function declaration + name = func.__name__ # change this + #args = [self.expr(var, localnames) for var in fast_args] + argstr = ", ".join(fast_args) + fast_function_header = ('def %s(space, %s):' + % (fast_name, argstr)) + print >> f, 'def %s(space, *args_w):' % (f_name,) kwlist = ['"%s"' % name for name in func.func_code.co_varnames[:func.func_code.co_argcount]] - kwlist.append('0') - print >> f, '\tstatic char* kwlist[] = {%s};' % (', '.join(kwlist),) - - if fast_args: - print >> f, '\tPyObject *%s;' % (', *'.join(fast_args)) - print >> f - - print >> f, '\tFUNCTION_CHECK()' + print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) # argument unpacking if vararg is not None: - print >> f, '\t%s = PyTuple_GetSlice(args, %d, INT_MAX);' % ( - vararg, len(positional_args)) - print >> f, '\tif (%s == NULL)' % (vararg,) - print >> f, '\t\tFUNCTION_RETURN(NULL)' - print >> f, '\targs = PyTuple_GetSlice(args, 0, %d);' % ( - len(positional_args),) - print >> f, '\tif (args == NULL) {' - print >> f, '\t\tERR_DECREF(%s)' % (vararg,) - print >> f, '\t\tFUNCTION_RETURN(NULL)' - print >> f, '\t}' - tail = """{ -\t\tERR_DECREF(args) -\t\tERR_DECREF(%s) -\t\tFUNCTION_RETURN(NULL); -\t} -\tPy_DECREF(args);""" % vararg - else: - tail = '\n\t\tFUNCTION_RETURN(NULL)' - for i in range(len(name_of_defaults)): - print >> f, '\t%s = %s;' % ( - positional_args[min_number_of_args+i], - name_of_defaults[i]) + varname = self.expr(vararg, locals) + lenargs = len(positional_args) + print >> f, ' %s = space.newtuple(list(args_w[%d:]))' % ( + varname, lenargs) + print >> f, ' _args_w = args_w[:%d]' % (lenargs,) + else: + print >> f, ' _args_w = args_w' + varname = None + + def tupstr(seq): + if len(seq) == 1: + fmt = '%s,' + else: + fmt = '%s' + return fmt % ', '.join(seq) + + print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) + # code not used: fmt = 'O'*min_number_of_args if min_number_of_args < len(positional_args): fmt += '|' + 'O'*(len(positional_args)-min_number_of_args) @@ -636,32 +760,37 @@ 'kwlist', ] lst += ['&' + a.name for a in positional_args] - print >> f, '\tif (!PyArg_ParseTupleAndKeywords(%s))' % ', '.join(lst), - print >> f, tail + #print >> f, '\tif (!PyArg_ParseTupleAndKeywords(%s))' % ', '.join(lst), - call_fast_args = list(fast_args) - if call_fast_args: - call_fast_args = 'TRACE_CALL ' + ', '.join(call_fast_args) - else: - call_fast_args = 'TRACE_CALL_VOID' - print >> f, '\treturn %s(%s);' % (fast_name, call_fast_args) - print >> f, '}' + print >> f, ' # XXX should parse args here, but no keyword support in gateway' + theargs = [arg for arg in fast_args if arg != varname] + txt = ('from pypy.translator.genrpy import PyArg_ParseMini\n' + 'm.PyArg_ParseMini = PyArg_ParseMini\n' + 'from pypy.interpreter.error import OperationError\n' + 'm.OperationError = OperationError') + self.initcode.append(txt) + print >> f, ' funcname = "%s"' % func.__name__ + if theargs: + txt = ' %s = PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' + print >>f, txt % (tupstr(theargs), + min_number_of_args, len(positional_args)) + else: + txt = ' PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' + print >>f, txt % (min_number_of_args, len(positional_args)) + print >> f, ' return %s(space, %s)' % (fast_name, ', '.join(fast_args)) print >> f print >> f, fast_function_header - print >> f, '{' fast_locals = [arg for arg in localnames if arg not in fast_set] - if fast_locals: - print >> f, '\tPyObject *%s;' % (', *'.join(fast_locals),) - print >> f # generate an incref for each input argument # skipped # print the body for line in body: - print >>f, line + print >> f, line + print >> f # print the PyMethodDef # skipped @@ -671,7 +800,7 @@ del self.translator.flowgraphs[func] Variable.instances.clear() - def rpyfunction_body(self, func): + def rpyfunction_body(self, func, localvars): try: graph = self.translator.getflowgraph(func) except Exception, e: @@ -682,86 +811,7 @@ # remove_direct_loops(graph) checkgraph(graph) - blocknum = {} allblocks = [] - localnames = {} - - def expr(v, wrapped = True): - if isinstance(v, Variable): - n = v.name - if n.startswith("v") and n[1:].isdigit(): - ret = localnames.get(v.name) - if not ret: - if wrapped: - localnames[v.name] = ret = "w_%d" % len(localnames) - else: - localnames[v.name] = ret = "v%d" % len(localnames) - return ret - elif isinstance(v, Constant): - return self.nameof(v.value, - debug=('Constant in the graph of',func)) - else: - raise TypeError, "expr(%r)" % (v,) - - def arglist(args): - res = [expr(arg) for arg in args] - return ", ".join(res) - - def oper(op): - if op.opname == "simple_call": - v = op.args[0] - exv = expr(v) - if exv.startswith("space.") and not exv.startswith("space.w_"): - # it is a space method - fmt = "%s = %s(%s)" - else: - if isinstance(v, Constant) and v.value in self.translator.flowgraphs: - fmt = "%s = %s(space, %s)" - else: - fmt = "%s = space.call(%s, space.newtuple([%s]))" - return fmt % (expr(op.result), expr(v), arglist(op.args[1:])) - if op.opname in self.has_listarg: - fmt = "%s = %s([%s])" - else: - fmt = "%s = %s(%s)" - # specialcase is_true - wrapped = op.opname != "is_true" - oper = "space.%s" % op.opname - return fmt % (expr(op.result, wrapped), oper, arglist(op.args)) - - def large_assignment(left, right, margin=65): - expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) - pieces = expr.split(",") - res = [pieces.pop(0)] - for piece in pieces: - if len(res[-1])+len(piece)+1 > margin: - res[-1] += "," - res.append(piece) - else: - res[-1] += (","+piece) - return res - - def gen_link(link, linklocalvars=None): - "Generate the code to jump across the given Link." - linklocalvars = linklocalvars or {} - left, right = [], [] - for a1, a2 in zip(link.args, link.target.inputargs): - if a1 in linklocalvars: - src = linklocalvars[a1] - else: - src = expr(a1) - left.append(expr(a2)) - right.append(src) - txt = "%s = %s" % (", ".join(left), ", ".join(right)) - if len(txt) <= 65: # arbitrary - yield txt - else: - for line in large_assignment(left, right): - yield line - goto = blocknum[link.target] - yield 'goto = %d' % goto - if goto <= blocknum[block]: - yield 'continue' f = self.f t = self.translator @@ -776,11 +826,6 @@ for block in allblocks: blocknum[block] = len(blocknum)+1 - # create function declaration - name = func.__name__ # change this - args = [expr(var) for var in start.inputargs] - argstr = ", ".join(args) - yield "def %s(space, %s):" % (name, argstr) yield " goto = %d # startblock" % blocknum[start] yield " while True:" @@ -789,34 +834,36 @@ regular_op = len(block.operations) - catch_exception # render all but maybe the last op for op in block.operations[:regular_op]: - yield "%s" % oper(op) + for line in self.oper(op, localvars).split("\n"): + yield "%s" % line # render the last op if it is exception handled for op in block.operations[regular_op:]: yield "try:" - yield " %s" % oper(op) + for line in self.oper(op, localvars).split("\n"): + yield " %s" % line if len(block.exits) == 0: if len(block.inputargs) == 2: # exc_cls, exc_value # exceptional return block - exc_cls = expr(block.inputargs[0]) - exc_val = expr(block.inputargs[1]) + exc_cls = self.expr(block.inputargs[0], localvars) + exc_val = self.expr(block.inputargs[1], localvars) yield "raise OperationError(%s, %s)" % (exc_cls, exc_val) else: # regular return block - retval = expr(block.inputargs[0]) + retval = self.expr(block.inputargs[0], localvars) yield "return %s" % retval return elif block.exitswitch is None: # single-exit block assert len(block.exits) == 1 - for op in gen_link(block.exits[0]): + for op in self.gen_link(block.exits[0], localvars, blocknum, block): yield "%s" % op elif catch_exception: # block catching the exceptions raised by its last operation # we handle the non-exceptional case first link = block.exits[0] assert link.exitcase is None - for op in gen_link(link): + for op in self.gen_link(link, localvars, blocknum, block): yield " %s" % op # we must catch the exception raised by the last operation, # which goes to the last err%d_%d label written above. @@ -826,10 +873,10 @@ for link in block.exits[1:]: assert issubclass(link.exitcase, Exception) # Exeption classes come unwrapped in link.exitcase - yield " %s space.issubtype(e.w_type, %s):" % (q, + yield " %s space.is_true(space.issubtype(e.w_type, %s)):" % (q, self.nameof(link.exitcase)) q = "elif" - for op in gen_link(link, { + for op in self.gen_link(link, localvars, blocknum, block, { Constant(last_exception): 'e.w_type', Constant(last_exc_value): 'e.w_value'}): yield " %s" % op @@ -843,16 +890,18 @@ exits.reverse() q = "if" for link in exits[:-1]: - yield "%s %s == %s:" % (q, expr(block.exitswitch), + yield "%s %s == %s:" % (q, self.expr(block.exitswitch, + localvars), link.exitcase) - for op in gen_link(link): + for op in self.gen_link(link, localvars, blocknum, block): yield " %s" % op q = "elif" link = exits[-1] yield "else:" - yield " assert %s == %s" % (expr(block.exitswitch), + yield " assert %s == %s" % (self.expr(block.exitswitch, + localvars), link.exitcase) - for op in gen_link(exits[-1]): + for op in self.gen_link(exits[-1], localvars, blocknum, block): yield " %s" % op for block in allblocks: @@ -870,11 +919,20 @@ RPY_INIT_HEADER = RPY_SEP + ''' -# something needed here? MODULE_INITFUNC(%(modname)s) +def init%(modname)s(space): + """NOT RPYTHON""" + class m: pass # fake module + m.__dict__ = globals() ''' RPY_INIT_FOOTER = ''' # entry point: %(entrypointname)s, %(entrypoint)s) +if __name__ == "__main__": + from pypy.objspace.std import StdObjSpace + space = StdObjSpace() + init%(modname)s(space) + print space.unwrap(space.call( + gfunc_%(entrypointname)s, space.newtuple([]))) ''' # a translation table suitable for str.translate() to remove @@ -884,17 +942,47 @@ 'A' <= chr(i) <= 'Z') and chr(i) or '_') for i in range(256)]) - +# temporary arg parsing +# what about keywords? Gateway doesn't support it. +def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): + err = None + if len(args_w) < minargs: + txt = "%s() takes at least %d argument%s (%d given)" + plural = ['s', ''][minargs == 1] + err = (name, minargs, plural, len(args_w)) + if len(args_w) > maxargs: + plural = ['s', ''][maxargs == 1] + if minargs == maxargs: + if minargs == 0: + txt = '%s() takes no arguments (%d given)' + err = (name, len(args_w)) + elif minargs == 1: + txt = '%s() takes exactly %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + else: + txt = '%s() takes at most %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + if err: + w_txt = space.wrap(txt) + w_tup = space.wrap(err) + w_txt = space.mod(w_txt, w_tup) + raise OperationError(space.w_TypeError, w_txt) + + # finally, we create the result ;-) + res_w = args_w + defaults_w[len(args_w) - minargs:] + assert len(res_w) == maxargs + return res_w +# _____________________________________________________________________ def somefunc(arg): pass def f(a,b): - print "start" +## print "start" a = [] a.append(3) for i in range(3): - print i + pass#print i if a > b: try: if b == 123: @@ -908,12 +996,15 @@ dummy = somefunc(23) return 42 -def ff(a, b): +class TestClass:pass + +def ff(a, b, c=3,*rest): try: raise SystemError, 42 return a+b finally: a = 7 + return len(rest),c glob = 100 def fff(): @@ -943,7 +1034,8 @@ #import md5 # how do I avoid the builtin module? from pypy.appspace import md5 - digest = md5.new("hello") + digest = md5.new("hello").hexdigest() + return digest def test_mod(): return app_mod__String_ANY("-%s-", ["hallo"]) @@ -951,7 +1043,45 @@ def test_join(): return " ".join(["hi", "there"]) -entry_point = (f, ff, fff, app_str_decode__String_ANY_ANY, test_mod, test_md5, test_join) [5] +# cannot nest classes,yet +class AnIterClass(object): + def __init__(self): + self.lis = [c for c in "test"] + def next(self): + if self.lis: + return self.lis.pop() + raise StopIteration + def __iter__(self): + return self + +def test_iter(): + res = [] + for i in "hallo": + res.append(i) + for i in AnIterClass(): + res.append(i) + return res + +def test_strutil(): + from pypy.objspace.std import strutil + return (strutil.string_to_int("42"), + strutil.string_to_long("12345678901234567890")) + +def all_entries(): + res = [func() for func in entry_points[:-1]] + return res + +entry_points = (lambda: f(2, 3), + lambda: ff(2, 3, 5), + fff, + lambda: app_str_decode__String_ANY_ANY("hugo"), + test_mod, + test_md5, + test_join, + test_iter, + test_strutil, + all_entries) +entry_point = entry_points[-1] import os, sys from pypy.interpreter import autopath @@ -960,33 +1090,23 @@ if appdir not in sys.path: sys.path.insert(0, appdir) + +test_mod() + t = Translator(entry_point, verbose=False, simplifying=True) if 0: gen = GenRpy(sys.stdout, t) else: fil= file("d:/tmp/look.py", "w") gen = GenRpy(fil, t) - print >> fil, \ -""" -from pypy.objspace.std import StdObjSpace -space = StdObjSpace() -test_mod(space) -""" fil.close() + import pypy.appspace.generated as tmp + pth = os.path.dirname(tmp.__file__) + fname = os.path.join(pth, gen.modname+".py") + file(fname, "w").write(file(fil.name).read()) #t.simplify() #t.view() # debugging graph = t.getflowgraph() ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab - -## testing how to call things -def f(space, w_a, w_b): - return space.add(w_a, w_b) - -space = gen.space -w = space.wrap -gw_f = interp2app(f) -w_gw_f = w(gw_f) -res = space.call(w_gw_f, space.newlist([w(2), w(3)])) -print res \ No newline at end of file From tismer at codespeak.net Mon Jan 10 14:33:41 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 10 Jan 2005 14:33:41 +0100 (MET) Subject: [pypy-svn] r8192 - pypy/trunk/src/pypy/translator Message-ID: <20050110133341.0288E27BAE@code1.codespeak.net> Author: tismer Date: Mon Jan 10 14:33:41 2005 New Revision: 8192 Modified: pypy/trunk/src/pypy/translator/genrpy.py Log: genrpy now produces output sorted by appearance in the source file(s) Modified: pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- pypy/trunk/src/pypy/translator/genrpy.py (original) +++ pypy/trunk/src/pypy/translator/genrpy.py Mon Jan 10 14:33:41 2005 @@ -12,6 +12,15 @@ This module appears to be already quite usable. But I need to ask how we want to integrate it. + +XXX open questions: +- do we wantamoduleperapp-spaceoperation? +- do we want to auto-generate stuff? +- do we want to create code that is more similar to the app code? +- do we want to create specialized code for constants? +- do we want to use small tail-functions instead of goto? +- do we want to inline small functions? +- do we want to translate non-rpythonic code as well? """ from __future__ import generators @@ -49,12 +58,6 @@ SEEN[result] = True return result -def go_figure_out_this_name(source): - # ahem - return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( - source, ) - - def ordered_blocks(graph): # collect all blocks allblocks = [] @@ -93,10 +96,9 @@ list.append(self, arg) class GenRpy: - def __init__(self, f, translator, modname=None, f2=None, f2name=None): - self.f = f - self.f2 = f2 - self.f2name = f2name + def __init__(self, fname, translator, modname=None, ftmpname=None): + self.fname = fname + self.ftmpname = ftmpname self.translator = translator self.modname = self.trans_funcname(modname or uniquemodulename(translator.functions[0].__name__)) @@ -128,10 +130,14 @@ # Or should it be the base space, ARMIN? #self.space = StdObjSpace() # for introspection self.space = FlowObjSpace() # for introspection - # debugging + + # just for debugging global _gen; _gen = self - self.gen_source() + #self.gen_source() + # opening the class to more parameterisation + + self.use_fast_call = False def expr(self, v, localnames, wrapped = True): if isinstance(v, Variable): @@ -167,7 +173,8 @@ "%(res)s = space.call(%(func)s, _tup)") # see if we can optimize for a fast call. # we justdo the very simple ones. - if isinstance(v, Constant) and exv.startswith('gfunc_'): + if self.use_fast_call and (isinstance(v, Constant) + and exv.startswith('gfunc_')): func = v.value if (not func.func_code.co_flags & CO_VARARGS) and ( func.func_defaults is None): @@ -480,7 +487,7 @@ "m.classtype = space.wrap(types.ClassType)\n") # metaclass = "m.classtype" # XXX I cannot instantiate these. - # XXX using type instead, since we still inherit from excpetion + # XXX using type instead, since we still inherit from excepetion # XXX what is the future of classes in pypy? name = self.uniquename('gcls_' + cls.__name__) @@ -630,6 +637,53 @@ raise Exception, 'Cannot translate an already-open file: %r' % (fil,) def gen_source(self): + # generate unordered source file, first. + # I prefer this over ordering everything in memory. + fname = self.fname + if self.ftmpname: + fname = self.ftmpname + f = file(fname, "w") + # generate ordered source file + try: + self.f = f + self.gen_source_temp() + finally: + f.close() + + def copyfile(source, target): + file(target, "w").write(file(source).read()) + + def order_sections(fname): + sep = "\n##SECTION##\n" + txt = file(fname).read() + pieces = txt.split(sep) + prelude = pieces.pop(0) + postlude = pieces.pop() + dic = {} + while pieces: + func = pieces.pop() + head = pieces.pop() + key = makekey(head, len(pieces)) + dic[key] = head + sep + func + lis = dic.items() + lis.sort() + lis = [prelude] + [func for head, func in lis] + [postlude] + txt = sep.join(lis) + file(fname, "w").write(txt) + + def makekey(txt, uniqueno): + dic = {} + for line in txt.split("\n"): + ign, name, value = line.split(None, 2) + dic[name] = eval(value) + key = dic["filename"], dic["firstlineno"], uniqueno + return key + + order_sections(fname) + if self.ftmpname: + copyfile(self.ftmpname, self.fname) + + def gen_source_temp(self): f = self.f info = { 'modname': self.modname, @@ -654,14 +708,15 @@ self.debugstack = () self.gen_global_declarations() + # set the final splitter + print >> f, "##SECTION##" # footer print >> f, self.RPY_INIT_HEADER % info - if self.f2name is not None: - print >> f, ' execfile("%s")' % self.f2name for codelines in self.initcode: for codeline in codelines.split("\n"): print >> f, " %s" % codeline print >> f, self.RPY_INIT_FOOTER % info + f.close() def gen_global_declarations(self): g = self.globaldecl @@ -676,14 +731,18 @@ for name in g: pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) del g[:] - if self.f2 is not None: - for line in self.initcode: - print >> self.f2, line - del self.initcode[:] def gen_rpyfunction(self, func): f = self.f + print >> f, "##SECTION##" # simple to split, afterwards + print >> f, ("## filename %r\n" + "## function %r\n" + "## firstlineno %d") % ( + func.func_code.co_filename, + func.func_code.co_name, + func.func_code.co_firstlineno) + print >> f, "##SECTION##" locals = {} body = list(self.rpyfunction_body(func, locals)) name_of_defaults = [self.nameof(x, debug=('Default argument of', func)) @@ -807,7 +866,7 @@ print 20*"*", e print func raise - # not needed, tuple assignment + # not needed, we use tuple assignment! # remove_direct_loops(graph) checkgraph(graph) @@ -974,6 +1033,8 @@ return res_w # _____________________________________________________________________ +## this should go into some test file + def somefunc(arg): pass @@ -1043,7 +1104,8 @@ def test_join(): return " ".join(["hi", "there"]) -# cannot nest classes,yet +# cannot nest local classes, yet +# this appears to be a problem in flow space. class AnIterClass(object): def __init__(self): self.lis = [c for c in "test"] @@ -1083,30 +1145,27 @@ all_entries) entry_point = entry_points[-1] -import os, sys -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -appdir = os.path.join(autopath.pypydir, 'appspace') - -if appdir not in sys.path: - sys.path.insert(0, appdir) - -test_mod() - -t = Translator(entry_point, verbose=False, simplifying=True) -if 0: - gen = GenRpy(sys.stdout, t) -else: - fil= file("d:/tmp/look.py", "w") - gen = GenRpy(fil, t) - fil.close() +if __name__ == "__main__": + import os, sys + from pypy.interpreter import autopath + srcdir = os.path.dirname(autopath.pypydir) + appdir = os.path.join(autopath.pypydir, 'appspace') + + if appdir not in sys.path: + sys.path.insert(0, appdir) + + fname = "d:/tmp/look.py" + t = Translator(entry_point, verbose=False, simplifying=True) + gen = GenRpy(fname, t) + gen.use_fast_call= True + gen.gen_source() import pypy.appspace.generated as tmp pth = os.path.dirname(tmp.__file__) fname = os.path.join(pth, gen.modname+".py") - file(fname, "w").write(file(fil.name).read()) + file(fname, "w").write(file(fname).read()) -#t.simplify() -#t.view() -# debugging -graph = t.getflowgraph() -ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab + #t.simplify() + #t.view() + # debugging + graph = t.getflowgraph() + ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab From pedronis at codespeak.net Mon Jan 10 15:44:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 10 Jan 2005 15:44:54 +0100 (MET) Subject: [pypy-svn] r8194 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050110144454.755EA27BAE@code1.codespeak.net> Author: pedronis Date: Mon Jan 10 15:44:54 2005 New Revision: 8194 Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py Log: other PyPy specific cases Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/utestconvert.py (original) +++ pypy/branch/src-pytest/pypy/tool/utestconvert.py Mon Jan 10 15:44:54 2005 @@ -24,8 +24,11 @@ d['assertNotAlmostEqual'] = ('assert round', ' !=', [2,3,4]) d['failUnlessAlmostEquals'] = ('assert not round', ' !=', [2,3,4]) # PyPy specific -d['assertRaises_w'] = ('self.raises_w', '', ['Any']) +d['assertRaises_w'] = ('self.space.raises_w', '', ['Any']) d['assertEqual_w'] = ('assert self.space.eq_w','',['Any']) +d['assertNotEqual_w'] = ('assert not self.space.eq_w','',['Any']) +d['failUnless_w'] = ('assert self.space.is_true','',['Any']) +d['failIf_w'] = ('assert not self.space.is_true','',['Any']) # the list of synonyms d['failUnlessRaises'] = d['assertRaises'] From pedronis at codespeak.net Mon Jan 10 16:26:59 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 10 Jan 2005 16:26:59 +0100 (MET) Subject: [pypy-svn] r8195 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050110152659.3F81B27BAE@code1.codespeak.net> Author: pedronis Date: Mon Jan 10 16:26:59 2005 New Revision: 8195 Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py Log: use less clash-prone fully qualified py.test.raises to simplify fiximport life for deciding whether to import py.test. Probably we should have a flag for the general case to choose between the short and the fully qual form, and maybe utestconvert itself should add the import py.test or from py.test import raises? Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/utestconvert.py (original) +++ pypy/branch/src-pytest/pypy/tool/utestconvert.py Mon Jan 10 16:26:59 2005 @@ -11,7 +11,7 @@ # function. # Old Unittest Name new name operator # of args -d['assertRaises'] = ('raises', '', ['Any']) +d['assertRaises'] = ('py.test.raises', '', ['Any']) d['fail'] = ('raise AssertionError', '', [0,1]) d['assert_'] = ('assert', '', [1,2]) d['failIf'] = ('assert not', '', [1,2]) From pedronis at codespeak.net Mon Jan 10 16:35:12 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 10 Jan 2005 16:35:12 +0100 (MET) Subject: [pypy-svn] r8196 - pypy/branch/src-pytest/pypy/tool Message-ID: <20050110153512.4EABC27BAE@code1.codespeak.net> Author: pedronis Date: Mon Jan 10 16:35:12 2005 New Revision: 8196 Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py Log: transform raises to py.test.raises was a bad idea (tm) because for app-level tests raises itself is added as a builtin directly. Modified: pypy/branch/src-pytest/pypy/tool/utestconvert.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/utestconvert.py (original) +++ pypy/branch/src-pytest/pypy/tool/utestconvert.py Mon Jan 10 16:35:12 2005 @@ -11,7 +11,7 @@ # function. # Old Unittest Name new name operator # of args -d['assertRaises'] = ('py.test.raises', '', ['Any']) +d['assertRaises'] = ('raises', '', ['Any']) d['fail'] = ('raise AssertionError', '', [0,1]) d['assert_'] = ('assert', '', [1,2]) d['failIf'] = ('assert not', '', [1,2]) From pedronis at codespeak.net Mon Jan 10 18:30:30 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 10 Jan 2005 18:30:30 +0100 (MET) Subject: [pypy-svn] r8198 - in pypy/branch/src-pytest/pypy/translator: test tool Message-ID: <20050110173030.3C23927BAE@code1.codespeak.net> Author: pedronis Date: Mon Jan 10 18:30:29 2005 New Revision: 8198 Modified: pypy/branch/src-pytest/pypy/translator/test/test_annrpython.py pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py pypy/branch/src-pytest/pypy/translator/test/test_pyrextrans.py pypy/branch/src-pytest/pypy/translator/test/test_sourcegen.py pypy/branch/src-pytest/pypy/translator/test/test_translator.py pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py Log: - ported translator/test tests as they were on the branch, I think we have more stuff on the head test_pyrextrans when run in verbose mode triggered code in buildpyxmodule that used a old make_dot interface, I changed that to have things work again - annotation/test tests didn't need porting Modified: pypy/branch/src-pytest/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_annrpython.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_annrpython.py Mon Jan 10 18:30:29 2005 @@ -1,6 +1,5 @@ import autopath -from pypy.tool import testit from pypy.tool.udir import udir from pypy.translator.annrpython import RPythonAnnotator, annmodel @@ -9,9 +8,8 @@ from pypy.translator.test import snippet -class AnnonateTestCase(testit.IntTestCase): - def setUp(self): - self.space = testit.objspace('flow') +class TestAnnonateTestCase: + objspacename = 'flow' def make_fun(self, func): import inspect @@ -45,7 +43,7 @@ block.closeblock(Link([result], fun.returnblock)) a = RPythonAnnotator() a.build_types(fun, [int]) - self.assertEquals(a.gettype(fun.getreturnvar()), int) + assert a.gettype(fun.getreturnvar()) == int def test_while(self): """ @@ -72,7 +70,7 @@ a = RPythonAnnotator() a.build_types(fun, [int]) - self.assertEquals(a.gettype(fun.getreturnvar()), int) + assert a.gettype(fun.getreturnvar()) == int def test_while_sum(self): """ @@ -107,97 +105,97 @@ a = RPythonAnnotator() a.build_types(fun, [int]) - self.assertEquals(a.gettype(fun.getreturnvar()), int) + assert a.gettype(fun.getreturnvar()) == int def test_f_calls_g(self): a = RPythonAnnotator() s = a.build_types(f_calls_g, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_lists(self): fun = self.make_fun(snippet.poor_man_rev_range) a = RPythonAnnotator() a.build_types(fun, [int]) # result should be a list of integers - self.assertEquals(a.gettype(fun.getreturnvar()), list) + assert a.gettype(fun.getreturnvar()) == list end_cell = a.binding(fun.getreturnvar()) - self.assertEquals(end_cell.s_item.knowntype, int) + assert end_cell.s_item.knowntype == int def test_factorial(self): a = RPythonAnnotator() s = a.build_types(snippet.factorial, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_factorial2(self): a = RPythonAnnotator() s = a.build_types(snippet.factorial2, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_build_instance(self): a = RPythonAnnotator() s = a.build_types(snippet.build_instance, []) # result should be a snippet.C instance - self.assertEquals(s.knowntype, snippet.C) + assert s.knowntype == snippet.C def test_set_attr(self): a = RPythonAnnotator() s = a.build_types(snippet.set_attr, []) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_merge_setattr(self): a = RPythonAnnotator() s = a.build_types(snippet.merge_setattr, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_inheritance1(self): a = RPythonAnnotator() s = a.build_types(snippet.inheritance1, []) # result should be exactly: - self.assertEquals(s, annmodel.SomeTuple([ + assert s == annmodel.SomeTuple([ a.bookkeeper.immutablevalue(()), annmodel.SomeInteger() - ])) + ]) def test_inheritance2(self): a = RPythonAnnotator() s = a.build_types(snippet._inheritance_nonrunnable, []) # result should be exactly: - self.assertEquals(s, annmodel.SomeTuple([ + assert s == annmodel.SomeTuple([ annmodel.SomeInteger(), annmodel.SomeObject() - ])) + ]) def test_poor_man_range(self): a = RPythonAnnotator() s = a.build_types(snippet.poor_man_range, [int]) # result should be a list of integers - self.assertEquals(s.knowntype, list) - self.assertEquals(s.s_item.knowntype, int) + assert s.knowntype == list + assert s.s_item.knowntype == int def test_methodcall1(self): a = RPythonAnnotator() s = a.build_types(snippet._methodcall1, [int]) # result should be a tuple of (C, positive_int) - self.assertEquals(s.knowntype, tuple) - self.assertEquals(len(s.items), 2) - self.assertEquals(s.items[0].knowntype, snippet.C) - self.assertEquals(s.items[1].knowntype, int) - self.assertEquals(s.items[1].nonneg, True) + assert s.knowntype == tuple + assert len(s.items) == 2 + assert s.items[0].knowntype == snippet.C + assert s.items[1].knowntype == int + assert s.items[1].nonneg == True def test_classes_methodcall1(self): a = RPythonAnnotator() a.build_types(snippet._methodcall1, [int]) # the user classes should have the following attributes: classes = a.bookkeeper.userclasses - self.assertEquals(classes[snippet.F].attrs.keys(), ['m']) - self.assertEquals(classes[snippet.G].attrs.keys(), ['m2']) - self.assertEquals(classes[snippet.H].attrs.keys(), ['attr']) - self.assertEquals(classes[snippet.H].about_attribute('attr'), + assert classes[snippet.F].attrs.keys() == ['m'] + assert classes[snippet.G].attrs.keys() == ['m2'] + assert classes[snippet.H].attrs.keys() == ['attr'] + assert classes[snippet.H].about_attribute('attr') == ( a.bookkeeper.immutablevalue(1)) def DISABLED_test_knownkeysdict(self): @@ -205,25 +203,25 @@ a = RPythonAnnotator() s = a.build_types(snippet.knownkeysdict, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_generaldict(self): a = RPythonAnnotator() s = a.build_types(snippet.generaldict, [str, int, str, int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_somebug1(self): a = RPythonAnnotator() s = a.build_types(snippet._somebug1, [int]) # result should be a built-in method - self.assert_(isinstance(s, annmodel.SomeBuiltin)) + assert isinstance(s, annmodel.SomeBuiltin) def test_with_init(self): a = RPythonAnnotator() s = a.build_types(snippet.with_init, [int]) # result should be an integer - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_with_more_init(self): a = RPythonAnnotator() @@ -233,9 +231,9 @@ # XXX on which class should the attribute 'a' appear? We only # ever flow WithInit.__init__ with a self which is an instance # of WithMoreInit, so currently it appears on WithMoreInit. - self.assertEquals(classes[snippet.WithMoreInit].about_attribute('a'), + assert classes[snippet.WithMoreInit].about_attribute('a') == ( annmodel.SomeInteger()) - self.assertEquals(classes[snippet.WithMoreInit].about_attribute('b'), + assert classes[snippet.WithMoreInit].about_attribute('b') == ( annmodel.SomeBool()) def test_global_instance(self): @@ -243,28 +241,28 @@ s = a.build_types(snippet.global_instance, []) # currently this returns the constant 42. # XXX not sure this is the best behavior... - self.assertEquals(s, a.bookkeeper.immutablevalue(42)) + assert s == a.bookkeeper.immutablevalue(42) def test_call_five(self): a = RPythonAnnotator() s = a.build_types(snippet.call_five, []) # returns should be a list of constants (= 5) - self.assert_(isinstance(s, annmodel.SomeList)) - self.assertEquals(s.s_item, a.bookkeeper.immutablevalue(5)) + assert isinstance(s, annmodel.SomeList) + assert s.s_item == a.bookkeeper.immutablevalue(5) def test_call_five_six(self): a = RPythonAnnotator() s = a.build_types(snippet.call_five_six, []) # returns should be a list of positive integers - self.assert_(isinstance(s, annmodel.SomeList)) - self.assertEquals(s.s_item, annmodel.SomeInteger(nonneg=True)) + assert isinstance(s, annmodel.SomeList) + assert s.s_item == annmodel.SomeInteger(nonneg=True) def test_constant_result(self): a = RPythonAnnotator() s = a.build_types(snippet.constant_result, []) #a.translator.simplify() # must return "yadda" - self.assertEquals(s, a.bookkeeper.immutablevalue("yadda")) + assert s == a.bookkeeper.immutablevalue("yadda") keys = a.translator.flowgraphs.keys() keys.sort() expected = [snippet.constant_result, @@ -272,14 +270,14 @@ # and not snippet.never_called ] expected.sort() - self.assertEquals(keys, expected) + assert keys == expected a.simplify() #a.translator.view() def test_call_pbc(self): a = RPythonAnnotator() s = a.build_types(snippet.call_cpbc, []) - self.assertEquals(s, a.bookkeeper.immutablevalue(42)) + assert s == a.bookkeeper.immutablevalue(42) def test_flow_type_info(self): a = RPythonAnnotator() @@ -287,7 +285,7 @@ a.translator.simplify() a.simplify() #a.translator.view() - self.assertEquals(s.knowntype, int) + assert s.knowntype == int def test_flow_type_info_2(self): a = RPythonAnnotator() @@ -295,19 +293,19 @@ [annmodel.SomeInteger(nonneg=True)]) # this checks that isinstance(i, int) didn't loose the # actually more precise information that i is non-negative - self.assertEquals(s, annmodel.SomeInteger(nonneg=True)) + assert s == annmodel.SomeInteger(nonneg=True) def test_flow_usertype_info(self): a = RPythonAnnotator() s = a.build_types(snippet.flow_usertype_info, [object]) #a.translator.view() - self.assertEquals(s.knowntype, snippet.WithInit) + assert s.knowntype == snippet.WithInit def test_flow_usertype_info2(self): a = RPythonAnnotator() s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit]) #a.translator.view() - self.assertEquals(s.knowntype, snippet.WithMoreInit) + assert s.knowntype == snippet.WithMoreInit def test_flow_identity_info(self): a = RPythonAnnotator() @@ -315,14 +313,14 @@ a.translator.simplify() a.simplify() #a.translator.view() - self.assertEquals(s, a.bookkeeper.immutablevalue((None, None))) + assert s == a.bookkeeper.immutablevalue((None, None)) def test_mergefunctions(self): a = RPythonAnnotator() s = a.build_types(snippet.mergefunctions, [int]) # the test is mostly that the above line hasn't blown up # but let's at least check *something* - self.assert_(isinstance(s, annmodel.SomePBC)) + assert isinstance(s, annmodel.SomePBC) def test_func_calls_func_which_just_raises(self): a = RPythonAnnotator() @@ -334,15 +332,15 @@ def test_tuple_unpack_from_const_tuple_with_different_types(self): a = RPythonAnnotator() s = a.build_types(snippet.func_arg_unpack, []) - self.assert_(isinstance(s, annmodel.SomeInteger)) - self.assertEquals(s.const, 3) + assert isinstance(s, annmodel.SomeInteger) + assert s.const == 3 def test_pbc_attr_preserved_on_instance(self): a = RPythonAnnotator() s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool]) #a.simplify() #a.translator.view() - self.assertEquals(s, annmodel.SomeInteger(nonneg=True)) + assert s == annmodel.SomeInteger(nonneg=True) #self.assertEquals(s.__class__, annmodel.SomeInteger) def test_is_and_knowntype_data(self): @@ -350,7 +348,7 @@ s = a.build_types(snippet.is_and_knowntype, [bool]) #a.simplify() #a.translator.view() - self.assertEquals(s, a.bookkeeper.immutablevalue(None)) + assert s == a.bookkeeper.immutablevalue(None) def test_isinstance_and_knowntype_data(self): a = RPythonAnnotator() @@ -358,7 +356,7 @@ s = a.build_types(snippet.isinstance_and_knowntype, [x]) #a.simplify() #a.translator.view() - self.assertEquals(s, x) + assert s == x def test_somepbc_simplify(self): a = RPythonAnnotator() @@ -379,9 +377,9 @@ ]: constmeth = getattr(example, methname) s_constmeth = iv(constmeth) - self.assert_(isinstance(s_constmeth, annmodel.SomeBuiltin)) + assert isinstance(s_constmeth, annmodel.SomeBuiltin) s_meth = s_example.getattr(iv(methname)) - self.assert_(isinstance(s_constmeth, annmodel.SomeBuiltin)) + assert isinstance(s_constmeth, annmodel.SomeBuiltin) def g(n): @@ -395,7 +393,3 @@ total += i i += 1 return total - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py Mon Jan 10 18:30:29 2005 @@ -1,5 +1,4 @@ import autopath -from pypy.tool import testit from pypy.tool.udir import udir @@ -39,90 +38,91 @@ from pypy.translator.test import snippet as t from pypy.translator.tool.buildcl import Literal -class GenCLTestCase(testit.IntTestCase): +class TestGenCLTestCase: - def setUp(self): - self.space = testit.objspace('flow') + objspacename = 'flow' + + def setup_method(self,method): if not global_cl: raise (testit.TestSkip, "Common Lisp neither configured nor detected.") def test_if(self): cl_if = make_cl_func(t.if_then_else) - self.assertEquals(cl_if(True, 50, 100), 50) - self.assertEquals(cl_if(False, 50, 100), 100) - self.assertEquals(cl_if(0, 50, 100), 100) - self.assertEquals(cl_if(1, 50, 100), 50) - self.assertEquals(cl_if([], 50, 100), 100) - self.assertEquals(cl_if([[]], 50, 100), 50) + assert cl_if(True, 50, 100) == 50 + assert cl_if(False, 50, 100) == 100 + assert cl_if(0, 50, 100) == 100 + assert cl_if(1, 50, 100) == 50 + assert cl_if([], 50, 100) == 100 + assert cl_if([[]], 50, 100) == 50 def test_gcd(self): cl_gcd = make_cl_func(t.my_gcd, [int, int]) - self.assertEquals(cl_gcd(96, 64), 32) + assert cl_gcd(96, 64) == 32 def test_is_perfect(self): # pun intended cl_perfect = make_cl_func(t.is_perfect_number, [int]) - self.assertEquals(cl_perfect(24), False) - self.assertEquals(cl_perfect(28), True) + assert cl_perfect(24) == False + assert cl_perfect(28) == True def test_bool(self): cl_bool = make_cl_func(t.my_bool) - self.assertEquals(cl_bool(0), False) - self.assertEquals(cl_bool(42), True) - self.assertEquals(cl_bool(True), True) + assert cl_bool(0) == False + assert cl_bool(42) == True + assert cl_bool(True) == True def test_array(self): cl_four = make_cl_func(t.two_plus_two) - self.assertEquals(cl_four(), 4) + assert cl_four() == 4 def test_sieve(self): cl_sieve = make_cl_func(t.sieve_of_eratosthenes) - self.assertEquals(cl_sieve(), 1028) + assert cl_sieve() == 1028 def test_easy(self): # These are the Pyrex tests which were easy to adopt. f1 = make_cl_func(t.simple_func, [int]) - self.assertEquals(f1(1), 2) + assert f1(1) == 2 f2 = make_cl_func(t.while_func, [int]) - self.assertEquals(f2(10), 55) + assert f2(10) == 55 f3 = make_cl_func(t.simple_id) - self.assertEquals(f3(9), 9) + assert f3(9) == 9 f4 = make_cl_func(t.branch_id) - self.assertEquals(f4(1, 2, 3), 2) - self.assertEquals(f4(0, 2, 3), 3) + assert f4(1, 2, 3) == 2 + assert f4(0, 2, 3) == 3 f5 = make_cl_func(t.int_id, [int]) - self.assertEquals(f5(3), 3) + assert f5(3) == 3 f6 = make_cl_func(t.time_waster, [int]) - self.assertEquals(f6(30), 3657) + assert f6(30) == 3657 def test_string(self): cl_greet = make_cl_func(t.greet, [str]) - self.assertEquals(cl_greet("world"), "helloworld") + assert cl_greet("world") == "helloworld" cl_stringmaker = make_cl_func(t.nested_whiles, [int, int]) - self.assertEquals(cl_stringmaker(111, 114), + assert cl_stringmaker(111, 114) == ( "...!...!...!...!...!") def test_for(self): cl_python = make_cl_func(t.choose_last) - self.assertEquals(cl_python(), "python") + assert cl_python() == "python" def test_builtin(self): cl_builtinusage = make_cl_func(t.builtinusage) - self.assertEquals(cl_builtinusage(), 4) + assert cl_builtinusage() == 4 def test_slice(self): cl_half = make_cl_func(t.half_of_n, [int]) - self.assertEquals(cl_half(10), 5) + assert cl_half(10) == 5 def test_powerset(self): cl_powerset = make_cl_func(t.powerset, [int]) result = cl_powerset(3) - self.assertEquals(result.__class__, Literal) - self.assertEquals(result.val, + assert result.__class__ == Literal + assert result.val == ( '#(#() #(0) #(1) #(0 1) #(2) #(0 2) #(1 2) #(0 1 2))') def test_yast(self): cl_sum = make_cl_func(t.yast) # yet another sum test - self.assertEquals(cl_sum(range(12)), 66) + assert cl_sum(range(12)) == 66 # TODO @@ -132,7 +132,3 @@ # - attribute. need object. symbol-plist? # yast # - need way to specify that argument is list of int. - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py Mon Jan 10 18:30:29 2005 @@ -1,5 +1,4 @@ import autopath -from pypy.tool import testit from pypy.tool.udir import udir from pypy.translator.genc import GenC from pypy.objspace.flow.model import * @@ -13,10 +12,9 @@ buildpyxmodule.enable_fast_compilation() -class NoTypeCGenTestCase(testit.IntTestCase): +class TestNoTypeCGenTestCase: - def setUp(self): - self.space = testit.objspace('flow') + objspacename = 'flow' def build_cfunc(self, func): try: func = func.im_func @@ -27,96 +25,96 @@ def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) - self.assertEquals(cfunc(1), 2) + assert cfunc(1) == 2 def test_while_func(self): while_func = self.build_cfunc(snippet.while_func) - self.assertEquals(while_func(10), 55) + assert while_func(10) == 55 def test_nested_whiles(self): nested_whiles = self.build_cfunc(snippet.nested_whiles) - self.assertEquals(nested_whiles(111, 114), + assert nested_whiles(111, 114) == ( '...!...!...!...!...!') def test_poor_man_range(self): poor_man_range = self.build_cfunc(snippet.poor_man_range) - self.assertEquals(poor_man_range(10), range(10)) + assert poor_man_range(10) == range(10) def poor_man_rev_range(self): poor_man_rev_range = self.build_cfunc(snippet.poor_man_rev_range) - self.assertEquals(poor_man_rev_range(10), range(9,-1,-1)) + assert poor_man_rev_range(10) == range(9,-1,-1) def test_simple_id(self): #we just want to see, if renaming of parameter works correctly #if the first branch is the end branch simple_id = self.build_cfunc(snippet.simple_id) - self.assertEquals(simple_id(9), 9) + assert simple_id(9) == 9 def test_branch_id(self): branch_id = self.build_cfunc(snippet.branch_id) - self.assertEquals(branch_id(1, 2, 3), 2) - self.assertEquals(branch_id(0, 2, 3), 3) + assert branch_id(1, 2, 3) == 2 + assert branch_id(0, 2, 3) == 3 def test_int_id(self): int_id = self.build_cfunc(snippet.int_id) - self.assertEquals(int_id(3), 3) + assert int_id(3) == 3 def dont_test_attrs(self): attrs = self.build_cfunc(snippet.attrs) - self.assertEquals(attrs(), 9) + assert attrs() == 9 def test_builtinusage(self): fun = self.build_cfunc(snippet.builtinusage) - self.assertEquals(fun(), 4) + assert fun() == 4 def test_sieve(self): sieve = self.build_cfunc(snippet.sieve_of_eratosthenes) - self.assertEquals(sieve(), 1028) + assert sieve() == 1028 def test_slice(self): half = self.build_cfunc(snippet.half_of_n) - self.assertEquals(half(10), 5) + assert half(10) == 5 def test_poly_branch(self): poly_branch = self.build_cfunc(snippet.poly_branch) - self.assertEquals(poly_branch(10), [1,2,3]*2) - self.assertEquals(poly_branch(0), ['a','b','c']*2) + assert poly_branch(10) == [1,2,3]*2 + assert poly_branch(0) == ['a','b','c']*2 def test_and(self): sand = self.build_cfunc(snippet.s_and) - self.assertEquals(sand(5, 6), "yes") - self.assertEquals(sand(5, 0), "no") - self.assertEquals(sand(0, 6), "no") - self.assertEquals(sand(0, 0), "no") + assert sand(5, 6) == "yes" + assert sand(5, 0) == "no" + assert sand(0, 6) == "no" + assert sand(0, 0) == "no" def test_yast(self): yast = self.build_cfunc(snippet.yast) - self.assertEquals(yast([1000,100,10,1]), 1111) - self.assertEquals(yast(range(100)), (99*100)/2) + assert yast([1000,100,10,1]) == 1111 + assert yast(range(100)) == (99*100)/2 def test_with_init(self): with_init = self.build_cfunc(snippet.with_init) - self.assertEquals(with_init(0), 0) - self.assertEquals(with_init(-100), -100) + assert with_init(0) == 0 + assert with_init(-100) == -100 def test_with_more_init(self): with_more_init = self.build_cfunc(snippet.with_more_init) - self.assertEquals(with_more_init(10, False), -10) - self.assertEquals(with_more_init(20, True), 20) + assert with_more_init(10, False) == -10 + assert with_more_init(20, True) == 20 def test_global_instance(self): global_instance = self.build_cfunc(snippet.global_instance) - self.assertEquals(global_instance(), 42) + assert global_instance() == 42 def test_global_newstyle_instance(self): global_newstyle_instance = self.build_cfunc(snippet.global_newstyle_instance) - self.assertEquals(global_newstyle_instance().a, 1) + assert global_newstyle_instance().a == 1 def test_global_recursive_list(self): global_recursive_list = self.build_cfunc(snippet.global_recursive_list) lst = global_recursive_list() - self.assertEquals(len(lst), 1) - self.assert_(lst[0] is lst) + assert len(lst) == 1 + assert lst[0] is lst ## def test_global_badinit(self): ## global_badinit = self.build_cfunc(snippet.global_badinit) @@ -124,69 +122,69 @@ def test_multiple_inheritance(self): multiple_inheritance = self.build_cfunc(snippet.multiple_inheritance) - self.assertEquals(multiple_inheritance(), 1+2+3+4) + assert multiple_inheritance() == 1+2+3+4 def test_call_star_args(self): call_star_args = self.build_cfunc(snippet.call_star_args) - self.assertEquals(call_star_args(42), 52) + assert call_star_args(42) == 52 def test_call_default_args(self): call_default_args = self.build_cfunc(snippet.call_default_args) - self.assertEquals(call_default_args(42), 111+42+3) + assert call_default_args(42) == 111+42+3 def test_call_default_and_star_args(self): call_default_and_star_args = self.build_cfunc( snippet.call_default_and_star_args) - self.assertEquals(call_default_and_star_args(42), + assert call_default_and_star_args(42) == ( (111+42+3+0, -1000-2000-3000+2)) def test_call_with_star(self): call_with_star = self.build_cfunc(snippet.call_with_star) - self.assertEquals(call_with_star(()), -15L) - self.assertEquals(call_with_star((4,)), -13L) - self.assertEquals(call_with_star((4,7)), -9L) - self.assertEquals(call_with_star([]), -15L) - self.assertEquals(call_with_star([4]), -13L) - self.assertEquals(call_with_star([4,7]), -9L) - self.assertRaises(TypeError, call_with_star, (4,7,12)) - self.assertRaises(TypeError, call_with_star, [4,7,12,63]) - self.assertRaises(TypeError, call_with_star, 521) + assert call_with_star(()) == -15L + assert call_with_star((4,)) == -13L + assert call_with_star((4,7)) == -9L + assert call_with_star([]) == -15L + assert call_with_star([4]) == -13L + assert call_with_star([4,7]) == -9L + raises(TypeError, call_with_star, (4,7,12)) + raises(TypeError, call_with_star, [4,7,12,63]) + raises(TypeError, call_with_star, 521) def XXX_test_call_with_keyword(self): call_with_keyword = self.build_cfunc(snippet.call_with_keyword) - self.assertEquals(call_with_keyword(100), 82) + assert call_with_keyword(100) == 82 def test_finallys(self): finallys = self.build_cfunc(snippet.finallys) - self.assertEquals(finallys(['hello']), 8) - self.assertEquals(finallys('X'), 8) - self.assertEquals(finallys([]), 6) - self.assertEquals(finallys('XY'), 6) + assert finallys(['hello']) == 8 + assert finallys('X') == 8 + assert finallys([]) == 6 + assert finallys('XY') == 6 def test_finally2(self): finally2 = self.build_cfunc(snippet.finally2) lst = range(10) finally2(lst, 5) - self.assertEquals(lst, [0,1,2,3,4, 6, 6,7,8, 'done']) + assert lst == [0,1,2,3,4, 6, 6,7,8, 'done'] dic = {} - self.assertRaises(KeyError, finally2, dic, "won't find this key") - self.assertEquals(dic, {-1: 'done'}) + raises(KeyError, finally2, dic, "won't find this key") + assert dic == {-1: 'done'} def test_bare_raise(self): bare_raise = self.build_cfunc(snippet.bare_raise) - self.assertEquals(bare_raise(range(0, 100, 10), False), 50) - self.assertEquals(bare_raise(range(0, 100, 10), True), 50) - self.assertRaises(IndexError, bare_raise, range(0, 30, 10), False) - self.assertEquals(bare_raise(range(0, 30, 10), True), None) + assert bare_raise(range(0, 100, 10), False) == 50 + assert bare_raise(range(0, 100, 10), True) == 50 + raises(IndexError, bare_raise, range(0, 30, 10), False) + assert bare_raise(range(0, 30, 10), True) == None def test_get_set_del_slice(self): fn = self.build_cfunc(snippet.get_set_del_slice) l = list('abcdefghij') result = fn(l) - self.assertEquals(l, [3, 'c', 8, 11, 'h', 9]) - self.assertEquals(result, ([3, 'c'], [9], [11, 'h'])) + assert l == [3, 'c', 8, 11, 'h', 9] + assert result == ([3, 'c'], [9], [11, 'h']) -class TypedTestCase(testit.IntTestCase): +class TestTypedTestCase: def getcompiled(self, func): t = Translator(func, simplifying=True) @@ -203,36 +201,36 @@ def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) - self.assertEquals(set_attr(), 2) + assert set_attr() == 2 def test_inheritance2(self): inheritance2 = self.getcompiled(snippet.inheritance2) - self.assertEquals(inheritance2(), ((-12, -12), (3, "world"))) + assert inheritance2() == ((-12, -12), (3, "world")) def test_factorial2(self): factorial2 = self.getcompiled(snippet.factorial2) - self.assertEquals(factorial2(5), 120) + assert factorial2(5) == 120 def test_factorial(self): factorial = self.getcompiled(snippet.factorial) - self.assertEquals(factorial(5), 120) + assert factorial(5) == 120 def test_simple_method(self): simple_method = self.getcompiled(snippet.simple_method) - self.assertEquals(simple_method(55), 55) + assert simple_method(55) == 55 def test_sieve_of_eratosthenes(self): sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes) - self.assertEquals(sieve_of_eratosthenes(), 1028) + assert sieve_of_eratosthenes() == 1028 def test_nested_whiles(self): nested_whiles = self.getcompiled(snippet.nested_whiles) - self.assertEquals(nested_whiles(5,3), '!!!!!') + assert nested_whiles(5,3) == '!!!!!' def test_call_five(self): call_five = self.getcompiled(snippet.call_five) result = call_five() - self.assertEquals(result, [5]) + 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 ") @@ -240,7 +238,7 @@ def test_call_unpack_56(self): call_unpack_56 = self.getcompiled(snippet.call_unpack_56) result = call_unpack_56() - self.assertEquals(result, (2, 5, 6)) + assert result == (2, 5, 6) def test_class_defaultattr(self): class K: @@ -250,7 +248,7 @@ k.n += " world" return k.n fn = self.getcompiled(class_defaultattr) - self.assertEquals(fn(), "hello world") + assert fn() == "hello world" def test_tuple_repr(self): def tuple_repr(x=int, y=object): @@ -259,22 +257,19 @@ x = x-1 return z fn = self.getcompiled(tuple_repr) - self.assertEquals(fn(6,'a'), (6,'a')) + assert fn(6,'a') == (6,'a') def test_classattribute(self): fn = self.getcompiled(snippet.classattribute) - self.assertEquals(fn(1), 123) - self.assertEquals(fn(2), 456) - self.assertEquals(fn(3), 789) - self.assertEquals(fn(4), 789) - self.assertEquals(fn(5), 101112) + assert fn(1) == 123 + assert fn(2) == 456 + assert fn(3) == 789 + assert fn(4) == 789 + assert fn(5) == 101112 def test_get_set_del_slice(self): fn = self.getcompiled(snippet.get_set_del_slice) l = list('abcdefghij') result = fn(l) - self.assertEquals(l, [3, 'c', 8, 11, 'h', 9]) - self.assertEquals(result, ([3, 'c'], [9], [11, 'h'])) - -if __name__ == '__main__': - testit.main() + assert l == [3, 'c', 8, 11, 'h', 9] + assert result == ([3, 'c'], [9], [11, 'h']) Modified: pypy/branch/src-pytest/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_pyrextrans.py Mon Jan 10 18:30:29 2005 @@ -1,5 +1,5 @@ import autopath -from pypy.tool import testit +import py from pypy.tool.udir import udir from pypy.translator.genpyrex import GenPyrex from pypy.objspace.flow.model import * @@ -13,16 +13,15 @@ buildpyxmodule.enable_fast_compilation() -class NoTypePyrexGenTestCase(testit.IntTestCase): +class TestNoTypePyrexGenTestCase: - def setUp(self): - self.space = testit.objspace('flow') + objspacename = 'flow' def build_cfunc(self, func): try: func = func.im_func except AttributeError: pass - dot = testit.Options.verbose >0 and 1 or 0 + dot = py.test.config.option.verbose >0 and 1 or 0 options = { 'simplify' : 1, 'dot' : dot, @@ -31,69 +30,69 @@ def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) - self.assertEquals(cfunc(1), 2) + assert cfunc(1) == 2 def test_while_func(self): while_func = self.build_cfunc(snippet.while_func) - self.assertEquals(while_func(10), 55) + assert while_func(10) == 55 def test_nested_whiles(self): nested_whiles = self.build_cfunc(snippet.nested_whiles) - self.assertEquals(nested_whiles(111, 114), + assert nested_whiles(111, 114) == ( '...!...!...!...!...!') def test_poor_man_range(self): poor_man_range = self.build_cfunc(snippet.poor_man_range) - self.assertEquals(poor_man_range(10), range(10)) + assert poor_man_range(10) == range(10) def poor_man_rev_range(self): poor_man_rev_range = self.build_cfunc(snippet.poor_man_rev_range) - self.assertEquals(poor_man_rev_range(10), range(9,-1,-1)) + assert poor_man_rev_range(10) == range(9,-1,-1) def test_simple_id(self): #we just want to see, if renaming of parameter works correctly #if the first branch is the end branch simple_id = self.build_cfunc(snippet.simple_id) - self.assertEquals(simple_id(9), 9) + assert simple_id(9) == 9 def test_branch_id(self): branch_id = self.build_cfunc(snippet.branch_id) - self.assertEquals(branch_id(1, 2, 3), 2) - self.assertEquals(branch_id(0, 2, 3), 3) + assert branch_id(1, 2, 3) == 2 + assert branch_id(0, 2, 3) == 3 def test_int_id(self): int_id = self.build_cfunc(snippet.int_id) - self.assertEquals(int_id(3), 3) + assert int_id(3) == 3 def dont_test_attrs(self): attrs = self.build_cfunc(snippet.attrs) - self.assertEquals(attrs(), 9) + assert attrs() == 9 def test_builtinusage(self): fun = self.build_cfunc(snippet.builtinusage) - self.assertEquals(fun(), 4) + assert fun() == 4 def test_sieve(self): sieve = self.build_cfunc(snippet.sieve_of_eratosthenes) - self.assertEquals(sieve(), 1028) + assert sieve() == 1028 def test_slice(self): half = self.build_cfunc(snippet.half_of_n) - self.assertEquals(half(10), 5) + assert half(10) == 5 def test_poly_branch(self): poly_branch = self.build_cfunc(snippet.poly_branch) - self.assertEquals(poly_branch(10), [1,2,3]*2) - self.assertEquals(poly_branch(0), ['a','b','c']*2) + assert poly_branch(10) == [1,2,3]*2 + assert poly_branch(0) == ['a','b','c']*2 def test_and(self): sand = self.build_cfunc(snippet.s_and) - self.assertEquals(sand(5, 6), "yes") - self.assertEquals(sand(5, 0), "no") - self.assertEquals(sand(0, 6), "no") - self.assertEquals(sand(0, 0), "no") + assert sand(5, 6) == "yes" + assert sand(5, 0) == "no" + assert sand(0, 6) == "no" + assert sand(0, 0) == "no" -class TypedTestCase(testit.IntTestCase): +class TestTypedTestCase: def getcompiled(self, func): t = Translator(func) @@ -110,35 +109,32 @@ def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) - self.assertEquals(set_attr(), 2) + assert set_attr() == 2 def test_inheritance2(self): inheritance2 = self.getcompiled(snippet.inheritance2) - self.assertEquals(inheritance2(), ((-12, -12), (3, "world"))) + assert inheritance2() == ((-12, -12), (3, "world")) def test_factorial2(self): factorial2 = self.getcompiled(snippet.factorial2) - self.assertEquals(factorial2(5), 120) + assert factorial2(5) == 120 def test_factorial(self): factorial = self.getcompiled(snippet.factorial) - self.assertEquals(factorial(5), 120) + assert factorial(5) == 120 def test_simple_method(self): simple_method = self.getcompiled(snippet.simple_method) - self.assertEquals(simple_method(55), 55) + assert simple_method(55) == 55 def test_sieve_of_eratosthenes(self): sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes) - self.assertEquals(sieve_of_eratosthenes(), 1028) + assert sieve_of_eratosthenes() == 1028 def test_nested_whiles(self): nested_whiles = self.getcompiled(snippet.nested_whiles) - self.assertEquals(nested_whiles(5,3), '!!!!!') + assert nested_whiles(5,3) == '!!!!!' def test_call_five(self): call_five = self.getcompiled(snippet.call_five) - self.assertEquals(call_five(), [5]) - -if __name__ == '__main__': - testit.main() + assert call_five() == [5] Modified: pypy/branch/src-pytest/pypy/translator/test/test_sourcegen.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_sourcegen.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_sourcegen.py Mon Jan 10 18:30:29 2005 @@ -1,6 +1,5 @@ import autopath -from pypy.tool import testit from pypy.tool.udir import udir from pypy.translator.genpyrex import GenPyrex @@ -14,7 +13,7 @@ buildpyxmodule.enable_fast_compilation() -class SourceGenTestCase(testit.IntTestCase): +class TestSourceGenTestCase: def test_simple_func(self): """ one test source: @@ -30,7 +29,7 @@ block.closeblock(Link([result], fun.returnblock)) result = GenPyrex(fun).emitcode() mod = make_module_from_pyxstring('test_source1', udir, result) - self.assertEquals(mod.f(1), 2) + assert mod.f(1) == 2 def test_if(self): """ @@ -55,8 +54,8 @@ result = GenPyrex(fun).emitcode() mod = make_module_from_pyxstring('test_source2', udir, result) - self.assertEquals(mod.f(-1, 42), 42) - self.assertEquals(mod.f(3, 5), 3) + assert mod.f(-1, 42) == 42 + assert mod.f(3, 5) == 3 def test_while_sum(self): """ @@ -91,8 +90,5 @@ result = GenPyrex(fun).emitcode() mod = make_module_from_pyxstring('test_source4', udir, result) - self.assertEquals(mod.f(3), 6) - self.assertEquals(mod.f(-3), 0) - -if __name__ == '__main__': - testit.main() + assert mod.f(3) == 6 + assert mod.f(-3) == 0 Modified: pypy/branch/src-pytest/pypy/translator/test/test_translator.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_translator.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_translator.py Mon Jan 10 18:30:29 2005 @@ -1,10 +1,4 @@ import autopath -from pypy.tool import testit from pypy.translator.translator import Translator from pypy.translator.test import snippet - - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py (original) +++ pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py Mon Jan 10 18:30:29 2005 @@ -1,5 +1,4 @@ import autopath -from pypy.tool import testit from pypy.tool.udir import udir from py.process import cmdexec @@ -54,7 +53,7 @@ lastdir = path.local() os.chdir(str(dirpath)) try: - modname = cfile.get('purebasename') + modname = cfile.purebasename if debug: print "modname", modname c = stdoutcapture.Capture(mixed_out_err = True) try: @@ -143,10 +142,9 @@ base = udir.join(name).new(ext='.py').write(source) if dot: - from pypy.translator.tool.make_dot import DotGen - dotgen = DotGen() - subgraphs = [] - subgraphs.append(dotgen.getsubgraph(name, funcgraph)) + from pypy.translator.tool.make_dot import FlowGraphDotGen + dotgen = FlowGraphDotGen(name) + dotgen.emit_subgraph(name, funcgraph) # apply transformations if simplify: @@ -177,13 +175,7 @@ if dot: if name != func.func_name: # if some transformations have been done - subgraphs.append(dotgen.getsubgraph(name, funcgraph)) - content = dotgen.getgraph("graph_"+func.func_name, subgraphs) - base = udir.join(name) - base.new(ext='dot').write(content) - base.new(ext='ps') - cmdexec('dot -Tps -o %s %s' % ( - str(base.new(ext='ps')), - str(base.new(ext='.dot')))) + dotgen.emit_subgraph(name, funcgraph) + dotgen.generate() return getattr(mod, func.func_name) From pedronis at codespeak.net Mon Jan 10 17:19:40 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 10 Jan 2005 17:19:40 +0100 (MET) Subject: [pypy-svn] r8197 - in pypy/branch/src-pytest/pypy: . objspace/std/test tool Message-ID: <20050110161940.4B0B327BB3@code1.codespeak.net> Author: pedronis Date: Mon Jan 10 17:19:39 2005 New Revision: 8197 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/objspace/std/test/test_boolobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_dictobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_dictproxy.py pypy/branch/src-pytest/pypy/objspace/std/test/test_instmethobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_iterobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_listobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_multimethod.py pypy/branch/src-pytest/pypy/objspace/std/test/test_noneobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_restricted_int.py pypy/branch/src-pytest/pypy/objspace/std/test/test_sliceobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_stdobjspace.py pypy/branch/src-pytest/pypy/objspace/std/test/test_stringformat.py pypy/branch/src-pytest/pypy/objspace/std/test/test_stringobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_strutil.py pypy/branch/src-pytest/pypy/objspace/std/test/test_tupleobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_typeobject.py pypy/branch/src-pytest/pypy/objspace/std/test/test_unicodestring.py pypy/branch/src-pytest/pypy/objspace/std/test/test_userobject.py pypy/branch/src-pytest/pypy/tool/fiximport.py Log: - conftest sticks py.test.raises as raises in tests module global namespace. - ported objspace/std/test tests Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Mon Jan 10 17:19:39 2005 @@ -83,10 +83,12 @@ class PyPyItem(py.test.Item): # All PyPy test items catch and display OperationErrors specially. - #def setup_module(self, mod): + def setup_module(self, mod): # if hasattr(mod, 'objspacename'): # mod.space = getttestobjspace(mod.objspacename) - # super(PyPyItem, self).setup_module(mod) + # stick py.test raise in module globals + mod.raises = py.test.raises + super(PyPyItem, self).setup_module(mod) def setup_class(self, cls): name = getattr(cls, 'objspacename', None) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_boolobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_boolobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_boolobject.py Mon Jan 10 17:19:39 2005 @@ -1,42 +1,33 @@ import autopath -from pypy.tool import testit -class TestW_BoolObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') +class TestW_BoolObject: + + def setup_method(self,method): self.true = self.space.w_True self.false = self.space.w_False self.wrap = self.space.wrap - def tearDown(self): - pass - def test_repr(self): - self.assertEqual_w(self.space.repr(self.true), self.wrap("True")) - self.assertEqual_w(self.space.repr(self.false), self.wrap("False")) + assert self.space.eq_w(self.space.repr(self.true), self.wrap("True")) + assert self.space.eq_w(self.space.repr(self.false), self.wrap("False")) def test_true(self): - self.failUnless_w(self.true) + assert self.space.is_true(self.true) def test_false(self): - self.failIf_w(self.false) + assert not self.space.is_true(self.false) -class AppBoolTest(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') - +class AppTestAppBoolTest: def test_bool_callable(self): - self.assertEquals(True, bool(1)) - self.assertEquals(False, bool(0)) - self.assertEquals(False, bool()) + assert True == bool(1) + assert False == bool(0) + assert False == bool() def test_bool_string(self): - self.assertEquals("True", str(True)) - self.assertEquals("False", str(False)) - self.assertEquals("True", repr(True)) - self.assertEquals("False", repr(False)) - -if __name__ == '__main__': - testit.main() + assert "True" == str(True) + assert "False" == str(False) + assert "True" == repr(True) + assert "False" == repr(False) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_dictobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_dictobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_dictobject.py Mon Jan 10 17:19:39 2005 @@ -1,29 +1,24 @@ import autopath -from pypy.tool import testit from pypy.objspace.std.dictobject import W_DictObject -class TestW_DictObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_DictObject: def test_empty(self): space = self.space d = W_DictObject(space, []) - self.failIf_w(d) + assert not self.space.is_true(d) def test_nonempty(self): space = self.space wNone = space.w_None d = W_DictObject(space, [(wNone, wNone)]) - self.failUnless(space.is_true(d)) + assert space.is_true(d) i = space.getitem(d, wNone) equal = space.eq(i, wNone) - self.failUnless(space.is_true(equal)) + assert space.is_true(equal) def test_setitem(self): space = self.space @@ -32,7 +27,7 @@ d = W_DictObject(space, [(space.wrap('zero'),space.wrap(0))]) space.setitem(d,wk1,wone) wback = space.getitem(d,wk1) - self.assertEqual_w(wback,wone) + assert self.space.eq_w(wback,wone) def test_delitem(self): space = self.space @@ -42,13 +37,13 @@ (space.wrap('one'),space.wrap(1)), (space.wrap('two'),space.wrap(2))]) space.delitem(d,space.wrap('one')) - self.assertEqual_w(space.getitem(d,space.wrap('zero')),space.wrap(0)) - self.assertEqual_w(space.getitem(d,space.wrap('two')),space.wrap(2)) - self.assertRaises_w(self.space.w_KeyError, + assert self.space.eq_w(space.getitem(d,space.wrap('zero')),space.wrap(0)) + assert self.space.eq_w(space.getitem(d,space.wrap('two')),space.wrap(2)) + self.space.raises_w(self.space.w_KeyError, space.getitem,d,space.wrap('one')) def test_wrap_dict(self): - self.assert_(isinstance(self.space.wrap({}), W_DictObject)) + assert isinstance(self.space.wrap({}), W_DictObject) def test_dict_compare(self): @@ -56,13 +51,13 @@ w0, w1, w2, w3 = map(w, range(4)) wd1 = self.space.newdict([(w0, w1), (w2, w3)]) wd2 = self.space.newdict([(w2, w3), (w0, w1)]) - self.assertEqual_w(wd1, wd2) + assert self.space.eq_w(wd1, wd2) wd3 = self.space.newdict([(w2, w2), (w0, w1)]) - self.assertNotEqual_w(wd1, wd3) + assert not self.space.eq_w(wd1, wd3) wd4 = self.space.newdict([(w3, w3), (w0, w1)]) - self.assertNotEqual_w(wd1, wd4) + assert not self.space.eq_w(wd1, wd4) wd5 = self.space.newdict([(w3, w3)]) - self.assertNotEqual_w(wd1, wd4) + assert not self.space.eq_w(wd1, wd4) def test_dict_call(self): space = self.space @@ -73,16 +68,16 @@ def deepwrap(lp): return [[w(a),w(b)] for a,b in lp] d = mydict() - self.assertEqual_w(d, w({})) + assert self.space.eq_w(d, w({})) args = w(([['a',2],[23,45]],)) d = mydict(args) - self.assertEqual_w(d, wd(deepwrap([['a',2],[23,45]]))) + assert self.space.eq_w(d, wd(deepwrap([['a',2],[23,45]]))) d = mydict(args, w({'a':33, 'b':44})) - self.assertEqual_w(d, wd(deepwrap([['a',33],['b',44],[23,45]]))) + assert self.space.eq_w(d, wd(deepwrap([['a',33],['b',44],[23,45]]))) d = mydict(w_kwds=w({'a':33, 'b':44})) - self.assertEqual_w(d, wd(deepwrap([['a',33],['b',44]]))) - self.assertRaises_w(space.w_TypeError, mydict, w((23,))) - self.assertRaises_w(space.w_ValueError, mydict, w(([[1,2,3]],))) + assert self.space.eq_w(d, wd(deepwrap([['a',33],['b',44]]))) + self.space.raises_w(space.w_TypeError, mydict, w((23,))) + self.space.raises_w(space.w_ValueError, mydict, w(([[1,2,3]],))) def test_dict_pop(self): space = self.space @@ -94,19 +89,19 @@ dd = mydict(w_kwds=w({"1":2, "3":4})) # means d.copy() pop = space.getattr(dd, w("pop")) result = space.call_function(pop, w("1")) - self.assertEqual_w(result, w(2)) - self.assertEqual_w(space.len(dd), w(1)) + assert self.space.eq_w(result, w(2)) + assert self.space.eq_w(space.len(dd), w(1)) dd = mydict(w_kwds=w({"1":2, "3":4})) # means d.copy() pop = space.getattr(dd, w("pop")) result = space.call_function(pop, w("1"), w(44)) - self.assertEqual_w(result, w(2)) - self.assertEqual_w(space.len(dd), w(1)) + assert self.space.eq_w(result, w(2)) + assert self.space.eq_w(space.len(dd), w(1)) result = space.call_function(pop, w("1"), w(44)) - self.assertEqual_w(result, w(44)) - self.assertEqual_w(space.len(dd), w(1)) + assert self.space.eq_w(result, w(44)) + assert self.space.eq_w(space.len(dd), w(1)) - self.assertRaises_w(space.w_KeyError, space.call_function, pop, w(33)) + self.space.raises_w(space.w_KeyError, space.call_function, pop, w(33)) def test_get(self): space = self.space @@ -115,142 +110,139 @@ return space.call(space.w_dict, w_args, w_kwds) d = mydict(w_kwds=w({"1":2, "3":4})) get = space.getattr(d, w("get")) - self.assertEqual_w(space.call_function(get, w("1")), w(2)) - self.assertEqual_w(space.call_function(get, w("1"), w(44)), w(2)) - self.assertEqual_w(space.call_function(get, w("33")), w(None)) - self.assertEqual_w(space.call_function(get, w("33"), w(44)), w(44)) + assert self.space.eq_w(space.call_function(get, w("1")), w(2)) + assert self.space.eq_w(space.call_function(get, w("1"), w(44)), w(2)) + assert self.space.eq_w(space.call_function(get, w("33")), w(None)) + assert self.space.eq_w(space.call_function(get, w("33"), w(44)), w(44)) -class Test_DictObject(testit.AppTestCase): +class AppTest_DictObject: - def setUp(self): - self.space = testit.objspace('std') - def test_equality(self): d = {1:2} f = {1:2} - self.assert_(d == f) - self.assert_(d != {1:3}) + assert d == f + assert d != {1:3} def test_clear(self): d = {1:2, 3:4} d.clear() - self.assertEqual(len(d), 0) + assert len(d) == 0 def test_copy(self): d = {1:2, 3:4} dd = d.copy() - self.assertEqual(d, dd) - self.failIf(d is dd) + assert d == dd + assert not d is dd def tooslow_test_get(self): d = {1:2, 3:4} - self.assertEqual(d.get(1), 2) - self.assertEqual(d.get(1,44), 2) - self.assertEqual(d.get(33), None) - self.assertEqual(d.get(33,44), 44) + assert d.get(1) == 2 + assert d.get(1,44) == 2 + assert d.get(33) == None + assert d.get(33,44) == 44 def tooslow_test_pop(self): d = {1:2, 3:4} dd = d.copy() result = dd.pop(1) - self.assertEqual(result, 2) - self.assertEqual(len(dd), 1) + assert result == 2 + assert len(dd) == 1 dd = d.copy() result = dd.pop(1, 44) - self.assertEqual(result, 2) - self.assertEqual(len(dd), 1) + assert result == 2 + assert len(dd) == 1 result = dd.pop(1, 44) - self.assertEqual(result, 44) - self.assertEqual(len(dd), 1) - self.assertRaises(KeyError, dd.pop, 33) + assert result == 44 + assert len(dd) == 1 + raises(KeyError, dd.pop, 33) def test_has_key(self): d = {1:2, 3:4} - self.failUnless(d.has_key(1)) - self.failIf(d.has_key(33)) + assert d.has_key(1) + assert not d.has_key(33) def test_items(self): d = {1:2, 3:4} its = d.items() its.sort() - self.assertEqual(its, [(1,2),(3,4)]) + assert its == [(1,2),(3,4)] def test_iteritems(self): d = {1:2, 3:4} dd = d.copy() for k, v in d.iteritems(): - self.assertEqual(v, dd[k]) + assert v == dd[k] del dd[k] - self.failIf(dd) + assert not dd def test_iterkeys(self): d = {1:2, 3:4} dd = d.copy() for k in d.iterkeys(): del dd[k] - self.failIf(dd) + assert not dd def test_itervalues(self): d = {1:2, 3:4} values = [] for k in d.itervalues(): values.append(k) - self.assertEqual(values, d.values()) + assert values == d.values() def test_keys(self): d = {1:2, 3:4} kys = d.keys() kys.sort() - self.assertEqual(kys, [1,3]) + assert kys == [1,3] def test_popitem(self): d = {1:2, 3:4} it = d.popitem() - self.assertEqual(len(d), 1) - self.failUnless(it==(1,2) or it==(3,4)) + assert len(d) == 1 + assert it==(1,2) or it==(3,4) it1 = d.popitem() - self.assertEqual(len(d), 0) - self.failUnless((it!=it1) and (it1==(1,2) or it1==(3,4))) + assert len(d) == 0 + assert (it!=it1) and (it1==(1,2) or it1==(3,4)) def test_setdefault(self): d = {1:2, 3:4} dd = d.copy() x = dd.setdefault(1, 99) - self.assertEqual(d, dd) - self.assertEqual(x, 2) + assert d == dd + assert x == 2 x = dd.setdefault(33, 99) d[33] = 99 - self.assertEqual(d, dd) - self.assertEqual(x, 99) + assert d == dd + assert x == 99 def test_update(self): d = {1:2, 3:4} dd = d.copy() d.update({}) - self.assertEqual(d, dd) + assert d == dd d.update({3:5, 6:7}) - self.assertEqual(d, {1:2, 3:5, 6:7}) + assert d == {1:2, 3:5, 6:7} def test_values(self): d = {1:2, 3:4} vals = d.values() vals.sort() - self.assertEqual(vals, [2,4]) + assert vals == [2,4] def test_eq(self): d1 = {1:2, 3:4} d2 = {1:2, 3:4} d3 = {1:2} bool = d1 == d2 - self.assertEqual(bool, True) + assert bool == True bool = d1 == d3 - self.assertEqual(bool, False) + assert bool == False bool = d1 != d2 - self.assertEqual(bool, False) + assert bool == False bool = d1 != d3 - self.assertEqual(bool, True) + assert bool == True def test_lt(self): d1 = {1:2, 3:4} @@ -258,36 +250,36 @@ d3 = {1:2, 3:5} d4 = {1:2} bool = d1 < d2 - self.assertEqual(bool, False) + assert bool == False bool = d1 < d3 - self.assertEqual(bool, True) + assert bool == True bool = d1 < d4 - self.assertEqual(bool, False) + assert bool == False def test_str_repr(self): - self.assertEqual('{}', str({})) - self.assertEqual('{1: 2}', str({1: 2})) - self.assertEqual("{'ba': 'bo'}", str({'ba': 'bo'})) + assert '{}' == str({}) + assert '{1: 2}' == str({1: 2}) + assert "{'ba': 'bo'}" == str({'ba': 'bo'}) # NOTE: the string repr depends on hash values of 1 and 'ba'!!! ok_reprs = ["{1: 2, 'ba': 'bo'}", "{'ba': 'bo', 1: 2}"] - self.assert_(str({1: 2, 'ba': 'bo'}) in ok_reprs) - self.assertEqual('{}', repr({})) - self.assertEqual('{1: 2}', repr({1: 2})) - self.assertEqual("{'ba': 'bo'}", repr({'ba': 'bo'})) - self.assert_(str({1: 2, 'ba': 'bo'}) in ok_reprs) + assert str({1: 2, 'ba': 'bo'}) in ok_reprs + assert '{}' == repr({}) + assert '{1: 2}' == repr({1: 2}) + assert "{'ba': 'bo'}" == repr({'ba': 'bo'}) + assert str({1: 2, 'ba': 'bo'}) in ok_reprs def test_new(self): d = dict() - self.assertEqual(d, {}) + assert d == {} args = [['a',2], [23,45]] d = dict(args) - self.assertEqual(d, {'a':2, 23:45}) + assert d == {'a':2, 23:45} d = dict(args, a=33, b=44) - self.assertEqual(d, {'a':33, 'b':44, 23:45}) + assert d == {'a':33, 'b':44, 23:45} d = dict(a=33, b=44) - self.assertEqual(d, {'a':33, 'b':44}) + assert d == {'a':33, 'b':44} d = dict({'a':33, 'b':44}) - self.assertEqual(d, {'a':33, 'b':44}) + assert d == {'a':33, 'b':44} try: d = dict(23) except (TypeError, ValueError): pass else: self.fail("dict(23) should raise!") @@ -296,10 +288,10 @@ else: self.fail("dict([[1,2,3]]) should raise!") def test_fromkeys(self): - self.assertEquals({}.fromkeys([1, 2], 1), {1: 1, 2: 1}) - self.assertEquals({}.fromkeys([1, 2]), {1: None, 2: None}) - self.assertEquals({}.fromkeys([]), {}) - self.assertEquals({1: 0, 2: 0, 3: 0}.fromkeys([1, '1'], 'j'), + assert {}.fromkeys([1, 2], 1) == {1: 1, 2: 1} + assert {}.fromkeys([1, 2]) == {1: None, 2: None} + assert {}.fromkeys([]) == {} + assert {1: 0, 2: 0, 3: 0}.fromkeys([1, '1'], 'j') == ( {1: 'j', '1': 'j'}) # the minimal 'space' needed to use a W_DictObject @@ -317,14 +309,11 @@ from pypy.objspace.std.dictobject import getitem__Dict_ANY, setitem__Dict_ANY_ANY -class TestDictImplementation(testit.TestCase): +class TestDictImplementation: - def setUp(self): + def setup_method(self,method): self.space = FakeSpace() - def tearDown(self): - pass - def test_stressdict(self): from random import randint d = W_DictObject(self.space, []) @@ -335,8 +324,4 @@ setitem__Dict_ANY_ANY(self.space, d, x, i) pydict[x] = i for x in pydict: - self.assertEqual(pydict[x], getitem__Dict_ANY(self.space, d, x)) - - -if __name__ == '__main__': - testit.main() + assert pydict[x] == getitem__Dict_ANY(self.space, d, x) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_dictproxy.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_dictproxy.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_dictproxy.py Mon Jan 10 17:19:39 2005 @@ -1,25 +1,20 @@ import autopath -from pypy.tool import testit -class TestUserObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') +objspacename = 'std' +class AppTestUserObject: def test_dictproxy(self): class NotEmpty: a = 1 - self.assertEquals(isinstance(NotEmpty.__dict__, dict), False) - self.assert_('a' in NotEmpty.__dict__) - self.assert_('a' in NotEmpty.__dict__.keys()) - self.assert_('b' not in NotEmpty.__dict__) - self.assert_(isinstance(NotEmpty.__dict__.copy(), dict)) - self.assert_(NotEmpty.__dict__ == NotEmpty.__dict__.copy()) + assert isinstance(NotEmpty.__dict__, dict) == False + assert 'a' in NotEmpty.__dict__ + assert 'a' in NotEmpty.__dict__.keys() + assert 'b' not in NotEmpty.__dict__ + assert isinstance(NotEmpty.__dict__.copy(), dict) + assert NotEmpty.__dict__ == NotEmpty.__dict__.copy() try: NotEmpty.__dict__['b'] = 1 except: pass else: raise AssertionError, 'this should not have been writable' - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_instmethobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_instmethobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_instmethobject.py Mon Jan 10 17:19:39 2005 @@ -1,37 +1,32 @@ import autopath -from pypy.tool import testit # NB. instmethobject.py has been removed, # but the following tests still make sense -class TestInstMethObjectApp(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') +objspacename = 'std' +class AppTestInstMethObjectApp: def test_callBound(self): boundMethod = [1,2,3].__len__ - self.assertEquals(boundMethod(), 3) - self.assertRaises(TypeError, boundMethod, 333) + assert boundMethod() == 3 + raises(TypeError, boundMethod, 333) def test_callUnbound(self): unboundMethod = list.__len__ - self.assertEquals(unboundMethod([1,2,3]), 3) - self.assertRaises(TypeError, unboundMethod) - self.assertRaises(TypeError, unboundMethod, 333) - self.assertRaises(TypeError, unboundMethod, [1,2,3], 333) + assert unboundMethod([1,2,3]) == 3 + raises(TypeError, unboundMethod) + raises(TypeError, unboundMethod, 333) + raises(TypeError, unboundMethod, [1,2,3], 333) def test_getBound(self): def f(l,x): return l[x+1] bound = f.__get__('abcdef') - self.assertEquals(bound(1), 'c') - self.assertRaises(TypeError, bound) - self.assertRaises(TypeError, bound, 2, 3) + assert bound(1) == 'c' + raises(TypeError, bound) + raises(TypeError, bound, 2, 3) def test_getUnbound(self): def f(l,x): return l[x+1] unbound = f.__get__(None, str) - self.assertEquals(unbound('abcdef', 2), 'd') - self.assertRaises(TypeError, unbound) - self.assertRaises(TypeError, unbound, 4) - self.assertRaises(TypeError, unbound, 4, 5) - -if __name__ == '__main__': - testit.main() + assert unbound('abcdef', 2) == 'd' + raises(TypeError, unbound) + raises(TypeError, unbound, 4) + raises(TypeError, unbound, 4, 5) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_iterobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_iterobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_iterobject.py Mon Jan 10 17:19:39 2005 @@ -1,26 +1,21 @@ import autopath from pypy.objspace.std.iterobject import W_SeqIterObject from pypy.interpreter.error import OperationError -from pypy.tool import testit -class TestW_IterObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_IterObject: def body3(self, w_iter): w = self.space.wrap - self.assertEqual_w(self.space.next(w_iter), w(5)) - self.assertEqual_w(self.space.next(w_iter), w(3)) - self.assertEqual_w(self.space.next(w_iter), w(99)) + assert self.space.eq_w(self.space.next(w_iter), w(5)) + assert self.space.eq_w(self.space.next(w_iter), w(3)) + assert self.space.eq_w(self.space.next(w_iter), w(99)) self.body0(w_iter) def body0(self, w_iter): - self.assertRaises(OperationError, self.space.next, w_iter) - self.assertRaises(OperationError, self.space.next, w_iter) + raises(OperationError, self.space.next, w_iter) + raises(OperationError, self.space.next, w_iter) def test_iter(self): w = self.space.wrap @@ -44,31 +39,24 @@ w_iter = self.space.iter(w_list) self.body0(w_iter) -class TestW_IterObjectApp(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') - +class AppTestW_IterObjectApp: def test_user_iter(self): class C: def next(self): raise StopIteration def __iter__(self): return self - self.assertEquals(list(C()), []) + assert list(C()) == [] def test_iter_getitem(self): class C: def __getitem__(self, i): return range(2)[i] - self.assertEquals(list(C()), range(2)) + assert list(C()) == range(2) def test_iter_fail_noseq(self): class C: pass - self.assertRaises(TypeError, + raises(TypeError, iter, C()) - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_listobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_listobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_listobject.py Mon Jan 10 17:19:39 2005 @@ -2,69 +2,64 @@ import autopath from pypy.objspace.std.listobject import W_ListObject from pypy.interpreter.error import OperationError -from pypy.tool import testit -class TestW_ListObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_ListObject: def test_is_true(self): w = self.space.wrap w_list = W_ListObject(self.space, []) - self.assertEqual(self.space.is_true(w_list), False) + assert self.space.is_true(w_list) == False w_list = W_ListObject(self.space, [w(5)]) - self.assertEqual(self.space.is_true(w_list), True) + assert self.space.is_true(w_list) == True w_list = W_ListObject(self.space, [w(5), w(3)]) - self.assertEqual(self.space.is_true(w_list), True) + assert self.space.is_true(w_list) == True def test_len(self): w = self.space.wrap w_list = W_ListObject(self.space, []) - self.assertEqual_w(self.space.len(w_list), w(0)) + assert self.space.eq_w(self.space.len(w_list), w(0)) w_list = W_ListObject(self.space, [w(5)]) - self.assertEqual_w(self.space.len(w_list), w(1)) + assert self.space.eq_w(self.space.len(w_list), w(1)) w_list = W_ListObject(self.space, [w(5), w(3), w(99)]*111) - self.assertEqual_w(self.space.len(w_list), w(333)) + assert self.space.eq_w(self.space.len(w_list), w(333)) def test_getitem(self): w = self.space.wrap w_list = W_ListObject(self.space, [w(5), w(3)]) - self.assertEqual_w(self.space.getitem(w_list, w(0)), w(5)) - self.assertEqual_w(self.space.getitem(w_list, w(1)), w(3)) - self.assertEqual_w(self.space.getitem(w_list, w(-2)), w(5)) - self.assertEqual_w(self.space.getitem(w_list, w(-1)), w(3)) - self.assertRaises_w(self.space.w_IndexError, + assert self.space.eq_w(self.space.getitem(w_list, w(0)), w(5)) + assert self.space.eq_w(self.space.getitem(w_list, w(1)), w(3)) + assert self.space.eq_w(self.space.getitem(w_list, w(-2)), w(5)) + assert self.space.eq_w(self.space.getitem(w_list, w(-1)), w(3)) + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_list, w(2)) - self.assertRaises_w(self.space.w_IndexError, + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_list, w(42)) - self.assertRaises_w(self.space.w_IndexError, + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_list, w(-3)) def test_iter(self): w = self.space.wrap w_list = W_ListObject(self.space, [w(5), w(3), w(99)]) w_iter = self.space.iter(w_list) - self.assertEqual_w(self.space.next(w_iter), w(5)) - self.assertEqual_w(self.space.next(w_iter), w(3)) - self.assertEqual_w(self.space.next(w_iter), w(99)) - self.assertRaises(OperationError, self.space.next, w_iter) - self.assertRaises(OperationError, self.space.next, w_iter) + assert self.space.eq_w(self.space.next(w_iter), w(5)) + assert self.space.eq_w(self.space.next(w_iter), w(3)) + assert self.space.eq_w(self.space.next(w_iter), w(99)) + raises(OperationError, self.space.next, w_iter) + raises(OperationError, self.space.next, w_iter) def test_contains(self): w = self.space.wrap w_list = W_ListObject(self.space, [w(5), w(3), w(99)]) - self.assertEqual_w(self.space.contains(w_list, w(5)), + assert self.space.eq_w(self.space.contains(w_list, w(5)), self.space.w_True) - self.assertEqual_w(self.space.contains(w_list, w(99)), + assert self.space.eq_w(self.space.contains(w_list, w(99)), self.space.w_True) - self.assertEqual_w(self.space.contains(w_list, w(11)), + assert self.space.eq_w(self.space.contains(w_list, w(11)), self.space.w_False) - self.assertEqual_w(self.space.contains(w_list, w_list), + assert self.space.eq_w(self.space.contains(w_list, w_list), self.space.w_False) def test_getslice(self): @@ -74,7 +69,7 @@ w_slice = self.space.newslice(w(start), w(stop), w(step)) w_list = W_ListObject(self.space, [w(i) for i in testlist]) w_result = self.space.getitem(w_list, w_slice) - self.assertEqual(self.space.unwrap(w_result), expected) + assert self.space.unwrap(w_result) == expected for testlist in [[], [5,3,99]]: for start in [-2, 0, 1, 10]: @@ -96,7 +91,7 @@ w_lhslist = W_ListObject(self.space, [w(i) for i in lhslist]) w_rhslist = W_ListObject(self.space, [w(i) for i in rhslist]) self.space.setitem(w_lhslist, w_slice, w_rhslist) - self.assertEqual(self.space.unwrap(w_lhslist), expected) + assert self.space.unwrap(w_lhslist) == expected test1([5,7,1,4], 1, 3, [9,8], [5,9,8,4]) @@ -111,14 +106,14 @@ w_list0 = W_ListObject(self.space, []) w_list1 = W_ListObject(self.space, [w(5), w(3), w(99)]) w_list2 = W_ListObject(self.space, [w(-7)] * 111) - self.assertEqual_w(self.space.add(w_list1, w_list1), + assert self.space.eq_w(self.space.add(w_list1, w_list1), W_ListObject(self.space, [w(5), w(3), w(99), w(5), w(3), w(99)])) - self.assertEqual_w(self.space.add(w_list1, w_list2), + assert self.space.eq_w(self.space.add(w_list1, w_list2), W_ListObject(self.space, [w(5), w(3), w(99)] + [w(-7)] * 111)) - self.assertEqual_w(self.space.add(w_list1, w_list0), w_list1) - self.assertEqual_w(self.space.add(w_list0, w_list2), w_list2) + assert self.space.eq_w(self.space.add(w_list1, w_list0), w_list1) + assert self.space.eq_w(self.space.add(w_list0, w_list2), w_list2) def test_mul(self): # only testing right mul at the moment @@ -128,10 +123,10 @@ w_lis = W_ListObject(self.space, [arg]) w_lis3 = W_ListObject(self.space, [arg]*n) w_res = self.space.mul(w_lis, w(n)) - self.assertEqual_w(w_lis3, w_res) + assert self.space.eq_w(w_lis3, w_res) # commute w_res = self.space.mul(w(n), w_lis) - self.assertEqual_w(w_lis3, w_res) + assert self.space.eq_w(w_lis3, w_res) def test_setitem(self): w = self.space.wrap @@ -139,12 +134,12 @@ w_exp1 = W_ListObject(self.space, [w(5), w(7)]) w_exp2 = W_ListObject(self.space, [w(8), w(7)]) self.space.setitem(w_list, w(1), w(7)) - self.assertEqual_w(w_exp1, w_list) + assert self.space.eq_w(w_exp1, w_list) self.space.setitem(w_list, w(-2), w(8)) - self.assertEqual_w(w_exp2, w_list) - self.assertRaises_w(self.space.w_IndexError, + assert self.space.eq_w(w_exp2, w_list) + self.space.raises_w(self.space.w_IndexError, self.space.setitem, w_list, w(2), w(5)) - self.assertRaises_w(self.space.w_IndexError, + self.space.raises_w(self.space.w_IndexError, self.space.setitem, w_list, w(-3), w(5)) def test_eq(self): @@ -155,15 +150,15 @@ w_list2 = W_ListObject(self.space, [w(5), w(3), w(99)]) w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) - self.assertEqual_w(self.space.eq(w_list0, w_list1), + assert self.space.eq_w(self.space.eq(w_list0, w_list1), self.space.w_False) - self.assertEqual_w(self.space.eq(w_list1, w_list0), + assert self.space.eq_w(self.space.eq(w_list1, w_list0), self.space.w_False) - self.assertEqual_w(self.space.eq(w_list1, w_list1), + assert self.space.eq_w(self.space.eq(w_list1, w_list1), self.space.w_True) - self.assertEqual_w(self.space.eq(w_list1, w_list2), + assert self.space.eq_w(self.space.eq(w_list1, w_list2), self.space.w_True) - self.assertEqual_w(self.space.eq(w_list2, w_list3), + assert self.space.eq_w(self.space.eq(w_list2, w_list3), self.space.w_False) def test_ne(self): w = self.space.wrap @@ -173,15 +168,15 @@ w_list2 = W_ListObject(self.space, [w(5), w(3), w(99)]) w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) - self.assertEqual_w(self.space.ne(w_list0, w_list1), + assert self.space.eq_w(self.space.ne(w_list0, w_list1), self.space.w_True) - self.assertEqual_w(self.space.ne(w_list1, w_list0), + assert self.space.eq_w(self.space.ne(w_list1, w_list0), self.space.w_True) - self.assertEqual_w(self.space.ne(w_list1, w_list1), + assert self.space.eq_w(self.space.ne(w_list1, w_list1), self.space.w_False) - self.assertEqual_w(self.space.ne(w_list1, w_list2), + assert self.space.eq_w(self.space.ne(w_list1, w_list2), self.space.w_False) - self.assertEqual_w(self.space.ne(w_list2, w_list3), + assert self.space.eq_w(self.space.ne(w_list2, w_list3), self.space.w_True) def test_lt(self): w = self.space.wrap @@ -192,17 +187,17 @@ w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) w_list4 = W_ListObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.lt(w_list0, w_list1), + assert self.space.eq_w(self.space.lt(w_list0, w_list1), self.space.w_True) - self.assertEqual_w(self.space.lt(w_list1, w_list0), + assert self.space.eq_w(self.space.lt(w_list1, w_list0), self.space.w_False) - self.assertEqual_w(self.space.lt(w_list1, w_list1), + assert self.space.eq_w(self.space.lt(w_list1, w_list1), self.space.w_False) - self.assertEqual_w(self.space.lt(w_list1, w_list2), + assert self.space.eq_w(self.space.lt(w_list1, w_list2), self.space.w_False) - self.assertEqual_w(self.space.lt(w_list2, w_list3), + assert self.space.eq_w(self.space.lt(w_list2, w_list3), self.space.w_True) - self.assertEqual_w(self.space.lt(w_list4, w_list3), + assert self.space.eq_w(self.space.lt(w_list4, w_list3), self.space.w_True) def test_ge(self): @@ -214,17 +209,17 @@ w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) w_list4 = W_ListObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.ge(w_list0, w_list1), + assert self.space.eq_w(self.space.ge(w_list0, w_list1), self.space.w_False) - self.assertEqual_w(self.space.ge(w_list1, w_list0), + assert self.space.eq_w(self.space.ge(w_list1, w_list0), self.space.w_True) - self.assertEqual_w(self.space.ge(w_list1, w_list1), + assert self.space.eq_w(self.space.ge(w_list1, w_list1), self.space.w_True) - self.assertEqual_w(self.space.ge(w_list1, w_list2), + assert self.space.eq_w(self.space.ge(w_list1, w_list2), self.space.w_True) - self.assertEqual_w(self.space.ge(w_list2, w_list3), + assert self.space.eq_w(self.space.ge(w_list2, w_list3), self.space.w_False) - self.assertEqual_w(self.space.ge(w_list4, w_list3), + assert self.space.eq_w(self.space.ge(w_list4, w_list3), self.space.w_False) def test_gt(self): @@ -236,17 +231,17 @@ w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) w_list4 = W_ListObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.gt(w_list0, w_list1), + assert self.space.eq_w(self.space.gt(w_list0, w_list1), self.space.w_False) - self.assertEqual_w(self.space.gt(w_list1, w_list0), + assert self.space.eq_w(self.space.gt(w_list1, w_list0), self.space.w_True) - self.assertEqual_w(self.space.gt(w_list1, w_list1), + assert self.space.eq_w(self.space.gt(w_list1, w_list1), self.space.w_False) - self.assertEqual_w(self.space.gt(w_list1, w_list2), + assert self.space.eq_w(self.space.gt(w_list1, w_list2), self.space.w_False) - self.assertEqual_w(self.space.gt(w_list2, w_list3), + assert self.space.eq_w(self.space.gt(w_list2, w_list3), self.space.w_False) - self.assertEqual_w(self.space.gt(w_list4, w_list3), + assert self.space.eq_w(self.space.gt(w_list4, w_list3), self.space.w_False) def test_le(self): @@ -258,92 +253,86 @@ w_list3 = W_ListObject(self.space, [w(5), w(3), w(99), w(-1)]) w_list4 = W_ListObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.le(w_list0, w_list1), + assert self.space.eq_w(self.space.le(w_list0, w_list1), self.space.w_True) - self.assertEqual_w(self.space.le(w_list1, w_list0), + assert self.space.eq_w(self.space.le(w_list1, w_list0), self.space.w_False) - self.assertEqual_w(self.space.le(w_list1, w_list1), + assert self.space.eq_w(self.space.le(w_list1, w_list1), self.space.w_True) - self.assertEqual_w(self.space.le(w_list1, w_list2), + assert self.space.eq_w(self.space.le(w_list1, w_list2), self.space.w_True) - self.assertEqual_w(self.space.le(w_list2, w_list3), + assert self.space.eq_w(self.space.le(w_list2, w_list3), self.space.w_True) - self.assertEqual_w(self.space.le(w_list4, w_list3), + assert self.space.eq_w(self.space.le(w_list4, w_list3), self.space.w_True) -class AppTestW_ListObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') - +class AppTestW_ListObject: def test_explicit_new_init(self): l = l0 = list.__new__(list) l.__init__([1,2]) - self.assert_(l is l0) - self.assertEquals(l,[1,2]) + assert l is l0 + assert l ==[1,2] list.__init__(l,[1,2,3]) - self.assert_(l is l0) - self.assertEquals(l,[1,2,3]) + assert l is l0 + assert l ==[1,2,3] def test_extend_list(self): l = l0 = [1] l.extend([2]) - self.assert_(l is l0) - self.assertEquals(l, [1,2]) + assert l is l0 + assert l == [1,2] def test_extend_tuple(self): l = l0 = [1] l.extend((2,)) - self.assert_(l is l0) - self.assertEquals(l, [1,2]) + assert l is l0 + assert l == [1,2] def test_sort(self): l = l0 = [1, 5, 3, 0] l.sort() - self.assert_(l is l0) - self.assertEquals(l, [0, 1, 3, 5]) + assert l is l0 + assert l == [0, 1, 3, 5] l = l0 = [] l.sort() - self.assert_(l is l0) - self.assertEquals(l, []) + assert l is l0 + assert l == [] l = l0 = [1] l.sort() - self.assert_(l is l0) - self.assertEquals(l, [1]) + assert l is l0 + assert l == [1] def test_sort_cmp(self): def lencmp(a,b): return cmp(len(a), len(b)) l = [ 'a', 'fiver', 'tre', '' ] l.sort(lencmp) - self.assertEquals(l, ['', 'a', 'tre', 'fiver']) + assert l == ['', 'a', 'tre', 'fiver'] l = [] l.sort(lencmp) - self.assertEquals(l, []) + assert l == [] l = [ 'a' ] l.sort(lencmp) - self.assertEquals(l, [ 'a' ]) + assert l == [ 'a' ] def test_extended_slice(self): l = range(10) del l[::2] - self.assertEquals(l,[1,3,5,7,9]) + assert l ==[1,3,5,7,9] l[-2::-1] = l[:-1] - self.assertEquals(l,[7,5,3,1,9]) + assert l ==[7,5,3,1,9] del l[-1:2:-1] - self.assertEquals(l,[7,5,3]) + assert l ==[7,5,3] del l[:2] - self.assertEquals(l,[3]) + assert l ==[3] def test_delall(self): l = l0 = [1,2,3] del l[:] - self.assert_(l is l0) - self.assertEquals(l, []) + assert l is l0 + assert l == [] def test_iadd(self): l = l0 = [1,2,3] l += [4,5] - self.assert_(l is l0) - self.assertEquals(l, [1,2,3,4,5]) - -if __name__ == '__main__': - testit.main() + assert l is l0 + assert l == [1,2,3,4,5] Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_multimethod.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_multimethod.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_multimethod.py Mon Jan 10 17:19:39 2005 @@ -1,11 +1,12 @@ import autopath from pypy.objspace.std.multimethod import * -from pypy.tool import testit BoundMultiMethod.ASSERT_BASE_TYPE = object +objspacename = 'std' + class X: def __init__(self, value): self.value = value @@ -90,60 +91,55 @@ return x -class TestMultiMethod(testit.TestCase): - def setUp(self): +class TestMultiMethod: + def setup_method(self,method): # only run when testing stdobjectspace - #XXX removed: testit.objspace('std') + #XXX removed: self.space self.space = FakeObjSpace() def test_non_delegate(self): space = self.space r = space.add(X(2), X(5)) - self.assertEquals(repr(r), "('add_x_x', , )") + assert repr(r) == "('add_x_x', , )" r = space.add(X(3), Y(4)) - self.assertEquals(repr(r), "('add_x_y', , )") + assert repr(r) == "('add_x_y', , )" r = space.add(Y(0), Y(20)) - self.assertEquals(repr(r), "('add_y_y', , )") + assert repr(r) == "('add_y_y', , )" r = space.add(w(-3), w([7,6,5])) - self.assertEquals(repr(r), "('add_int_any', -3, [7, 6, 5])") + assert repr(r) == "('add_int_any', -3, [7, 6, 5])" r = space.add(w(5), w("test")) - self.assertEquals(repr(r), "('add_int_string', 5, 'test')") + assert repr(r) == "('add_int_string', 5, 'test')" r = space.add(w("x"), w("y")) - self.assertEquals(repr(r), "('add_string_string', 'x', 'y')") + assert repr(r) == "('add_string_string', 'x', 'y')" def test_delegate_y_to_x(self): space = self.space r = space.add(Y(-1), X(7)) - self.assertEquals(repr(r), "('add_x_x', >, )") + assert repr(r) == "('add_x_x', >, )" r = space.add(Y(1), X(7)) - self.assertEquals(repr(r), "('add_x_x', >, )") + assert repr(r) == "('add_x_x', >, )" r = space.add(X(-3), Y(20)) - self.assertEquals(repr(r), "('add_x_x', , >)") + assert repr(r) == "('add_x_x', , >)" def test_no_operation_defined(self): space = self.space - self.assertRaises(OperationError, space.add, w([3]), w(4)) - self.assertRaises(OperationError, space.add, w(3.0), w('bla')) - #self.assertRaises(OperationError, space.add, X(0), w("spam")) - #self.assertRaises(OperationError, space.add, Y(666), w("egg")) + raises(OperationError, space.add, w([3]), w(4)) + raises(OperationError, space.add, w(3.0), w('bla')) + #raises(OperationError, space.add, X(0), w("spam")) + #raises(OperationError, space.add, Y(666), w("egg")) def test_delegate_x_to_str(self): space = self.space r = space.add(X(42), w("spam")) - self.assertEquals(repr(r), "('add_string_string', '!42', 'spam')") + assert repr(r) == "('add_string_string', '!42', 'spam')" r = space.add(Y(20), w("egg")) - self.assertEquals(repr(r), "('add_string_string', '!', 'egg')") - - - -if __name__ == '__main__': - testit.main() + assert repr(r) == "('add_string_string', '!', 'egg')" Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_noneobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_noneobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_noneobject.py Mon Jan 10 17:19:39 2005 @@ -1,25 +1,16 @@ import autopath -from pypy.tool import testit -class TestW_NoneObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_NoneObject: def test_equality(self): - self.assertEqual_w(self.space.w_None, self.space.w_None) + assert self.space.eq_w(self.space.w_None, self.space.w_None) def test_inequality(self): neresult = self.space.ne(self.space.w_None, self.space.w_None) - self.failIf_w(neresult) + assert not self.space.is_true(neresult) def test_false(self): - self.failIf_w(self.space.w_None) - - -if __name__ == '__main__': - testit.main() + assert not self.space.is_true(self.space.w_None) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_restricted_int.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_restricted_int.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_restricted_int.py Mon Jan 10 17:19:39 2005 @@ -1,18 +1,16 @@ import unittest import autopath -from pypy.tool import testit from pypy.objspace.std.restricted_int import * import sys maxint_mask = (sys.maxint*2 + 1) -class Test_r_int(testit.TestCase): +objspacename = 'std' - def setUp(self): - space = testit.objspace('std') +class Test_r_int: - def tearDown(self): - pass + def setup_method(self,method): + space = self.space def test__add__(self): self.binary_test(lambda x, y: x + y) @@ -21,8 +19,8 @@ def test__mul__(self): self.binary_test(lambda x, y: x * y) x = 3; y = [2] - self.assertEquals(x*y, r_int(x)*y) - self.assertEquals(y*x, y*r_int(x)) + assert x*y == r_int(x)*y + assert y*x == y*r_int(x) def test__div__(self): self.binary_test(lambda x, y: x // y) def test__mod__(self): @@ -53,7 +51,7 @@ for arg in (-10, -1, 0, 3, 12345): res = f(arg) cmp = f(r_int(arg)) - self.assertEquals(res, cmp) + assert res == cmp def binary_test(self, f, rargs = None): if not rargs: @@ -64,15 +62,12 @@ res = f(larg, rarg) left, right = types cmp = f(left(larg), right(rarg)) - self.assertEquals(res, cmp) + assert res == cmp -class Test_r_uint(testit.TestCase): +class Test_r_uint: - def setUp(self): - space = testit.objspace('std') - - def tearDown(self): - pass + def setup_method(self,method): + space = self.space def test__add__(self): self.binary_test(lambda x, y: x + y) @@ -81,8 +76,8 @@ def test__mul__(self): self.binary_test(lambda x, y: x * y) x = 3; y = [2] - self.assertEquals(x*y, r_uint(x)*y) - self.assertEquals(y*x, y*r_uint(x)) + assert x*y == r_uint(x)*y + assert y*x == y*r_uint(x) def test__div__(self): self.binary_test(lambda x, y: x // y) def test__mod__(self): @@ -114,7 +109,7 @@ for arg in (0, 3, 12345): res = f(arg) & maxint_mask cmp = f(r_uint(arg)) - self.assertEquals(res, cmp) + assert res == cmp def binary_test(self, f, rargs = None): mask = maxint_mask @@ -130,7 +125,4 @@ res = res[0] & mask, res[1] & mask else: res = res & mask - self.assertEquals(res, cmp) - -if __name__ == '__main__': - testit.main() + assert res == cmp Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_sliceobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_sliceobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_sliceobject.py Mon Jan 10 17:19:39 2005 @@ -1,18 +1,13 @@ import autopath -from pypy.tool import testit -class TestW_SliceObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_SliceObject: def equal_indices(self, got, expected): - self.assertEqual(len(got), len(expected)) + assert len(got) == len(expected) for g, e in zip(got, expected): - self.assertEqual(g, e) + assert g == e def test_indices(self): from pypy.objspace.std import slicetype @@ -32,31 +27,25 @@ w = space.wrap w_None = space.w_None w_slice = space.newslice(w_None, w_None, w(0)) - self.assertRaises_w(space.w_ValueError, + self.space.raises_w(space.w_ValueError, slicetype.indices3, space, w_slice, 10) -class Test_SliceObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') - +class AppTest_SliceObject: def test_new(self): def cmp_slice(sl1, sl2): for attr in "start", "stop", "step": if getattr(sl1, attr) != getattr(sl2, attr): return False return True - self.assertRaises(TypeError, slice) - self.assertRaises(TypeError, slice, 1, 2, 3, 4) - self.failUnless(cmp_slice(slice(23), slice(None, 23, None))) - self.failUnless(cmp_slice(slice(23, 45), slice(23, 45, None))) + raises(TypeError, slice) + raises(TypeError, slice, 1, 2, 3, 4) + assert cmp_slice(slice(23), slice(None, 23, None)) + assert cmp_slice(slice(23, 45), slice(23, 45, None)) def test_indices(self): - self.assertEqual(slice(4,11,2).indices(28), (4, 11, 2)) - self.assertEqual(slice(4,11,2).indices(8), (4, 8, 2)) - self.assertEqual(slice(4,11,2).indices(2), (2, 2, 2)) - self.assertEqual(slice(11,4,-2).indices(28), (11, 4, -2)) - self.assertEqual(slice(11,4,-2).indices(8), (7, 4, -2)) - self.assertEqual(slice(11,4,-2).indices(2), (1, 2, -2)) - -if __name__ == '__main__': - testit.main() + assert slice(4,11,2).indices(28) == (4, 11, 2) + assert slice(4,11,2).indices(8) == (4, 8, 2) + assert slice(4,11,2).indices(2) == (2, 2, 2) + assert slice(11,4,-2).indices(28) == (11, 4, -2) + assert slice(11,4,-2).indices(8) == (7, 4, -2) + assert slice(11,4,-2).indices(2) == (1, 2, -2) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_stdobjspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_stdobjspace.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_stdobjspace.py Mon Jan 10 17:19:39 2005 @@ -1,23 +1,14 @@ import autopath -from pypy.tool import testit -class TestW_StdObjSpace(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_StdObjSpace: def test_wrap_wrap(self): - self.assertRaises(TypeError, + raises(TypeError, self.space.wrap, self.space.wrap(0)) def hopeful_test_exceptions(self): self.apptest("self.failUnless(issubclass(ArithmeticError, Exception))") self.apptest("self.failIf(issubclass(ArithmeticError, KeyError))") - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_stringformat.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_stringformat.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_stringformat.py Mon Jan 10 17:19:39 2005 @@ -1,83 +1,84 @@ import autopath -from pypy.tool import testit -class TestStringObjectWithDict(testit.AppTestCase): +objspacename = 'std' + +class AppTestStringObjectWithDict: def test_format_item(self): d = {'i': 23} - self.assertEquals('a23b', 'a%(i)sb' % d) - self.assertEquals('23b', '%(i)sb' % d) - self.assertEquals('a23', 'a%(i)s' % d) - self.assertEquals('23', '%(i)s' % d) + assert 'a23b' == 'a%(i)sb' % d + assert '23b' == '%(i)sb' % d + assert 'a23' == 'a%(i)s' % d + assert '23' == '%(i)s' % d def test_format_two_items(self): d = {'i': 23, 'j': 42} - self.assertEquals('a23b42c', 'a%(i)sb%(j)sc' % d) - self.assertEquals('a23b23c', 'a%(i)sb%(i)sc' % d) + assert 'a23b42c' == 'a%(i)sb%(j)sc' % d + assert 'a23b23c' == 'a%(i)sb%(i)sc' % d def test_format_percent(self): - self.assertEquals('a%b', 'a%%b' % {}) + assert 'a%b' == 'a%%b' % {} def test_format_empty_key(self): d = {'':42} - self.assertEquals('42', '%()s' % d) + assert '42' == '%()s' % d def test_format_wrong_char(self): d = {'i': 23} - self.assertRaises(ValueError, 'a%(i)Zb'.__mod__, d) + raises(ValueError, 'a%(i)Zb'.__mod__, d) def test_format_missing(self): d = {'i': 23} - self.assertRaises(KeyError, 'a%(x)sb'.__mod__, d) + raises(KeyError, 'a%(x)sb'.__mod__, d) -class TestStringObject(testit.AppTestCase): +class AppTestStringObject: def test_format_item(self): - self.assertEquals('a23b', 'a%sb' % 23) - self.assertEquals('23b', '%sb' % 23) - self.assertEquals('a23', 'a%s' % 23) - self.assertEquals('23', '%s' % 23) + assert 'a23b' == 'a%sb' % 23 + assert '23b' == '%sb' % 23 + assert 'a23' == 'a%s' % 23 + assert '23' == '%s' % 23 def test_format_percent(self): - self.assertEquals('a%b', 'a%%b' % ()) - self.assertEquals('%b', '%%b' % ()) - self.assertEquals('a%', 'a%%' % ()) - self.assertEquals('%', '%%' % ()) + assert 'a%b' == 'a%%b' % () + assert '%b' == '%%b' % () + assert 'a%' == 'a%%' % () + assert '%' == '%%' % () def test_format_too_much(self): - self.assertRaises(TypeError, '%s%s'.__mod__, ()) - self.assertRaises(TypeError, '%s%s'.__mod__, (23,)) + raises(TypeError, '%s%s'.__mod__, ()) + raises(TypeError, '%s%s'.__mod__, (23,)) def test_format_not_enough(self): - self.assertRaises(TypeError, '%s%s'.__mod__, (23,)*3) - self.assertRaises(TypeError, '%s%s'.__mod__, (23,)*4) + raises(TypeError, '%s%s'.__mod__, (23,)*3) + raises(TypeError, '%s%s'.__mod__, (23,)*4) def test_format_string(self): - self.assertEquals('23', '%s' % '23') - self.assertEquals("'23'", '%r' % '23') - self.assertRaises(TypeError, '%d'.__mod__, "23") + assert '23' == '%s' % '23' + assert "'23'" == '%r' % '23' + raises(TypeError, '%d'.__mod__, "23") def test_format_float(self): - self.assertEquals('23', '%d' % 23.456) - self.assertEquals('17', '%x' % 23.456) - self.assertEquals('23.456', '%s' % 23.456) + assert '23' == '%d' % 23.456 + assert '17' == '%x' % 23.456 + assert '23.456' == '%s' % 23.456 # for 'r' use a float that has an exact decimal rep: - self.assertEquals('23.125', '%r' % 23.125) + assert '23.125' == '%r' % 23.125 def test_format_int(self): - self.assertEquals('23', '%d' % 23) - self.assertEquals('17', '%x' % 23) - self.assertEquals('0x17', '%#x' % 23) - self.assertEquals('23', '%s' % 23) - self.assertEquals('23', '%r' % 23) + assert '23' == '%d' % 23 + assert '17' == '%x' % 23 + assert '0x17' == '%#x' % 23 + assert '23' == '%s' % 23 + assert '23' == '%r' % 23 def test_format_list(self): - self.assertEquals('<[1, 2]>', '<%s>' % [1,2]) - self.assertEquals('<[1, 2]-[3, 4]>', '<%s-%s>' % ([1,2], [3,4])) + assert '<[1, 2]>' == '<%s>' % [1,2] + assert '<[1, 2]-[3, 4]>' == '<%s-%s>' % ([1,2], [3,4]) def test_format_tuple(self): - self.assertEquals('<(1, 2)>', '<%s>' % ((1,2),)) - self.assertEquals('<(1, 2)-(3, 4)>', '<%s-%s>' % ((1,2), (3,4))) + assert '<(1, 2)>' == '<%s>' % ((1,2),) + assert '<(1, 2)-(3, 4)>' == '<%s-%s>' % ((1,2), (3,4)) def test_format_dict(self): @@ -92,55 +93,52 @@ # It is what CPython *does*, however. All software sucks. - self.assertEquals('<{1: 2}>', '<%s>' % {1:2}) - self.assertEquals('<{1: 2}-{3: 4}>', '<%s-%s>' % ({1:2}, {3:4})) + assert '<{1: 2}>' == '<%s>' % {1:2} + assert '<{1: 2}-{3: 4}>' == '<%s-%s>' % ({1:2}, {3:4}) def test_format_wrong_char(self): - self.assertRaises(ValueError, 'a%Zb'.__mod__, ((23,),)) + raises(ValueError, 'a%Zb'.__mod__, ((23,),)) def test_incomplete_format(self): - self.assertRaises(ValueError, '%'.__mod__, ((23,),)) + raises(ValueError, '%'.__mod__, ((23,),)) -class TestWidthPrec(testit.AppTestCase): +class AppTestWidthPrec: def test_width(self): - self.assertEquals("%3s" %'a', ' a') - self.assertEquals("%-3s"%'a', 'a ') + assert "%3s" %'a' == ' a' + assert "%-3s"%'a' == 'a ' def test_prec_string(self): - self.assertEquals("%.3s"%'a', 'a') - self.assertEquals("%.3s"%'abcde', 'abc') + assert "%.3s"%'a' == 'a' + assert "%.3s"%'abcde' == 'abc' def test_prec_width_string(self): - self.assertEquals("%5.3s" %'a', ' a') - self.assertEquals("%5.3s" %'abcde', ' abc') - self.assertEquals("%-5.3s"%'a', 'a ') - self.assertEquals("%-5.3s"%'abcde', 'abc ') + assert "%5.3s" %'a' == ' a' + assert "%5.3s" %'abcde' == ' abc' + assert "%-5.3s"%'a' == 'a ' + assert "%-5.3s"%'abcde' == 'abc ' def test_zero_pad(self): - self.assertEquals("%02d"%1, "01") - self.assertEquals("%05d"%1, "00001") - self.assertEquals("%-05d"%1, "1 ") - self.assertEquals("%04f"%2.25, "2.250000") - self.assertEquals("%05g"%2.25, "02.25") - self.assertEquals("%-05g"%2.25,"2.25 ") - self.assertEquals("%05s"%2.25, " 2.25") + assert "%02d"%1 == "01" + assert "%05d"%1 == "00001" + assert "%-05d"%1 == "1 " + assert "%04f"%2.25 == "2.250000" + assert "%05g"%2.25 == "02.25" + assert "%-05g"%2.25 =="2.25 " + assert "%05s"%2.25 == " 2.25" def test_star_width(self): - self.assertEquals("%*s" %( 5, 'abc'), ' abc') - self.assertEquals("%*s" %(-5, 'abc'), 'abc ') - self.assertEquals("%-*s"%( 5, 'abc'), 'abc ') - self.assertEquals("%-*s"%(-5, 'abc'), 'abc ') + assert "%*s" %( 5, 'abc') == ' abc' + assert "%*s" %(-5, 'abc') == 'abc ' + assert "%-*s"%( 5, 'abc') == 'abc ' + assert "%-*s"%(-5, 'abc') == 'abc ' def test_star_prec(self): - self.assertEquals("%.*s"%( 3, 'abc'), 'abc') - self.assertEquals("%.*s"%( 3, 'abcde'), 'abc') - self.assertEquals("%.*s"%(-3, 'abc'), '') + assert "%.*s"%( 3, 'abc') == 'abc' + assert "%.*s"%( 3, 'abcde') == 'abc' + assert "%.*s"%(-3, 'abc') == '' def test_star_width_prec(self): - self.assertEquals("%*.*s"%( 5, 3, 'abc'), ' abc') - self.assertEquals("%*.*s"%( 5, 3, 'abcde'), ' abc') - self.assertEquals("%*.*s"%(-5, 3, 'abcde'), 'abc ') - -if __name__ == '__main__': - testit.main() + assert "%*.*s"%( 5, 3, 'abc') == ' abc' + assert "%*.*s"%( 5, 3, 'abcde') == ' abc' + assert "%*.*s"%(-5, 3, 'abcde') == 'abc ' Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_stringobject.py Mon Jan 10 17:19:39 2005 @@ -1,15 +1,13 @@ import autopath -from pypy.tool import testit from pypy.objspace.std import stringobject from pypy.objspace.std.stringobject import W_StringObject -class TestW_StringObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') +class TestW_StringObject: - def tearDown(self): + def teardown_method(self,method): pass ## def test_order_rich(self): @@ -41,29 +39,29 @@ def test_equality(self): w = self.space.wrap - self.assertEqual_w(w('abc'), w('abc')) - self.assertNotEqual_w(w('abc'), w('def')) + assert self.space.eq_w(w('abc'), w('abc')) + assert not self.space.eq_w(w('abc'), w('def')) def test_order_cmp(self): space = self.space w = space.wrap - self.failUnless_w(space.lt(w('a'), w('b'))) - self.failUnless_w(space.lt(w('a'), w('ab'))) - self.failUnless_w(space.le(w('a'), w('a'))) - self.failUnless_w(space.gt(w('a'), w(''))) + assert self.space.is_true(space.lt(w('a'), w('b'))) + assert self.space.is_true(space.lt(w('a'), w('ab'))) + assert self.space.is_true(space.le(w('a'), w('a'))) + assert self.space.is_true(space.gt(w('a'), w(''))) def test_truth(self): w = self.space.wrap - self.failUnless_w(w('non-empty')) - self.failIf_w(w('')) + assert self.space.is_true(w('non-empty')) + assert not self.space.is_true(w('')) def test_getitem(self): space = self.space w = space.wrap w_str = w('abc') - self.assertEqual_w(space.getitem(w_str, w(0)), w('a')) - self.assertEqual_w(space.getitem(w_str, w(-1)), w('c')) - self.assertRaises_w(space.w_IndexError, + assert self.space.eq_w(space.getitem(w_str, w(0)), w('a')) + assert self.space.eq_w(space.getitem(w_str, w(-1)), w('c')) + self.space.raises_w(space.w_IndexError, space.getitem, w_str, w(3)) @@ -74,22 +72,22 @@ w_str = w('abc') w_slice = space.newslice(w(0), w(0), None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('')) w_slice = space.newslice(w(0), w(1), None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('a')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('a')) w_slice = space.newslice(w(0), w(10), None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('abc')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('abc')) w_slice = space.newslice(space.w_None, space.w_None, None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('abc')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('abc')) w_slice = space.newslice(space.w_None, w(-1), None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('ab')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('ab')) w_slice = space.newslice(w(-1), space.w_None, None) - self.assertEqual_w(space.getitem(w_str, w_slice), w('c')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('c')) def test_extended_slice(self): space = self.space @@ -102,233 +100,230 @@ w_str = w('hello') w_slice = space.newslice(w_None, w_None, w(1)) - self.assertEqual_w(space.getitem(w_str, w_slice), w('hello')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('hello')) w_slice = space.newslice(w_None, w_None, w(-1)) - self.assertEqual_w(space.getitem(w_str, w_slice), w('olleh')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('olleh')) w_slice = space.newslice(w_None, w_None, w(2)) - self.assertEqual_w(space.getitem(w_str, w_slice), w('hlo')) + assert self.space.eq_w(space.getitem(w_str, w_slice), w('hlo')) w_slice = space.newslice(w(1), w_None, w(2)) - self.assertEqual_w(space.getitem(w_str, w_slice), w('el')) - -class TestStringObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') + assert self.space.eq_w(space.getitem(w_str, w_slice), w('el')) +class AppTestStringObject: def test_format_wrongchar(self): - self.assertRaises(ValueError, 'a%Zb'.__mod__, ((23,),)) + raises(ValueError, 'a%Zb'.__mod__, ((23,),)) def test_split(self): - self.assertEquals("".split(), []) - self.assertEquals("a".split(), ['a']) - self.assertEquals(" a ".split(), ['a']) - self.assertEquals("a b c".split(), ['a','b','c']) - self.assertEquals('this is the split function'.split(), ['this', 'is', 'the', 'split', 'function']) - self.assertEquals('a|b|c|d'.split('|'), ['a', 'b', 'c', 'd']) - self.assertEquals('a|b|c|d'.split('|', 2), ['a', 'b', 'c|d']) - self.assertEquals('a b c d'.split(None, 1), ['a', 'b c d']) - self.assertEquals('a b c d'.split(None, 2), ['a', 'b', 'c d']) - self.assertEquals('a b c d'.split(None, 3), ['a', 'b', 'c', 'd']) - self.assertEquals('a b c d'.split(None, 4), ['a', 'b', 'c', 'd']) - self.assertEquals('a b c d'.split(None, 0), ['a b c d']) - self.assertEquals('a b c d'.split(None, 2), ['a', 'b', 'c d']) - self.assertEquals('a b c d '.split(), ['a', 'b', 'c', 'd']) - self.assertEquals('a//b//c//d'.split('//'), ['a', 'b', 'c', 'd']) - self.assertEquals('endcase test'.split('test'), ['endcase ', '']) + assert "".split() == [] + assert "a".split() == ['a'] + assert " a ".split() == ['a'] + assert "a b c".split() == ['a','b','c'] + assert 'this is the split function'.split() == ['this', 'is', 'the', 'split', 'function'] + assert 'a|b|c|d'.split('|') == ['a', 'b', 'c', 'd'] + assert 'a|b|c|d'.split('|', 2) == ['a', 'b', 'c|d'] + assert 'a b c d'.split(None, 1) == ['a', 'b c d'] + assert 'a b c d'.split(None, 2) == ['a', 'b', 'c d'] + assert 'a b c d'.split(None, 3) == ['a', 'b', 'c', 'd'] + assert 'a b c d'.split(None, 4) == ['a', 'b', 'c', 'd'] + assert 'a b c d'.split(None, 0) == ['a b c d'] + assert 'a b c d'.split(None, 2) == ['a', 'b', 'c d'] + assert 'a b c d '.split() == ['a', 'b', 'c', 'd'] + assert 'a//b//c//d'.split('//') == ['a', 'b', 'c', 'd'] + assert 'endcase test'.split('test') == ['endcase ', ''] def test_split_splitchar(self): - self.assertEquals("/a/b/c".split('/'), ['','a','b','c']) + assert "/a/b/c".split('/') == ['','a','b','c'] def test_title(self): - self.assertEquals("brown fox".title(), "Brown Fox") - self.assertEquals("!brown fox".title(), "!Brown Fox") - self.assertEquals("bROWN fOX".title(), "Brown Fox") - self.assertEquals("Brown Fox".title(), "Brown Fox") - self.assertEquals("bro!wn fox".title(), "Bro!Wn Fox") + assert "brown fox".title() == "Brown Fox" + assert "!brown fox".title() == "!Brown Fox" + assert "bROWN fOX".title() == "Brown Fox" + assert "Brown Fox".title() == "Brown Fox" + assert "bro!wn fox".title() == "Bro!Wn Fox" def test_istitle(self): - self.assertEquals("brown fox".istitle(), False) - self.assertEquals("!brown fox".istitle(), False) - self.assertEquals("bROWN fOX".istitle(), False) - self.assertEquals("Brown Fox".istitle(), True) - self.assertEquals("bro!wn fox".istitle(), False) - self.assertEquals("Bro!wn fox".istitle(), False) - self.assertEquals("!brown Fox".istitle(), False) - self.assertEquals("!Brown Fox".istitle(), True) - self.assertEquals("Brow&&&&N Fox".istitle(), True) - self.assertEquals("!Brow&&&&n Fox".istitle(), False) + assert "brown fox".istitle() == False + assert "!brown fox".istitle() == False + assert "bROWN fOX".istitle() == False + assert "Brown Fox".istitle() == True + assert "bro!wn fox".istitle() == False + assert "Bro!wn fox".istitle() == False + assert "!brown Fox".istitle() == False + assert "!Brown Fox".istitle() == True + assert "Brow&&&&N Fox".istitle() == True + assert "!Brow&&&&n Fox".istitle() == False def test_capitalize(self): - self.assertEquals("brown fox".capitalize(), "Brown fox") - self.assertEquals(' hello '.capitalize(), ' hello ') - self.assertEquals('Hello '.capitalize(), 'Hello ') - self.assertEquals('hello '.capitalize(), 'Hello ') - self.assertEquals('aaaa'.capitalize(), 'Aaaa') - self.assertEquals('AaAa'.capitalize(), 'Aaaa') + assert "brown fox".capitalize() == "Brown fox" + assert ' hello '.capitalize() == ' hello ' + assert 'Hello '.capitalize() == 'Hello ' + assert 'hello '.capitalize() == 'Hello ' + assert 'aaaa'.capitalize() == 'Aaaa' + assert 'AaAa'.capitalize() == 'Aaaa' def test_rjust(self): s = "abc" - self.assertEquals(s.rjust(2), s) - self.assertEquals(s.rjust(3), s) - self.assertEquals(s.rjust(4), " " + s) - self.assertEquals(s.rjust(5), " " + s) - self.assertEquals('abc'.rjust(10), ' abc') - self.assertEquals('abc'.rjust(6), ' abc') - self.assertEquals('abc'.rjust(3), 'abc') - self.assertEquals('abc'.rjust(2), 'abc') + assert s.rjust(2) == s + assert s.rjust(3) == s + assert s.rjust(4) == " " + s + assert s.rjust(5) == " " + s + assert 'abc'.rjust(10) == ' abc' + assert 'abc'.rjust(6) == ' abc' + assert 'abc'.rjust(3) == 'abc' + assert 'abc'.rjust(2) == 'abc' def test_ljust(self): s = "abc" - self.assertEquals(s.ljust(2), s) - self.assertEquals(s.ljust(3), s) - self.assertEquals(s.ljust(4), s + " ") - self.assertEquals(s.ljust(5), s + " ") - self.assertEquals('abc'.ljust(10), 'abc ') - self.assertEquals('abc'.ljust(6), 'abc ') - self.assertEquals('abc'.ljust(3), 'abc') - self.assertEquals('abc'.ljust(2), 'abc') + assert s.ljust(2) == s + assert s.ljust(3) == s + assert s.ljust(4) == s + " " + assert s.ljust(5) == s + " " + assert 'abc'.ljust(10) == 'abc ' + assert 'abc'.ljust(6) == 'abc ' + assert 'abc'.ljust(3) == 'abc' + assert 'abc'.ljust(2) == 'abc' def test_replace(self): - self.assertEquals('one!two!three!'.replace('!', '@', 1), 'one at two!three!') - self.assertEquals('one!two!three!'.replace('!', ''), 'onetwothree') - self.assertEquals('one!two!three!'.replace('!', '@', 2), 'one at two@three!') - self.assertEquals('one!two!three!'.replace('!', '@', 3), 'one at two@three@') - self.assertEquals('one!two!three!'.replace('!', '@', 4), 'one at two@three@') - self.assertEquals('one!two!three!'.replace('!', '@', 0), 'one!two!three!') - self.assertEquals('one!two!three!'.replace('!', '@'), 'one at two@three@') - self.assertEquals('one!two!three!'.replace('x', '@'), 'one!two!three!') - self.assertEquals('one!two!three!'.replace('x', '@', 2), 'one!two!three!') - self.assertEquals('abc'.replace('', '-'), '-a-b-c-') - self.assertEquals('abc'.replace('', '-', 3), '-a-b-c') - self.assertEquals('abc'.replace('', '-', 0), 'abc') - self.assertEquals(''.replace('', ''), '') - self.assertEquals('abc'.replace('ab', '--', 0), 'abc') - self.assertEquals('abc'.replace('xy', '--'), 'abc') - self.assertEquals('123'.replace('123', ''), '') - self.assertEquals('123123'.replace('123', ''), '') - self.assertEquals('123x123'.replace('123', ''), 'x') + assert 'one!two!three!'.replace('!', '@', 1) == 'one at two!three!' + assert 'one!two!three!'.replace('!', '') == 'onetwothree' + assert 'one!two!three!'.replace('!', '@', 2) == 'one at two@three!' + assert 'one!two!three!'.replace('!', '@', 3) == 'one at two@three@' + assert 'one!two!three!'.replace('!', '@', 4) == 'one at two@three@' + assert 'one!two!three!'.replace('!', '@', 0) == 'one!two!three!' + assert 'one!two!three!'.replace('!', '@') == 'one at two@three@' + assert 'one!two!three!'.replace('x', '@') == 'one!two!three!' + assert 'one!two!three!'.replace('x', '@', 2) == 'one!two!three!' + assert 'abc'.replace('', '-') == '-a-b-c-' + assert 'abc'.replace('', '-', 3) == '-a-b-c' + assert 'abc'.replace('', '-', 0) == 'abc' + assert ''.replace('', '') == '' + assert 'abc'.replace('ab', '--', 0) == 'abc' + assert 'abc'.replace('xy', '--') == 'abc' + assert '123'.replace('123', '') == '' + assert '123123'.replace('123', '') == '' + assert '123x123'.replace('123', '') == 'x' def test_strip(self): s = " a b " - self.assertEquals(s.strip(), "a b") - self.assertEquals(s.rstrip(), " a b") - self.assertEquals(s.lstrip(), "a b ") - self.assertEquals('xyzzyhelloxyzzy'.strip('xyz'), 'hello') - self.assertEquals('xyzzyhelloxyzzy'.lstrip('xyz'), 'helloxyzzy') - self.assertEquals('xyzzyhelloxyzzy'.rstrip('xyz'), 'xyzzyhello') + assert s.strip() == "a b" + assert s.rstrip() == " a b" + assert s.lstrip() == "a b " + assert 'xyzzyhelloxyzzy'.strip('xyz') == 'hello' + assert 'xyzzyhelloxyzzy'.lstrip('xyz') == 'helloxyzzy' + assert 'xyzzyhelloxyzzy'.rstrip('xyz') == 'xyzzyhello' def test_zfill(self): - self.assertEquals('123'.zfill(2), '123') - self.assertEquals('123'.zfill(3), '123') - self.assertEquals('123'.zfill(4), '0123') - self.assertEquals('+123'.zfill(3), '+123') - self.assertEquals('+123'.zfill(4), '+123') - self.assertEquals('+123'.zfill(5), '+0123') - self.assertEquals('-123'.zfill(3), '-123') - self.assertEquals('-123'.zfill(4), '-123') - self.assertEquals('-123'.zfill(5), '-0123') - self.assertEquals(''.zfill(3), '000') - self.assertEquals('34'.zfill(1), '34') - self.assertEquals('34'.zfill(4), '0034') + assert '123'.zfill(2) == '123' + assert '123'.zfill(3) == '123' + assert '123'.zfill(4) == '0123' + assert '+123'.zfill(3) == '+123' + assert '+123'.zfill(4) == '+123' + assert '+123'.zfill(5) == '+0123' + assert '-123'.zfill(3) == '-123' + assert '-123'.zfill(4) == '-123' + assert '-123'.zfill(5) == '-0123' + assert ''.zfill(3) == '000' + assert '34'.zfill(1) == '34' + assert '34'.zfill(4) == '0034' def test_center(self): s="a b" - self.assertEquals(s.center(0), "a b") - self.assertEquals(s.center(1), "a b") - self.assertEquals(s.center(2), "a b") - self.assertEquals(s.center(3), "a b") - self.assertEquals(s.center(4), "a b ") - self.assertEquals(s.center(5), " a b ") - self.assertEquals(s.center(6), " a b ") - self.assertEquals(s.center(7), " a b ") - self.assertEquals(s.center(8), " a b ") - self.assertEquals(s.center(9), " a b ") - self.assertEquals('abc'.center(10), ' abc ') - self.assertEquals('abc'.center(6), ' abc ') - self.assertEquals('abc'.center(3), 'abc') - self.assertEquals('abc'.center(2), 'abc') + assert s.center(0) == "a b" + assert s.center(1) == "a b" + assert s.center(2) == "a b" + assert s.center(3) == "a b" + assert s.center(4) == "a b " + assert s.center(5) == " a b " + assert s.center(6) == " a b " + assert s.center(7) == " a b " + assert s.center(8) == " a b " + assert s.center(9) == " a b " + assert 'abc'.center(10) == ' abc ' + assert 'abc'.center(6) == ' abc ' + assert 'abc'.center(3) == 'abc' + assert 'abc'.center(2) == 'abc' def test_count(self): - self.assertEquals("".count("x"),0) - self.assertEquals("".count(""),1) - self.assertEquals("Python".count(""),7) - self.assertEquals("ab aaba".count("ab"),2) - self.assertEquals('aaa'.count('a'), 3) - self.assertEquals('aaa'.count('b'), 0) - self.assertEquals('aaa'.count('a', -1), 1) - self.assertEquals('aaa'.count('a', -10), 3) - self.assertEquals('aaa'.count('a', 0, -1), 2) - self.assertEquals('aaa'.count('a', 0, -10), 0) + assert "".count("x") ==0 + assert "".count("") ==1 + assert "Python".count("") ==7 + assert "ab aaba".count("ab") ==2 + assert 'aaa'.count('a') == 3 + assert 'aaa'.count('b') == 0 + assert 'aaa'.count('a', -1) == 1 + assert 'aaa'.count('a', -10) == 3 + assert 'aaa'.count('a', 0, -1) == 2 + assert 'aaa'.count('a', 0, -10) == 0 def test_startswith(self): - self.assertEquals('ab'.startswith('ab'), 1) - self.assertEquals('ab'.startswith('a'), 1) - self.assertEquals('ab'.startswith(''), 1) - self.assertEquals('x'.startswith('a'), 0) - self.assertEquals('x'.startswith('x'), 1) - self.assertEquals(''.startswith(''), 1) - self.assertEquals(''.startswith('a'), 0) - self.assertEquals('x'.startswith('xx'), 0) - self.assertEquals('y'.startswith('xx'), 0) + assert 'ab'.startswith('ab') == 1 + assert 'ab'.startswith('a') == 1 + assert 'ab'.startswith('') == 1 + assert 'x'.startswith('a') == 0 + assert 'x'.startswith('x') == 1 + assert ''.startswith('') == 1 + assert ''.startswith('a') == 0 + assert 'x'.startswith('xx') == 0 + assert 'y'.startswith('xx') == 0 def test_endswith(self): - self.assertEquals('ab'.endswith('ab'), 1) - self.assertEquals('ab'.endswith('b'), 1) - self.assertEquals('ab'.endswith(''), 1) - self.assertEquals('x'.endswith('a'), 0) - self.assertEquals('x'.endswith('x'), 1) - self.assertEquals(''.endswith(''), 1) - self.assertEquals(''.endswith('a'), 0) - self.assertEquals('x'.endswith('xx'), 0) - self.assertEquals('y'.endswith('xx'), 0) + assert 'ab'.endswith('ab') == 1 + assert 'ab'.endswith('b') == 1 + assert 'ab'.endswith('') == 1 + assert 'x'.endswith('a') == 0 + assert 'x'.endswith('x') == 1 + assert ''.endswith('') == 1 + assert ''.endswith('a') == 0 + assert 'x'.endswith('xx') == 0 + assert 'y'.endswith('xx') == 0 def test_expandtabs(self): - self.assertEquals('abc\rab\tdef\ng\thi'.expandtabs(), 'abc\rab def\ng hi') - self.assertEquals('abc\rab\tdef\ng\thi'.expandtabs(8), 'abc\rab def\ng hi') - self.assertEquals('abc\rab\tdef\ng\thi'.expandtabs(4), 'abc\rab def\ng hi') - self.assertEquals('abc\r\nab\tdef\ng\thi'.expandtabs(4), 'abc\r\nab def\ng hi') - self.assertEquals('abc\rab\tdef\ng\thi'.expandtabs(), 'abc\rab def\ng hi') - self.assertEquals('abc\rab\tdef\ng\thi'.expandtabs(8), 'abc\rab def\ng hi') - self.assertEquals('abc\r\nab\r\ndef\ng\r\nhi'.expandtabs(4), 'abc\r\nab\r\ndef\ng\r\nhi') + assert 'abc\rab\tdef\ng\thi'.expandtabs() == 'abc\rab def\ng hi' + assert 'abc\rab\tdef\ng\thi'.expandtabs(8) == 'abc\rab def\ng hi' + assert 'abc\rab\tdef\ng\thi'.expandtabs(4) == 'abc\rab def\ng hi' + assert 'abc\r\nab\tdef\ng\thi'.expandtabs(4) == 'abc\r\nab def\ng hi' + assert 'abc\rab\tdef\ng\thi'.expandtabs() == 'abc\rab def\ng hi' + assert 'abc\rab\tdef\ng\thi'.expandtabs(8) == 'abc\rab def\ng hi' + assert 'abc\r\nab\r\ndef\ng\r\nhi'.expandtabs(4) == 'abc\r\nab\r\ndef\ng\r\nhi' s = 'xy\t' - self.assertEquals(s.expandtabs(),'xy ') + assert s.expandtabs() =='xy ' s = '\txy\t' - self.assertEquals(s.expandtabs(),' xy ') - self.assertEquals(s.expandtabs(1),' xy ') - self.assertEquals(s.expandtabs(2),' xy ') - self.assertEquals(s.expandtabs(3),' xy ') + assert s.expandtabs() ==' xy ' + assert s.expandtabs(1) ==' xy ' + assert s.expandtabs(2) ==' xy ' + assert s.expandtabs(3) ==' xy ' - self.assertEquals('xy'.expandtabs(),'xy') - self.assertEquals(''.expandtabs(),'') + assert 'xy'.expandtabs() =='xy' + assert ''.expandtabs() =='' def test_splitlines(self): s="ab\nab\n \n x\n\n\n" - self.assertEquals(s.splitlines(),['ab', 'ab', ' ', ' x', '', '']) - self.assertEquals(s.splitlines(),s.splitlines(0)) - self.assertEquals(s.splitlines(1),['ab\n', 'ab\n', ' \n', ' x\n', '\n', '\n']) + assert s.splitlines() ==['ab', 'ab', ' ', ' x', '', ''] + assert s.splitlines() ==s.splitlines(0) + assert s.splitlines(1) ==['ab\n', 'ab\n', ' \n', ' x\n', '\n', '\n'] s="\none\n\two\nthree\n\n" - self.assertEquals(s.splitlines(),['', 'one', '\two', 'three', '']) - self.assertEquals(s.splitlines(1),['\n', 'one\n', '\two\n', 'three\n', '\n']) + assert s.splitlines() ==['', 'one', '\two', 'three', ''] + assert s.splitlines(1) ==['\n', 'one\n', '\two\n', 'three\n', '\n'] def test_find(self): - self.assertEquals('abcdefghiabc'.find('abc'), 0) - self.assertEquals('abcdefghiabc'.find('abc', 1), 9) - self.assertEquals('abcdefghiabc'.find('def', 4), -1) + assert 'abcdefghiabc'.find('abc') == 0 + assert 'abcdefghiabc'.find('abc', 1) == 9 + assert 'abcdefghiabc'.find('def', 4) == -1 def test_index(self): - self.assertEquals('abcdefghiabc'.index(''), 0) - self.assertEquals('abcdefghiabc'.index('def'), 3) - self.assertEquals('abcdefghiabc'.index('abc'), 0) - self.assertEquals('abcdefghiabc'.index('abc', 1), 9) + assert 'abcdefghiabc'.index('') == 0 + assert 'abcdefghiabc'.index('def') == 3 + assert 'abcdefghiabc'.index('abc') == 0 + assert 'abcdefghiabc'.index('abc', 1) == 9 #XXX it comes UnicodeError #self.assertRaises(ValueError, 'abcdefghiabc'.index('hib')) #self.assertRaises(ValueError, 'abcdefghiab'.index('abc', 1)) @@ -336,16 +331,16 @@ #self.assertRaises(ValueError, 'abcdefghi'.index('ghi', -1)) def test_rfind(self): - self.assertEquals('abcdefghiabc'.rfind('abc'), 9) - self.assertEquals('abcdefghiabc'.rfind(''), 12) - self.assertEquals('abcdefghiabc'.rfind('abcd'), 0) - self.assertEquals('abcdefghiabc'.rfind('abcz'), -1) + assert 'abcdefghiabc'.rfind('abc') == 9 + assert 'abcdefghiabc'.rfind('') == 12 + assert 'abcdefghiabc'.rfind('abcd') == 0 + assert 'abcdefghiabc'.rfind('abcz') == -1 def test_rindex(self): - self.assertEquals('abcdefghiabc'.rindex(''), 12) - self.assertEquals('abcdefghiabc'.rindex('def'), 3) - self.assertEquals('abcdefghiabc'.rindex('abc'), 9) - self.assertEquals('abcdefghiabc'.rindex('abc', 0, -1), 0) + assert 'abcdefghiabc'.rindex('') == 12 + assert 'abcdefghiabc'.rindex('def') == 3 + assert 'abcdefghiabc'.rindex('abc') == 9 + assert 'abcdefghiabc'.rindex('abc', 0, -1) == 0 #XXX it comes UnicodeError #self.assertRaises(ValueError, 'abcdefghiabc'.rindex('hib')) #self.assertRaises(ValueError, 'defghiabc'.rindex('def', 1)) @@ -355,79 +350,79 @@ def test_split_maxsplit(self): - self.assertEquals("/a/b/c".split('/', 2), ['','a','b/c']) - self.assertEquals("a/b/c".split("/"), ['a', 'b', 'c']) - self.assertEquals(" a ".split(None, 0), ['a ']) - self.assertEquals(" a ".split(None, 1), ['a']) - self.assertEquals(" a a ".split(" ", 0), [' a a ']) - self.assertEquals(" a a ".split(" ", 1), ['', 'a a ']) + assert "/a/b/c".split('/', 2) == ['','a','b/c'] + assert "a/b/c".split("/") == ['a', 'b', 'c'] + assert " a ".split(None, 0) == ['a '] + assert " a ".split(None, 1) == ['a'] + assert " a a ".split(" ", 0) == [' a a '] + assert " a a ".split(" ", 1) == ['', 'a a '] def test_join(self): - self.assertEquals(", ".join(['a', 'b', 'c']), "a, b, c") - self.assertEquals("".join([]), "") - self.assertEquals("-".join(['a', 'b']), 'a-b') - self.assertRaises(TypeError, ''.join, 1) - self.assertRaises(TypeError, ''.join, [1]) - self.assertRaises(TypeError, ''.join, [[1]]) + assert ", ".join(['a', 'b', 'c']) == "a, b, c" + assert "".join([]) == "" + assert "-".join(['a', 'b']) == 'a-b' + raises(TypeError, ''.join, 1) + raises(TypeError, ''.join, [1]) + raises(TypeError, ''.join, [[1]]) def test_lower(self): - self.assertEquals("aaa AAA".lower(), "aaa aaa") - self.assertEquals("".lower(), "") + assert "aaa AAA".lower() == "aaa aaa" + assert "".lower() == "" def test_upper(self): - self.assertEquals("aaa AAA".upper(), "AAA AAA") - self.assertEquals("".upper(), "") + assert "aaa AAA".upper() == "AAA AAA" + assert "".upper() == "" def test_isalnum(self): - self.assertEquals("".isalnum(), False) - self.assertEquals("!Bro12345w&&&&n Fox".isalnum(), False) - self.assertEquals("125 Brown Foxes".isalnum(), False) - self.assertEquals("125BrownFoxes".isalnum(), True) + assert "".isalnum() == False + assert "!Bro12345w&&&&n Fox".isalnum() == False + assert "125 Brown Foxes".isalnum() == False + assert "125BrownFoxes".isalnum() == True def test_isalpha(self): - self.assertEquals("".isalpha(), False) - self.assertEquals("!Bro12345w&&&&nFox".isalpha(), False) - self.assertEquals("Brown Foxes".isalpha(), False) - self.assertEquals("125".isalpha(), False) + assert "".isalpha() == False + assert "!Bro12345w&&&&nFox".isalpha() == False + assert "Brown Foxes".isalpha() == False + assert "125".isalpha() == False def test_isdigit(self): - self.assertEquals("".isdigit(), False) - self.assertEquals("!Bro12345w&&&&nFox".isdigit(), False) - self.assertEquals("Brown Foxes".isdigit(), False) - self.assertEquals("125".isdigit(), True) + assert "".isdigit() == False + assert "!Bro12345w&&&&nFox".isdigit() == False + assert "Brown Foxes".isdigit() == False + assert "125".isdigit() == True def test_isspace(self): - self.assertEquals("".isspace(), False) - self.assertEquals("!Bro12345w&&&&nFox".isspace(), False) - self.assertEquals(" ".isspace(), True) - self.assertEquals("\t\t\b\b\n".isspace(), False) - self.assertEquals("\t\t".isspace(), True) - self.assertEquals("\t\t\r\r\n".isspace(), True) + assert "".isspace() == False + assert "!Bro12345w&&&&nFox".isspace() == False + assert " ".isspace() == True + assert "\t\t\b\b\n".isspace() == False + assert "\t\t".isspace() == True + assert "\t\t\r\r\n".isspace() == True def test_islower(self): - self.assertEquals("".islower(), False) - self.assertEquals(" ".islower(), False) - self.assertEquals("\t\t\b\b\n".islower(), False) - self.assertEquals("b".islower(), True) - self.assertEquals("bbb".islower(), True) - self.assertEquals("!bbb".islower(), False) - self.assertEquals("BBB".islower(), False) - self.assertEquals("bbbBBB".islower(), False) + assert "".islower() == False + assert " ".islower() == False + assert "\t\t\b\b\n".islower() == False + assert "b".islower() == True + assert "bbb".islower() == True + assert "!bbb".islower() == False + assert "BBB".islower() == False + assert "bbbBBB".islower() == False def test_isupper(self): - self.assertEquals("".isupper(), False) - self.assertEquals(" ".isupper(), False) - self.assertEquals("\t\t\b\b\n".isupper(), False) - self.assertEquals("B".isupper(), True) - self.assertEquals("BBB".isupper(), True) - self.assertEquals("!BBB".isupper(), False) - self.assertEquals("bbb".isupper(), False) - self.assertEquals("BBBbbb".isupper(), False) + assert "".isupper() == False + assert " ".isupper() == False + assert "\t\t\b\b\n".isupper() == False + assert "B".isupper() == True + assert "BBB".isupper() == True + assert "!BBB".isupper() == False + assert "bbb".isupper() == False + assert "BBBbbb".isupper() == False def test_swapcase(self): - self.assertEquals("aaa AAA 111".swapcase(), "AAA aaa 111") - self.assertEquals("".swapcase(), "") + assert "aaa AAA 111".swapcase() == "AAA aaa 111" + assert "".swapcase() == "" def test_translate(self): def maketrans(origin, image): @@ -441,12 +436,12 @@ return tbl table = maketrans('abc', 'xyz') - self.assertEquals('xyzxyz', 'xyzabcdef'.translate(table, 'def')) + assert 'xyzxyz' == 'xyzabcdef'.translate(table, 'def') table = maketrans('a', 'A') - self.assertEquals('Abc', 'abc'.translate(table)) - self.assertEquals('xyz', 'xyz'.translate(table)) - self.assertEquals('yz', 'xyz'.translate(table, 'x')) + assert 'Abc' == 'abc'.translate(table) + assert 'xyz' == 'xyz'.translate(table) + assert 'yz' == 'xyz'.translate(table, 'x') #self.assertRaises(ValueError, 'xyz'.translate('too short', 'strip')) #self.assertRaises(ValueError, 'xyz'.translate('too short')) @@ -455,34 +450,30 @@ l=[] for i in iter("42"): l.append(i) - self.assertEquals(l, ['4','2']) + assert l == ['4','2'] def test_repr(self): - self.assertEquals(repr("") ,"''") - self.assertEquals(repr("a") ,"'a'") - self.assertEquals(repr("'") ,'"\'"') - self.assertEquals(repr("\'") ,"\"\'\"") - self.assertEquals(repr("\"") ,'\'"\'') - self.assertEquals(repr("\t") ,"'\\t'") - self.assertEquals(repr("\\") ,"'\\\\'") - self.assertEquals(repr('') ,"''") - self.assertEquals(repr('a') ,"'a'") - self.assertEquals(repr('"') ,"'\"'") - self.assertEquals(repr('\'') ,'"\'"') - self.assertEquals(repr('\"') ,"'\"'") - self.assertEquals(repr('\t') ,"'\\t'") - self.assertEquals(repr('\\') ,"'\\\\'") - self.assertEquals(repr("'''\"") ,'\'\\\'\\\'\\\'"\'') - self.assertEquals(repr(chr(19)) ,"'\\x13'") - self.assertEquals(repr(chr(2)) ,"'\\x02'") + assert repr("") =="''" + assert repr("a") =="'a'" + assert repr("'") =='"\'"' + assert repr("\'") =="\"\'\"" + assert repr("\"") =='\'"\'' + assert repr("\t") =="'\\t'" + assert repr("\\") =="'\\\\'" + assert repr('') =="''" + assert repr('a') =="'a'" + assert repr('"') =="'\"'" + assert repr('\'') =='"\'"' + assert repr('\"') =="'\"'" + assert repr('\t') =="'\\t'" + assert repr('\\') =="'\\\\'" + assert repr("'''\"") =='\'\\\'\\\'\\\'"\'' + assert repr(chr(19)) =="'\\x13'" + assert repr(chr(2)) =="'\\x02'" def test_contains(self): - self.failUnless('' in 'abc') - self.failUnless('a' in 'abc') - self.failUnless('ab' in 'abc') - self.failIf('d' in 'abc') - self.assertRaises(TypeError, 'a'.__contains__, 1) - - -if __name__ == '__main__': - testit.main() + assert '' in 'abc' + assert 'a' in 'abc' + assert 'ab' in 'abc' + assert not 'd' in 'abc' + raises(TypeError, 'a'.__contains__, 1) Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_strutil.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_strutil.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_strutil.py Mon Jan 10 17:19:39 2005 @@ -1,8 +1,9 @@ import autopath -from pypy.tool import testit from pypy.objspace.std.strutil import * -class TestStrUtil(testit.TestCase): +objspacename = 'std' + +class TestStrUtil: def test_string_to_int(self): cases = [('0', 0), @@ -21,8 +22,8 @@ (' -123456789 ', -123456789), ] for s, expected in cases: - self.assertEquals(string_to_int(s), expected) - self.assertEquals(string_to_long(s), expected) + assert string_to_int(s) == expected + assert string_to_long(s) == expected def test_string_to_int_base(self): cases = [('111', 2, 7), @@ -50,12 +51,12 @@ ('0X', 16, 0), # " " ] for s, base, expected in cases: - self.assertEquals(string_to_int(s, base), expected) - self.assertEquals(string_to_int('+'+s, base), expected) - self.assertEquals(string_to_int('-'+s, base), -expected) - self.assertEquals(string_to_int(s+'\n', base), expected) - self.assertEquals(string_to_int(' +'+s, base), expected) - self.assertEquals(string_to_int('-'+s+' ', base), -expected) + assert string_to_int(s, base) == expected + assert string_to_int('+'+s, base) == expected + assert string_to_int('-'+s, base) == -expected + assert string_to_int(s+'\n', base) == expected + assert string_to_int(' +'+s, base) == expected + assert string_to_int('-'+s+' ', base) == -expected def test_string_to_int_error(self): cases = ['0x123', # must use base 0 or 16 @@ -75,11 +76,11 @@ '@', ] for s in cases: - self.assertRaises(ValueError, string_to_int, s) - self.assertRaises(ValueError, string_to_int, ' '+s) - self.assertRaises(ValueError, string_to_int, s+' ') - self.assertRaises(ValueError, string_to_int, '+'+s) - self.assertRaises(ValueError, string_to_int, '-'+s) + raises(ValueError, string_to_int, s) + raises(ValueError, string_to_int, ' '+s) + raises(ValueError, string_to_int, s+' ') + raises(ValueError, string_to_int, '+'+s) + raises(ValueError, string_to_int, '-'+s) def test_string_to_int_base_error(self): cases = [('1', 1), @@ -97,21 +98,18 @@ ('12.3', 16), ] for s, base in cases: - self.assertRaises(ValueError, string_to_int, s, base) - self.assertRaises(ValueError, string_to_int, ' '+s, base) - self.assertRaises(ValueError, string_to_int, s+' ', base) - self.assertRaises(ValueError, string_to_int, '+'+s, base) - self.assertRaises(ValueError, string_to_int, '-'+s, base) + raises(ValueError, string_to_int, s, base) + raises(ValueError, string_to_int, ' '+s, base) + raises(ValueError, string_to_int, s+' ', base) + raises(ValueError, string_to_int, '+'+s, base) + raises(ValueError, string_to_int, '-'+s, base) def test_string_to_long(self): - self.assertEquals(string_to_long('123L'), 123) - self.assertEquals(string_to_long('123L '), 123) - self.assertRaises(ValueError, string_to_long, 'L') - self.assertRaises(ValueError, string_to_long, 'L ') - self.assertEquals(string_to_long('123L', 4), 27) - self.assertEquals(string_to_long('123L', 30), 27000 + 1800 + 90 + 21) - self.assertEquals(string_to_long('123L', 22), 10648 + 968 + 66 + 21) - self.assertEquals(string_to_long('123L', 21), 441 + 42 + 3) - -if __name__ == '__main__': - testit.main() + assert string_to_long('123L') == 123 + assert string_to_long('123L ') == 123 + raises(ValueError, string_to_long, 'L') + raises(ValueError, string_to_long, 'L ') + assert string_to_long('123L', 4) == 27 + assert string_to_long('123L', 30) == 27000 + 1800 + 90 + 21 + assert string_to_long('123L', 22) == 10648 + 968 + 66 + 21 + assert string_to_long('123L', 21) == 441 + 42 + 3 Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_tupleobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_tupleobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_tupleobject.py Mon Jan 10 17:19:39 2005 @@ -1,70 +1,65 @@ #from __future__ import nested_scopes import autopath -from pypy.tool import testit from pypy.objspace.std.tupleobject import W_TupleObject from pypy.interpreter.error import OperationError -class TestW_TupleObject(testit.TestCase): +objspacename = 'std' - def setUp(self): - self.space = testit.objspace('std') - - def tearDown(self): - pass +class TestW_TupleObject: def test_is_true(self): w = self.space.wrap w_tuple = W_TupleObject(self.space, []) - self.assertEqual(self.space.is_true(w_tuple), False) + assert self.space.is_true(w_tuple) == False w_tuple = W_TupleObject(self.space, [w(5)]) - self.assertEqual(self.space.is_true(w_tuple), True) + assert self.space.is_true(w_tuple) == True w_tuple = W_TupleObject(self.space, [w(5), w(3)]) - self.assertEqual(self.space.is_true(w_tuple), True) + assert self.space.is_true(w_tuple) == True def test_len(self): w = self.space.wrap w_tuple = W_TupleObject(self.space, []) - self.assertEqual_w(self.space.len(w_tuple), w(0)) + assert self.space.eq_w(self.space.len(w_tuple), w(0)) w_tuple = W_TupleObject(self.space, [w(5)]) - self.assertEqual_w(self.space.len(w_tuple), w(1)) + assert self.space.eq_w(self.space.len(w_tuple), w(1)) w_tuple = W_TupleObject(self.space, [w(5), w(3), w(99)]*111) - self.assertEqual_w(self.space.len(w_tuple), w(333)) + assert self.space.eq_w(self.space.len(w_tuple), w(333)) def test_getitem(self): w = self.space.wrap w_tuple = W_TupleObject(self.space, [w(5), w(3)]) - self.assertEqual_w(self.space.getitem(w_tuple, w(0)), w(5)) - self.assertEqual_w(self.space.getitem(w_tuple, w(1)), w(3)) - self.assertEqual_w(self.space.getitem(w_tuple, w(-2)), w(5)) - self.assertEqual_w(self.space.getitem(w_tuple, w(-1)), w(3)) - self.assertRaises_w(self.space.w_IndexError, + assert self.space.eq_w(self.space.getitem(w_tuple, w(0)), w(5)) + assert self.space.eq_w(self.space.getitem(w_tuple, w(1)), w(3)) + assert self.space.eq_w(self.space.getitem(w_tuple, w(-2)), w(5)) + assert self.space.eq_w(self.space.getitem(w_tuple, w(-1)), w(3)) + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_tuple, w(2)) - self.assertRaises_w(self.space.w_IndexError, + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_tuple, w(42)) - self.assertRaises_w(self.space.w_IndexError, + self.space.raises_w(self.space.w_IndexError, self.space.getitem, w_tuple, w(-3)) def test_iter(self): w = self.space.wrap w_tuple = W_TupleObject(self.space, [w(5), w(3), w(99)]) w_iter = self.space.iter(w_tuple) - self.assertEqual_w(self.space.next(w_iter), w(5)) - self.assertEqual_w(self.space.next(w_iter), w(3)) - self.assertEqual_w(self.space.next(w_iter), w(99)) - self.assertRaises(OperationError, self.space.next, w_iter) - self.assertRaises(OperationError, self.space.next, w_iter) + assert self.space.eq_w(self.space.next(w_iter), w(5)) + assert self.space.eq_w(self.space.next(w_iter), w(3)) + assert self.space.eq_w(self.space.next(w_iter), w(99)) + raises(OperationError, self.space.next, w_iter) + raises(OperationError, self.space.next, w_iter) def test_contains(self): w = self.space.wrap w_tuple = W_TupleObject(self.space, [w(5), w(3), w(99)]) - self.assertEqual_w(self.space.contains(w_tuple, w(5)), + assert self.space.eq_w(self.space.contains(w_tuple, w(5)), self.space.w_True) - self.assertEqual_w(self.space.contains(w_tuple, w(99)), + assert self.space.eq_w(self.space.contains(w_tuple, w(99)), self.space.w_True) - self.assertEqual_w(self.space.contains(w_tuple, w(11)), + assert self.space.eq_w(self.space.contains(w_tuple, w(11)), self.space.w_False) - self.assertEqual_w(self.space.contains(w_tuple, w_tuple), + assert self.space.eq_w(self.space.contains(w_tuple, w_tuple), self.space.w_False) def test_add(self): @@ -72,14 +67,14 @@ w_tuple0 = W_TupleObject(self.space, []) w_tuple1 = W_TupleObject(self.space, [w(5), w(3), w(99)]) w_tuple2 = W_TupleObject(self.space, [w(-7)] * 111) - self.assertEqual_w(self.space.add(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.add(w_tuple1, w_tuple1), W_TupleObject(self.space, [w(5), w(3), w(99), w(5), w(3), w(99)])) - self.assertEqual_w(self.space.add(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.add(w_tuple1, w_tuple2), W_TupleObject(self.space, [w(5), w(3), w(99)] + [w(-7)] * 111)) - self.assertEqual_w(self.space.add(w_tuple1, w_tuple0), w_tuple1) - self.assertEqual_w(self.space.add(w_tuple0, w_tuple2), w_tuple2) + assert self.space.eq_w(self.space.add(w_tuple1, w_tuple0), w_tuple1) + assert self.space.eq_w(self.space.add(w_tuple0, w_tuple2), w_tuple2) def test_mul(self): # only testing right mul at the moment @@ -89,10 +84,10 @@ w_tup = W_TupleObject(self.space, [arg]) w_tup3 = W_TupleObject(self.space, [arg]*n) w_res = self.space.mul(w_tup, w(n)) - self.assertEqual_w(w_tup3, w_res) + assert self.space.eq_w(w_tup3, w_res) # commute w_res = self.space.mul(w(n), w_tup) - self.assertEqual_w(w_tup3, w_res) + assert self.space.eq_w(w_tup3, w_res) def test_getslice(self): w = self.space.wrap @@ -101,7 +96,7 @@ w_slice = self.space.newslice(w(start), w(stop), w(step)) w_tuple = W_TupleObject(self.space, [w(i) for i in testtuple]) w_result = self.space.getitem(w_tuple, w_slice) - self.assertEqual(self.space.unwrap(w_result), expected) + assert self.space.unwrap(w_result) == expected for testtuple in [(), (5,3,99), tuple(range(5,555,10))]: for start in [-2, -1, 0, 1, 10]: @@ -123,15 +118,15 @@ w_tuple2 = W_TupleObject(self.space, [w(5), w(3), w(99)]) w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) - self.assertEqual_w(self.space.eq(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.eq(w_tuple0, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.eq(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.eq(w_tuple1, w_tuple0), self.space.w_False) - self.assertEqual_w(self.space.eq(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.eq(w_tuple1, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.eq(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.eq(w_tuple1, w_tuple2), self.space.w_True) - self.assertEqual_w(self.space.eq(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.eq(w_tuple2, w_tuple3), self.space.w_False) def test_ne(self): w = self.space.wrap @@ -141,15 +136,15 @@ w_tuple2 = W_TupleObject(self.space, [w(5), w(3), w(99)]) w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) - self.assertEqual_w(self.space.ne(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.ne(w_tuple0, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.ne(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.ne(w_tuple1, w_tuple0), self.space.w_True) - self.assertEqual_w(self.space.ne(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.ne(w_tuple1, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.ne(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.ne(w_tuple1, w_tuple2), self.space.w_False) - self.assertEqual_w(self.space.ne(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.ne(w_tuple2, w_tuple3), self.space.w_True) def test_lt(self): w = self.space.wrap @@ -160,17 +155,17 @@ w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) w_tuple4 = W_TupleObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.lt(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.lt(w_tuple0, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.lt(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.lt(w_tuple1, w_tuple0), self.space.w_False) - self.assertEqual_w(self.space.lt(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.lt(w_tuple1, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.lt(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.lt(w_tuple1, w_tuple2), self.space.w_False) - self.assertEqual_w(self.space.lt(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.lt(w_tuple2, w_tuple3), self.space.w_True) - self.assertEqual_w(self.space.lt(w_tuple4, w_tuple3), + assert self.space.eq_w(self.space.lt(w_tuple4, w_tuple3), self.space.w_True) def test_ge(self): @@ -182,17 +177,17 @@ w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) w_tuple4 = W_TupleObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.ge(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.ge(w_tuple0, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.ge(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.ge(w_tuple1, w_tuple0), self.space.w_True) - self.assertEqual_w(self.space.ge(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.ge(w_tuple1, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.ge(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.ge(w_tuple1, w_tuple2), self.space.w_True) - self.assertEqual_w(self.space.ge(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.ge(w_tuple2, w_tuple3), self.space.w_False) - self.assertEqual_w(self.space.ge(w_tuple4, w_tuple3), + assert self.space.eq_w(self.space.ge(w_tuple4, w_tuple3), self.space.w_False) def test_gt(self): @@ -204,17 +199,17 @@ w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) w_tuple4 = W_TupleObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.gt(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.gt(w_tuple0, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.gt(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.gt(w_tuple1, w_tuple0), self.space.w_True) - self.assertEqual_w(self.space.gt(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.gt(w_tuple1, w_tuple1), self.space.w_False) - self.assertEqual_w(self.space.gt(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.gt(w_tuple1, w_tuple2), self.space.w_False) - self.assertEqual_w(self.space.gt(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.gt(w_tuple2, w_tuple3), self.space.w_False) - self.assertEqual_w(self.space.gt(w_tuple4, w_tuple3), + assert self.space.eq_w(self.space.gt(w_tuple4, w_tuple3), self.space.w_False) def test_le(self): @@ -226,18 +221,15 @@ w_tuple3 = W_TupleObject(self.space, [w(5), w(3), w(99), w(-1)]) w_tuple4 = W_TupleObject(self.space, [w(5), w(3), w(9), w(-1)]) - self.assertEqual_w(self.space.le(w_tuple0, w_tuple1), + assert self.space.eq_w(self.space.le(w_tuple0, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.le(w_tuple1, w_tuple0), + assert self.space.eq_w(self.space.le(w_tuple1, w_tuple0), self.space.w_False) - self.assertEqual_w(self.space.le(w_tuple1, w_tuple1), + assert self.space.eq_w(self.space.le(w_tuple1, w_tuple1), self.space.w_True) - self.assertEqual_w(self.space.le(w_tuple1, w_tuple2), + assert self.space.eq_w(self.space.le(w_tuple1, w_tuple2), self.space.w_True) - self.assertEqual_w(self.space.le(w_tuple2, w_tuple3), + assert self.space.eq_w(self.space.le(w_tuple2, w_tuple3), self.space.w_True) - self.assertEqual_w(self.space.le(w_tuple4, w_tuple3), + assert self.space.eq_w(self.space.le(w_tuple4, w_tuple3), self.space.w_True) - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_typeobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_typeobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_typeobject.py Mon Jan 10 17:19:39 2005 @@ -1,5 +1,4 @@ import autopath -from pypy.tool import testit ##class TestSpecialMultimethodCode(testit.TestCase): @@ -53,41 +52,40 @@ ## w({'x1': 5.5, 'x2': 7})), ## w(-1.5)) -class TestTypeObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') +objspacename = 'std' +class AppTestTypeObject: def test_bases(self): - self.assertEquals(int.__bases__, (object,)) + assert int.__bases__ == (object,) class X: pass - self.assertEquals(X.__bases__, (object,)) + assert X.__bases__ == (object,) class Y(X): pass - self.assertEquals(Y.__bases__, (X,)) + assert Y.__bases__ == (X,) class Z(Y,X): pass - self.assertEquals(Z.__bases__, (Y, X)) + assert Z.__bases__ == (Y, X) def test_builtin_add(self): x = 5 - self.assertEquals(x.__add__(6), 11) + assert x.__add__(6) == 11 x = 3.5 - self.assertEquals(x.__add__(2), 5.5) - self.assertEquals(x.__add__(2.0), 5.5) + assert x.__add__(2) == 5.5 + assert x.__add__(2.0) == 5.5 def test_builtin_call(self): def f(*args): return args - self.assertEquals(f.__call__(), ()) - self.assertEquals(f.__call__(5), (5,)) - self.assertEquals(f.__call__("hello", "world"), ("hello", "world")) + assert f.__call__() == () + assert f.__call__(5) == (5,) + assert f.__call__("hello", "world") == ("hello", "world") def test_builtin_call_kwds(self): def f(*args, **kwds): return args, kwds - self.assertEquals(f.__call__(), ((), {})) - self.assertEquals(f.__call__("hello", "world"), (("hello", "world"), {})) - self.assertEquals(f.__call__(5, bla=6), ((5,), {"bla": 6})) - self.assertEquals(f.__call__(a=1, b=2, c=3), ((), {"a": 1, "b": 2, - "c": 3})) + assert f.__call__() == ((), {}) + assert f.__call__("hello", "world") == (("hello", "world"), {}) + assert f.__call__(5, bla=6) == ((5,), {"bla": 6}) + assert f.__call__(a=1, b=2, c=3) == ((), {"a": 1, "b": 2, + "c": 3}) def test_multipleinheritance_fail(self): try: @@ -105,15 +103,15 @@ class HasOuterMetaclass(object): __metaclass__ = OuterMetaClass - self.assertEquals(type(HasOuterMetaclass), OuterMetaClass) - self.assertEquals(type(HasOuterMetaclass), HasOuterMetaclass.__metaclass__) + assert type(HasOuterMetaclass) == OuterMetaClass + assert type(HasOuterMetaclass) == HasOuterMetaclass.__metaclass__ def test_inner_metaclass(self): class HasInnerMetaclass(object): class __metaclass__(type): pass - self.assertEquals(type(HasInnerMetaclass), HasInnerMetaclass.__metaclass__) + assert type(HasInnerMetaclass) == HasInnerMetaclass.__metaclass__ def test_implicit_metaclass(self): global __metaclass__ @@ -130,7 +128,7 @@ pass try: - self.assertEquals(type(HasImplicitMetaclass), __metaclass__) + assert type(HasImplicitMetaclass) == __metaclass__ finally: if has_old_metaclass: __metaclass__ = old_metaclass @@ -148,20 +146,20 @@ def mro(self): return [self, object] - self.assertEquals(B_mro.__bases__, (A_mro,)) - self.assertEquals(B_mro.__mro__, (B_mro, object)) - self.assertEquals(B_mro.mro(), [B_mro, object]) - self.assertEquals(B_mro.b, 1) - self.assertEquals(B_mro().b, 1) - self.assertEquals(getattr(B_mro, 'a', None), None) - self.assertEquals(getattr(B_mro(), 'a', None), None) + assert B_mro.__bases__ == (A_mro,) + assert B_mro.__mro__ == (B_mro, object) + assert B_mro.mro() == [B_mro, object] + assert B_mro.b == 1 + assert B_mro().b == 1 + assert getattr(B_mro, 'a', None) == None + assert getattr(B_mro(), 'a', None) == None def test_nodoc(self): class NoDoc(object): pass try: - self.assertEquals(NoDoc.__doc__, None) + assert NoDoc.__doc__ == None except AttributeError: raise AssertionError, "__doc__ missing!" @@ -169,13 +167,13 @@ class ExplicitDoc(object): __doc__ = 'foo' - self.assertEquals(ExplicitDoc.__doc__, 'foo') + assert ExplicitDoc.__doc__ == 'foo' def test_implicitdoc(self): class ImplicitDoc(object): "foo" - self.assertEquals(ImplicitDoc.__doc__, 'foo') + assert ImplicitDoc.__doc__ == 'foo' def test_immutabledoc(self): class ImmutableDoc(object): @@ -192,8 +190,4 @@ else: raise AssertionError, '__doc__ should not be writable' - self.assertEquals(ImmutableDoc.__doc__, 'foo') - - -if __name__ == '__main__': - testit.main() + assert ImmutableDoc.__doc__ == 'foo' Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_unicodestring.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_unicodestring.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_unicodestring.py Mon Jan 10 17:19:39 2005 @@ -2,45 +2,39 @@ # really implement unicode yet). import autopath, sys -from pypy.tool import testit -class TestUnicodeStringStdOnly(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') +objspacename = 'std' +class AppTestUnicodeStringStdOnly: def test_compares(self): - self.assertEqual(u'a', 'a') - self.assertEqual('a', u'a') - self.assertNotEqual(u'a', 'b') - self.assertNotEqual('a', u'b') + assert u'a' == 'a' + assert 'a' == u'a' + assert not u'a' == 'b' # xxx u'a' != 'b' fails + assert not 'a' == u'b'# xxx 'a' != u'b' fails -class TestUnicodeString(testit.AppTestCase): +class AppTestUnicodeString: def test_addition(self): def check(a, b): - self.assertEqual(a, b) - self.assertEqual(type(a), type(b)) + assert a == b + assert type(a) == type(b) check(u'a' + 'b', u'ab') check('a' + u'b', u'ab') def test_join(self): def check(a, b): - self.assertEqual(a, b) - self.assertEqual(type(a), type(b)) + assert a == b + assert type(a) == type(b) check(', '.join([u'a']), u'a') check(', '.join(['a', u'b']), u'a, b') check(u', '.join(['a', 'b']), u'a, b') if sys.version_info >= (2,3): def test_contains_ex(self): - self.failUnless(u'' in 'abc') - self.failUnless(u'bc' in 'abc') - self.failUnless('bc' in 'abc') + assert u'' in 'abc' + assert u'bc' in 'abc' + assert 'bc' in 'abc' def test_contains(self): - self.failUnless(u'a' in 'abc') - self.failUnless('a' in u'abc') - - -if __name__ == '__main__': - testit.main() + assert u'a' in 'abc' + assert 'a' in u'abc' Modified: pypy/branch/src-pytest/pypy/objspace/std/test/test_userobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/test/test_userobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/test/test_userobject.py Mon Jan 10 17:19:39 2005 @@ -1,30 +1,28 @@ import autopath -from pypy.tool import testit -class TestUserObject(testit.AppTestCase): - def setUp(self): - self.space = testit.objspace('std') +objspacename = 'std' +class AppTestUserObject: def test_emptyclass(self): class empty: pass inst = empty() - self.failUnless(isinstance(inst, empty)) + assert isinstance(inst, empty) inst.attr=23 - self.assertEquals(inst.attr,23) + assert inst.attr ==23 def test_method(self): class A: def f(self, v): return v*42 a = A() - self.assertEquals(a.f('?'), '??????????????????????????????????????????') + assert a.f('?') == '??????????????????????????????????????????' def test_unboundmethod(self): class A: def f(self, v): return v*17 a = A() - self.assertEquals(A.f(a, '!'), '!!!!!!!!!!!!!!!!!') + assert A.f(a, '!') == '!!!!!!!!!!!!!!!!!' def test_subclassing(self): for base in tuple, list, dict, str, int, float: @@ -36,17 +34,17 @@ if base is not dict: # XXX must be fixed raise else: - self.failUnless(isinstance(stuff, base)) + assert isinstance(stuff, base) def test_subclasstuple(self): class subclass(tuple): pass stuff = subclass() - self.failUnless(isinstance(stuff, tuple)) + assert isinstance(stuff, tuple) stuff.attr = 23 - self.assertEquals(stuff.attr,23) - self.assertEquals(len(stuff),0) + assert stuff.attr ==23 + assert len(stuff) ==0 result = stuff + (1,2,3) - self.assertEquals(len(result),3) + assert len(result) ==3 def test_subsubclass(self): class base: @@ -54,9 +52,9 @@ class derived(base): derivedattr = 34 inst = derived() - self.failUnless(isinstance(inst, base)) - self.assertEquals(inst.baseattr,12) - self.assertEquals(inst.derivedattr,34) + assert isinstance(inst, base) + assert inst.baseattr ==12 + assert inst.derivedattr ==34 def test_descr_get(self): class C: @@ -64,7 +62,7 @@ def __get__(self, ob, cls=None): return 42 prop = desc() - self.assertEquals(C().prop, 42) + assert C().prop == 42 def test_descr_set(self): class C: @@ -74,7 +72,7 @@ prop = desc() c = C() c.prop = 32 - self.assertEquals(c.wibble, 32) + assert c.wibble == 32 def test_descr_delete(self): class C: @@ -86,63 +84,60 @@ prop = desc() c = C() del c.prop - self.assertEquals(c.wibble, 22) + assert c.wibble == 22 def test_class_setattr(self): class C: pass C.a = 1 - self.assert_(hasattr(C, 'a')) - self.assertEquals(C.a, 1) + assert hasattr(C, 'a') + assert C.a == 1 def test_add(self): class C: def __add__(self, other): return self, other c1 = C() - self.assertEquals(c1+3, (c1, 3)) + assert c1+3 == (c1, 3) def test_call(self): class C: def __call__(self, *args): return args c1 = C() - self.assertEquals(c1(), ()) - self.assertEquals(c1(5), (5,)) - self.assertEquals(c1("hello", "world"), ("hello", "world")) + assert c1() == () + assert c1(5) == (5,) + assert c1("hello", "world") == ("hello", "world") def test_getattribute(self): class C: def __getattribute__(self, name): return '->' + name c1 = C() - self.assertEquals(c1.a, '->a') + assert c1.a == '->a' c1.a = 5 - self.assertEquals(c1.a, '->a') + assert c1.a == '->a' def test_getattr(self): class C: def __getattr__(self, name): return '->' + name c1 = C() - self.assertEquals(c1.a, '->a') + assert c1.a == '->a' c1.a = 5 - self.assertEquals(c1.a, 5) + assert c1.a == 5 def test_dict(self): class A(object): pass class B(A): pass - self.failIf('__dict__' in object.__dict__) - self.assert_('__dict__' in A.__dict__) - self.failIf('__dict__' in B.__dict__) + assert not '__dict__' in object.__dict__ + assert '__dict__' in A.__dict__ + assert not '__dict__' in B.__dict__ a = A() a.x = 5 - self.assertEquals(a.__dict__, {'x': 5}) + assert a.__dict__ == {'x': 5} a.__dict__ = {'y': 6} - self.assertEquals(a.y, 6) - self.failIf(hasattr(a, 'x')) - -if __name__ == '__main__': - testit.main() + assert a.y == 6 + assert not hasattr(a, 'x') Modified: pypy/branch/src-pytest/pypy/tool/fiximport.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/fiximport.py (original) +++ pypy/branch/src-pytest/pypy/tool/fiximport.py Mon Jan 10 17:19:39 2005 @@ -43,8 +43,8 @@ return base_indent,lines pass_re = re.compile(r"^\s*pass\s*$") -getobjspace_re = r"testit\.objspace\((.*)\)" -setspace_re = r"self\.space\s*=\s*" +getobjspace_re = re.compile(r"testit\.objspace\((.*)\)") +setspace_re = re.compile(r"self\.space\s*=\s*") def up_down_port(lines): npass = 0 @@ -97,6 +97,9 @@ global_objspacename = False confused = False + + import_autopath_lineno = -1 + while True: if pushback: line = pushback.pop() @@ -168,6 +171,8 @@ else: print ' * ignored class', rest line = 'class ' + rest + '\n' + if line.rstrip() == "import autopath": + import_autopath_lineno = len(lines) lines.append(line) f.close() From hpk at codespeak.net Mon Jan 10 19:27:28 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 10 Jan 2005 19:27:28 +0100 (MET) Subject: [pypy-svn] r8199 - pypy/branch/src-pytest/pypy Message-ID: <20050110182728.EF2D527BC1@code1.codespeak.net> Author: hpk Date: Mon Jan 10 19:27:28 2005 New Revision: 8199 Modified: pypy/branch/src-pytest/pypy/conftest.py pypy/branch/src-pytest/pypy/test_all.py Log: - test_all is now more or less a synonym for py.test (or do we want to erase it all-together?) - a more fun docustring Modified: pypy/branch/src-pytest/pypy/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/conftest.py (original) +++ pypy/branch/src-pytest/pypy/conftest.py Mon Jan 10 19:27:28 2005 @@ -62,7 +62,8 @@ def collect_app_function(self, extpy): if extpy.check(func=1, basestarts='app_test_'): - assert not extpy.check(genfunc=1), "you must be joking" + assert not extpy.check(genfunc=1), ( + "generator app level functions? you must be joking") yield AppTestFunction(extpy) def collect_class(self, extpy): Modified: pypy/branch/src-pytest/pypy/test_all.py ============================================================================== --- pypy/branch/src-pytest/pypy/test_all.py (original) +++ pypy/branch/src-pytest/pypy/test_all.py Mon Jan 10 19:27:28 2005 @@ -1,8 +1,5 @@ #! /usr/bin/env python import tool.autopath -from pypy.tool import testit - -if __name__ == '__main__': - testit.main(tool.autopath.pypydir) - +from py.__impl__.test.cmdline import main +main() From tismer at codespeak.net Mon Jan 10 19:38:16 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 10 Jan 2005 19:38:16 +0100 (MET) Subject: [pypy-svn] r8200 - pypy/trunk/src/pypy/interpreter Message-ID: <20050110183816.13F5E27BC1@code1.codespeak.net> Author: tismer Date: Mon Jan 10 19:38:15 2005 New Revision: 8200 Modified: pypy/trunk/src/pypy/interpreter/pyopcode.py Log: for flow space: added a handler for missing UnboundLocalError, see NameError but XXX: There is a problem with the flow space. Do we need to redefine RPython to have no control paths which could generate this? Modified: pypy/trunk/src/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/pyopcode.py (original) +++ pypy/trunk/src/pypy/interpreter/pyopcode.py Mon Jan 10 19:38:15 2005 @@ -91,7 +91,14 @@ if w_value is UNDEFINED: varname = f.getlocalvarname(varindex) message = "local variable '%s' referenced before assignment" % varname - raise OperationError(f.space.w_UnboundLocalError, f.space.wrap(message)) + try: + w_exc_type = f.space.w_UnboundLocalError + w_exc_value = f.space.wrap(message) + except AttributeError: + # object space does not support it, so crash really + raise UnboundLocalError, (message + + ", but %s has no UnboundLocalError!" % f.space) + raise OperationError(w_exc_type, w_exc_value) f.valuestack.push(w_value) def LOAD_CONST(f, constindex): From ale at codespeak.net Tue Jan 11 08:58:41 2005 From: ale at codespeak.net (ale at codespeak.net) Date: Tue, 11 Jan 2005 08:58:41 +0100 (MET) Subject: [pypy-svn] r8201 - pypy/trunk/src/pypy/appspace Message-ID: <20050111075841.478E327BB3@code1.codespeak.net> Author: ale Date: Tue Jan 11 08:58:40 2005 New Revision: 8201 Added: pypy/trunk/src/pypy/appspace/struct.py Log: Added the start of a struct module. It is not quite finished yet. The structure of the code is basically as in structmodule.c. But some python goodies has been used - if that makes the module less RPython I don't know. TODO: Find a way to get information on native alignment and sizes. Convert the CPython tests to py.test Make the tests pass (all tests pass except a test for a floating point rounding error "SF bug 705836") Do some more error checking on floats (there is an empty function called "sane_float" which should do the checking. General cleanup of the code Added: pypy/trunk/src/pypy/appspace/struct.py ============================================================================== --- (empty file) +++ pypy/trunk/src/pypy/appspace/struct.py Tue Jan 11 08:58:40 2005 @@ -0,0 +1,343 @@ +import math,sys + +"""Functions to convert between Python values and C structs. +Python strings are used to hold the data representing the C struct +and also as format strings to describe the layout of data in the C struct. + +The optional first format char indicates byte order, size and alignment: + @: native order, size & alignment (default) + =: native order, std. size & alignment + <: little-endian, std. size & alignment + >: big-endian, std. size & alignment + !: same as > + +The remaining chars indicate types of args and must match exactly; +these can be preceded by a decimal repeat count: + x: pad byte (no data); + c:char; + b:signed byte; + B:unsigned byte; + h:short; + H:unsigned short; + i:int; + I:unsigned int; + l:long; + L:unsigned long; + f:float; + d:double. +Special cases (preceding decimal count indicates length): + s:string (array of char); p: pascal string (with count byte). +Special case (only available in native format): + P:an integer type that is wide enough to hold a pointer. +Special case (not in native mode unless 'long long' in platform C): + q:long long; + Q:unsigned long long +Whitespace between formats is ignored. + +The variable struct.error is an exception raised on errors.""" + +# TODO: XXX Find a way to get information on native sizes and alignments +class StructError(Exception): + pass +error = StructError +def unpack_int(data,index,size,le): + bytes = [ord(b) for b in data[index:index+size]] + if le == 'little': + bytes.reverse() + number = 0 + for b in bytes: + number = number << 8 | b + return number + +def unpack_signed_int(data,index,size,le): + number = unpack_int(data,index,size,le) + max = 2**(size*8) + if number > 2**(size*8 - 1) - 1: + number = -1*(max - number) + return number + +def unpack_float(data,index,size,le): + bytes = [ord(b) for b in data[index:index+size]] + if len(bytes) != size: + raise StructError,"Not enough data to unpack" + if le == 'big': + bytes.reverse() + if size == 4: + bias = 127 + exp = 8 + prec = 23 + else: + bias = 1023 + exp = 11 + prec = 52 +# print bytes,size,index,len(data),data + mantissa = bytes[size-2] & (2**(15-exp)-1) +# print mantissa + for b in bytes[size-3::-1]: + mantissa = mantissa << 8 | b +# print mantissa + mantissa = 1 + (1.0*mantissa)/(2**(prec)) + mantissa /= 2 +# print mantissa + e = (bytes[-1] & 0x7f) << (exp - 7) + e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1) + e -= bias + e += 1 + sign = bytes[-1] & 0x80 + number = math.ldexp(mantissa,e) +# print number,index,mantissa,e,bytes#,data + if sign : number *= -1 + return number + +def unpack_char(data,index,size,le): + return data[index:index+size] + +def pack_int(number,size,le): + x=number + res=[] + for i in range(size): + res.append(chr(x&0xff)) + x >>= 8 + if le == 'big': + res.reverse() + return ''.join(res) + +def pack_signed_int(number,size,le): + if type(number) not in [int,long]: + raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" + if number > 2**(8*size-1)-1 or number < -1*2**(8*size-1): + raise OverflowError,"Number:%i to large to convert" % number + return pack_int(number,size,le) + +def pack_unsigned_int(number,size,le): + if type(number) not in [int,long]: + raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" + if number < 0: + raise TypeError,"can't convert negative long to unsigned" + if number > 2**(8*size)-1: + raise OverflowError,"Number:%i to large to convert" % number + return pack_int(number,size,le) + +def pack_char(char,size,le): +# print char + return str(char) + +def sane_float(man,e): + # TODO: XXX Implement checks for floats + return True + +def pack_float(number,size,le): + + if number < 0: + sign=1 + number *= -1 + else: + sign =0 + if size == 4: + bias = 127 + exp = 8 + prec = 23 + else: + bias = 1023 + exp = 11 + prec = 52 + + man,e = math.frexp(number) + if 0.5 <= man and man < 1.0: + man *= 2 + e -= 1 + if sane_float(man,e): + man -= 1 + e += bias + mantissa = int(2**prec *(man) +0.5) + res=[] + + for i in range(size-2): + res += [ mantissa & 0xff] + mantissa >>= 8 + res += [ (mantissa & (2**(15-exp)-1)) | ((e & (2**(exp-7)-1))<<(15-exp))] + res += [sign << 7 | e >> (exp - 7)] + if le == 'big': + res.reverse() + return ''.join([chr(x) for x in res]) + # TODO: What todo with insane floats/doubles. handle in sanefloat? + +big_endian_format = { + 'x':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, + 'b':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, + 'B':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, + 'c':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_char, 'unpack' : unpack_char}, + 's':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, + 'p':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, + 'h':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, + 'H':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, + 'i':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, + 'I':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, + 'l':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, + 'L':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, + 'q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, + 'Q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, + 'f':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, + 'd':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, + } +default = big_endian_format +formatmode={ '<' : (default, 'little'), + '>' : (default, 'big'), + '!' : (default, 'big'), + '=' : (default, sys.byteorder), + '@' : (default, sys.byteorder) + } + +def getmode(fmt): + try: + formatdef,endianness = formatmode[fmt[0]] + index = 1 + except KeyError: + formatdef,endianness = formatmode['@'] + index = 0 + return formatdef,endianness,index +def getNum(fmt,i): + num=None + cur = fmt[i] + while ('0'<= cur ) and ( cur <= '9'): + if num == None: + num = int(cur) + else: + num = 10*num + int(cur) + i += 1 + cur = fmt[i] + return num,i + +def calcsize(fmt): + """calcsize(fmt) -> int + Return size of C struct described by format string fmt. + See struct.__doc__ for more on format strings.""" + + formatdef,endianness,i = getmode(fmt) + num = 0 + result = 0 + while i string + Return string containing values v1, v2, ... packed according to fmt. + See struct.__doc__ for more on format strings.""" + formatdef,endianness,i = getmode(fmt) + args = list(args) + n_args = len(args) + result = [] + while i=0: + result += [args[0][:num] + '\0'*padding] + else: + result += [args[0][:num]] + args.pop() + else: + raise StructError,"arg for string format not a string" + elif cur == 'p': + if type(args[0]) == str: + padding = num - len(args[0]) - 1 + + if padding > 0: + result += [chr(len(args[0])) + args[0][:num-1] + '\0'*padding] + else: + if num<255: + result += [chr(num-1) + args[0][:num-1]] + else: + result += [chr(255) + args[0][:num-1]] + args.pop() + else: + raise StructError,"arg for string format not a string" + + else: + if len(args) == 0: + raise StructError,"insufficient arguments to pack" + for var in args[:num]: + result += [format['pack'](var,format['size'],endianness)] + args=args[num:] + num = None + i += 1 + if len(args) != 0: + raise StructError,"too many arguments for pack format" + return ''.join(result) + +def unpack(fmt,data): + """unpack(fmt, string) -> (v1, v2, ...) + Unpack the string, containing packed C structure data, according + to fmt. Requires len(string)==calcsize(fmt). + See struct.__doc__ for more on format strings.""" + formatdef,endianness,i = getmode(fmt) +# print fmt,data + j = 0 + num = 0 + result = [] + length= calcsize(fmt) + if length != len (data): + raise StructError,"unpack str size does not match format" + while i= num: + n = num-1 + result.append(data[j+1:j+n+1]) + j += num + i += 1 + else: + for n in range(num): + result += [format['unpack'](data,j,format['size'],endianness)] + j += format['size'] + i += 1 + + return result + +if __name__ == '__main__': + print pack_float(1.23,4,'little') + import struct + print struct.pack('f',1.23), pack('f',1.23) + print unpack('f',pack('f',1.23)) \ No newline at end of file From hpk at codespeak.net Tue Jan 11 13:59:14 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 13:59:14 +0100 (MET) Subject: [pypy-svn] r8203 - in pypy/branch/src-pytest/pypy/appspace: . test Message-ID: <20050111125914.0EFB727BBE@code1.codespeak.net> Author: hpk Date: Tue Jan 11 13:59:13 2005 New Revision: 8203 Added: pypy/branch/src-pytest/pypy/appspace/cpy_test_types.py - copied unchanged from r8172, pypy/branch/src-pytest/pypy/appspace/builtin_types_test.py pypy/branch/src-pytest/pypy/appspace/test/conftest.py pypy/branch/src-pytest/pypy/appspace/test/cpy_test_types.py - copied unchanged from r8175, pypy/branch/src-pytest/pypy/appspace/builtin_types_test.py pypy/branch/src-pytest/pypy/appspace/test/support_tests.py - copied, changed from r8175, pypy/branch/src-pytest/pypy/appspace/support_tests.py Removed: pypy/branch/src-pytest/pypy/appspace/builtin_types_test.py pypy/branch/src-pytest/pypy/appspace/support_tests.py Modified: pypy/branch/src-pytest/pypy/appspace/test/test_cmathmodule.py pypy/branch/src-pytest/pypy/appspace/test/test_exceptions.py pypy/branch/src-pytest/pypy/appspace/test/test_file.py pypy/branch/src-pytest/pypy/appspace/test/test_sha.py pypy/branch/src-pytest/pypy/appspace/test/test_sio.py Log: - moved tests to test subdirectory - a beginning of running regr-tests (cpy_test_types.py) over PyPy the whole appspace needs refactoring probably along the lines of merging with modules and dealing with cpython regr-tests separately. Deleted: /pypy/branch/src-pytest/pypy/appspace/builtin_types_test.py ============================================================================== --- /pypy/branch/src-pytest/pypy/appspace/builtin_types_test.py Tue Jan 11 13:59:13 2005 +++ (empty file) @@ -1,787 +0,0 @@ -# Python test set -- part 6, built-in types -# Slightly edited version for PyPy. - -from support_tests import * - -print '6. Built-in types' - -print '6.1 Truth value testing' -if None: raise TestFailed, 'None is true instead of false' -if 0: raise TestFailed, '0 is true instead of false' -if 0L: raise TestFailed, '0L is true instead of false' -if 0.0: raise TestFailed, '0.0 is true instead of false' -if '': raise TestFailed, '\'\' is true instead of false' -if (): raise TestFailed, '() is true instead of false' -if []: raise TestFailed, '[] is true instead of false' -if {}: raise TestFailed, '{} is true instead of false' -if not 1: raise TestFailed, '1 is false instead of true' -if not 1L: raise TestFailed, '1L is false instead of true' -if not 1.0: raise TestFailed, '1.0 is false instead of true' -if not 'x': raise TestFailed, '\'x\' is false instead of true' -if not (1, 1): raise TestFailed, '(1, 1) is false instead of true' -if not [1]: raise TestFailed, '[1] is false instead of true' -if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true' -def f(): pass -class C: pass -import sys -x = C() -if not f: raise TestFailed, 'f is false instead of true' -if not C: raise TestFailed, 'C is false instead of true' -if not sys: raise TestFailed, 'sys is false instead of true' -if not x: raise TestFailed, 'x is false instead of true' - -print '6.2 Boolean operations' -if 0 or 0: raise TestFailed, '0 or 0 is true instead of false' -if 1 and 1: pass -else: raise TestFailed, '1 and 1 is false instead of false' -if not 1: raise TestFailed, 'not 1 is true instead of false' - -print '6.3 Comparisons' -if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass -else: raise TestFailed, 'int comparisons failed' -if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass -else: raise TestFailed, 'long int comparisons failed' -if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass -else: raise TestFailed, 'float comparisons failed' -if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass -else: raise TestFailed, 'string comparisons failed' -if 0 in [0] and 0 not in [1]: pass -else: raise TestFailed, 'membership test failed' -if None is None and [] is not []: pass -else: raise TestFailed, 'identity test failed' - - -print '6.3.1 Conversion errors' -try: float('') -except ValueError: pass -else: raise TestFailed, "float('') didn't raise ValueError" - -try: float('5\0') -except ValueError: pass -else: raise TestFailed, "float('5\0') didn't raise ValueError" - -print '6.3.2 Division errors' -try: 5.0 / 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError" - -try: 5.0 // 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError" - -try: 5.0 % 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError" - -try: 5L / 0 -except ZeroDivisionError: pass -else: raise TestFailed, "5L / 0 didn't raise ZeroDivisionError" - -try: 5 / 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError" - -try: 5 // 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError" - -try: 5 % 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError" - -print '6.4 Numeric types (mostly conversions)' -if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons' -if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons' -if -1 != -1L or -1 != -1.0 or -1L != -1.0: - raise TestFailed, 'int/long/float value not equal' -# calling built-in types without argument must return 0 -if int() != 0: raise TestFailed, 'int() does not return 0' -if long() != 0L: raise TestFailed, 'long() does not return 0L' -if float() != 0.0: raise TestFailed, 'float() does not return 0.0' -if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass -else: raise TestFailed, 'int() does not round properly' -if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass -else: raise TestFailed, 'long() does not round properly' -if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass -else: raise TestFailed, 'float() does not work properly' -print '6.4.1 32-bit integers' -if 12 + 24 != 36: raise TestFailed, 'int op' -if 12 + (-24) != -12: raise TestFailed, 'int op' -if (-12) + 24 != 12: raise TestFailed, 'int op' -if (-12) + (-24) != -36: raise TestFailed, 'int op' -if not 12 < 24: raise TestFailed, 'int op' -if not -24 < -12: raise TestFailed, 'int op' -# Test for a particular bug in integer multiply -xsize, ysize, zsize = 238, 356, 4 -if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): - raise TestFailed, 'int mul commutativity' -# And another. -m = -sys.maxint - 1 -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - prod = divisor * j - if prod != m: - raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m) - if type(prod) is not int: - raise TestFailed, ("expected type(prod) to be int, not %r" % - type(prod)) -# Check for expected * overflow to long. -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) -# Check for expected * overflow to long. -m = sys.maxint -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor + 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) - -print '6.4.2 Long integers' -if 12L + 24L != 36L: raise TestFailed, 'long op' -if 12L + (-24L) != -12L: raise TestFailed, 'long op' -if (-12L) + 24L != 12L: raise TestFailed, 'long op' -if (-12L) + (-24L) != -36L: raise TestFailed, 'long op' -if not 12L < 24L: raise TestFailed, 'long op' -if not -24L < -12L: raise TestFailed, 'long op' -x = sys.maxint -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)+1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' -x = -x -if int(long(x)) != x: raise TestFailed, 'long op' -x = x-1 -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)-1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' - -try: 5 << -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift <<' - -try: 5L << -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift <<' - -try: 5 >> -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift >>' - -try: 5L >> -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift >>' - -print '6.4.3 Floating point numbers' -if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op' -if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op' -if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op' -if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op' -if not 12.0 < 24.0: raise TestFailed, 'float op' -if not -24.0 < -12.0: raise TestFailed, 'float op' - -print '6.5 Sequence types' - -print '6.5.1 Strings' -if len('') != 0: raise TestFailed, 'len(\'\')' -if len('a') != 1: raise TestFailed, 'len(\'a\')' -if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')' -if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation' -if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3' -if 0*'abcde' != '': raise TestFailed, 'string repetition 0*' -if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string' -if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass -else: raise TestFailed, 'in/not in string' -x = 'x'*103 -if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug' - -#extended slices for strings -a = '0123456789' -vereq(a[::], a) -vereq(a[::2], '02468') -vereq(a[1::2], '13579') -vereq(a[::-1],'9876543210') -vereq(a[::-2], '97531') -vereq(a[3::-2], '31') -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], '02468') - -if have_unicode: - a = unicode('0123456789', 'ascii') - vereq(a[::], a) - vereq(a[::2], unicode('02468', 'ascii')) - vereq(a[1::2], unicode('13579', 'ascii')) - vereq(a[::-1], unicode('9876543210', 'ascii')) - vereq(a[::-2], unicode('97531', 'ascii')) - vereq(a[3::-2], unicode('31', 'ascii')) - vereq(a[-100:100:], a) - vereq(a[100:-100:-1], a[::-1]) - vereq(a[-100L:100L:2L], unicode('02468', 'ascii')) - - -print '6.5.2 Tuples' -# calling built-in types without argument must return empty -if tuple() != (): raise TestFailed,'tuple() does not return ()' -if len(()) != 0: raise TestFailed, 'len(())' -if len((1,)) != 1: raise TestFailed, 'len((1,))' -if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))' -if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation' -if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3' -if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*' -if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple' -if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass -else: raise TestFailed, 'in/not in tuple' -try: ()[0] -except IndexError: pass -else: raise TestFailed, "tuple index error didn't raise IndexError" -x = () -x += () -if x != (): raise TestFailed, 'tuple inplace add from () to () failed' -x += (1,) -if x != (1,): raise TestFailed, 'tuple resize from () failed' - -# extended slicing - subscript only for tuples -a = (0,1,2,3,4) -vereq(a[::], a) -vereq(a[::2], (0,2,4)) -vereq(a[1::2], (1,3)) -vereq(a[::-1], (4,3,2,1,0)) -vereq(a[::-2], (4,2,0)) -vereq(a[3::-2], (3,1)) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], (0,2,4)) - -# Check that a specific bug in _PyTuple_Resize() is squashed. -def f(): - for i in range(1000): - yield i -vereq(list(tuple(f())), range(1000)) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO: this fails with PyPy because overriding __getitem__ will -# really override what the sequence iterator returns -#class T(tuple): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(T((1,2))).next(), 1) - -print '6.5.3 Lists' -# calling built-in types without argument must return empty -if list() != []: raise TestFailed,'list() does not return []' -if len([]) != 0: raise TestFailed, 'len([])' -if len([1,]) != 1: raise TestFailed, 'len([1,])' -if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])' -if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation' -if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3' -if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L' -if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*' -if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*' -if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list' -if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass -else: raise TestFailed, 'in/not in list' -a = [1, 2, 3, 4, 5] -a[:-1] = a -if a != [1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (head)" -a = [1, 2, 3, 4, 5] -a[1:] = a -if a != [1, 1, 2, 3, 4, 5]: - raise TestFailed, "list self-slice-assign (tail)" -a = [1, 2, 3, 4, 5] -a[1:-1] = a -if a != [1, 1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (center)" -try: [][0] -except IndexError: pass -else: raise TestFailed, "list index error didn't raise IndexError" -try: [][0] = 5 -except IndexError: pass -else: raise TestFailed, "list assignment index error didn't raise IndexError" -try: [].pop() -except IndexError: pass -else: raise TestFailed, "empty list.pop() didn't raise IndexError" -try: [1].pop(5) -except IndexError: pass -else: raise TestFailed, "[1].pop(5) didn't raise IndexError" -try: [][0:1] = 5 -except TypeError: pass -else: raise TestFailed, "bad list slice assignment didn't raise TypeError" -try: [].extend(None) -except TypeError: pass -else: raise TestFailed, "list.extend(None) didn't raise TypeError" -a = [1, 2, 3, 4] -a *= 0 -if a != []: - raise TestFailed, "list inplace repeat" - -a = [] -a[:] = tuple(range(10)) -if a != range(10): - raise TestFailed, "assigning tuple to slice" - -print '6.5.3a Additional list operations' -a = [0,1,2,3,4] -a[0L] = 1 -a[1L] = 2 -a[2L] = 3 -if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]' -a[0] = 5 -a[1] = 6 -a[2] = 7 -if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]' -a[-2L] = 88 -a[-1L] = 99 -if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]' -a[-2] = 8 -a[-1] = 9 -if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]' -a[:2] = [0,4] -a[-3:] = [] -a[1:1] = [1,2,3] -if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment' -a[ 1L : 4L] = [7,8,9] -if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints' -del a[1:4] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=range(0,5) -del a[1L:4L] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0L] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1L] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=[] -a.append(0) -a.append(1) -a.append(2) -if a != [0,1,2]: raise TestFailed, 'list append' -a.insert(0, -2) -a.insert(1, -1) -a.insert(2,0) -if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert' -b = a[:] -b.insert(-2, "foo") -b.insert(-200, "left") -b.insert(200, "right") -if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2' -# a = [-2,-1,0,0,1,2] -if a.count(0) != 2: raise TestFailed, ' list count' -if a.index(0) != 2: raise TestFailed, 'list index' -if a.index(0,2) != 2: raise TestFailed, 'list index, start argument' -if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' -if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument' -if a.index(0,3) != 3: raise TestFailed, 'list index, start argument' -if a.index(0,-3) != 3: raise TestFailed, 'list index, -start argument' -if a.index(0,3,4) != 3: raise TestFailed, 'list index, stop argument' -if a.index(0,-3,-2) != 3: raise TestFailed, 'list index, -stop argument' -if a.index(0,-4*sys.maxint,4*sys.maxint) != 2: - raise TestFailed, 'list index, -maxint, maxint argument' -try: - a.index(0, 4*sys.maxint,-4*sys.maxint) -except ValueError: - pass -else: - raise TestFailed, 'list index, maxint,-maxint argument' - -try: - a.index(2,0,-10) -except ValueError: - pass -else: - raise TestFailed, 'list index, very -stop argument' -a.remove(0) -try: - a.index(2,0,4) -except ValueError: - pass -else: - raise TestFailed, 'list index, stop argument.' -if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove' -a.reverse() -if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse' -a.sort() -if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort' -def revcmp(a, b): return cmp(b, a) -a.sort(revcmp) -if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func' -# The following dumps core in unpatched Python 1.5: -def myComparison(x,y): - return cmp(x%3, y%7) -z = range(12) -z.sort(myComparison) - -try: z.sort(2) -except TypeError: pass -else: raise TestFailed, 'list sort compare function is not callable' - -''' XXX TODO: add detection of list modification during sort -def selfmodifyingComparison(x,y): - z.append(1) - return cmp(x, y) -try: z.sort(selfmodifyingComparison) -except ValueError: pass -else: raise TestFailed, 'modifying list during sort' -''' - -try: z.sort(lambda x, y: 's') -except TypeError: pass -else: raise TestFailed, 'list sort compare function does not return int' - -# Test extreme cases with long ints -a = [0,1,2,3,4] -if a[ -pow(2,128L): 3 ] != [0,1,2]: - raise TestFailed, "list slicing with too-small long integer" -if a[ 3: pow(2,145L) ] != [3,4]: - raise TestFailed, "list slicing with too-large long integer" - -# extended slicing - -# subscript -a = [0,1,2,3,4] -vereq(a[::], a) -vereq(a[::2], [0,2,4]) -vereq(a[1::2], [1,3]) -vereq(a[::-1], [4,3,2,1,0]) -vereq(a[::-2], [4,2,0]) -vereq(a[3::-2], [3,1]) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], [0,2,4]) -vereq(a[1000:2000:2], []) -vereq(a[-1000:-2000:-2], []) -# deletion -del a[::2] -vereq(a, [1,3]) -a = range(5) -del a[1::2] -vereq(a, [0,2,4]) -a = range(5) -del a[1::-2] -vereq(a, [0,2,3,4]) -a = range(10) -del a[::1000] -vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9]) -# assignment -a = range(10) -a[::2] = [-1]*5 -vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]) -a = range(10) -a[::-4] = [10]*3 -vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]) -a = range(4) -a[::-1] = a -vereq(a, [3, 2, 1, 0]) -a = range(10) -b = a[:] -c = a[:] -a[2:3] = ["two", "elements"] -b[slice(2,3)] = ["two", "elements"] -c[2:3:] = ["two", "elements"] -vereq(a, b) -vereq(a, c) -a = range(10) -a[::2] = tuple(range(5)) -vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9]) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO same as class T(tuple) above -#class L(list): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(L([1,2])).next(), 1) - - -print '6.6 Mappings == Dictionaries' -# calling built-in types without argument must return empty -if dict() != {}: raise TestFailed,'dict() does not return {}' -d = {} -if d.keys() != []: raise TestFailed, '{}.keys()' -if d.values() != []: raise TestFailed, '{}.values()' -if d.items() != []: raise TestFailed, '{}.items()' -if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')' -if ('a' in d) != 0: raise TestFailed, "'a' in {}" -if ('a' not in d) != 1: raise TestFailed, "'a' not in {}" -if len(d) != 0: raise TestFailed, 'len({})' -d = {'a': 1, 'b': 2} -if len(d) != 2: raise TestFailed, 'len(dict)' -k = d.keys() -k.sort() -if k != ['a', 'b']: raise TestFailed, 'dict keys()' -if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass -else: raise TestFailed, 'dict keys()' -if 'a' in d and 'b' in d and 'c' not in d: pass -else: raise TestFailed, 'dict keys() # in/not in version' -if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item' -d['c'] = 3 -d['a'] = 4 -if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment' -del d['b'] -if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion' -print '6.6.1 dict methods' -# dict.clear() -d = {1:1, 2:2, 3:3} -d.clear() -if d != {}: raise TestFailed, 'dict clear' -# dict.update() -d.update({1:100}) -d.update({2:20}) -d.update({1:1, 2:2, 3:3}) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update' -d.clear() -try: d.update(None) -except AttributeError: pass -else: raise TestFailed, 'dict.update(None), AttributeError expected' -print '6.6.2 user-dict methods' -class SimpleUserDict: - def __init__(self): - self.d = {1:1, 2:2, 3:3} - def keys(self): - return self.d.keys() - def __getitem__(self, i): - return self.d[i] -d.update(SimpleUserDict()) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)' -d.clear() -class FailingUserDict: - def keys(self): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.keys() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __iter__(self): - raise ValueError - return BogonIter() -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()) expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = 1 - def __iter__(self): - return self - def next(self): - if self.i: - self.i = 0 - return 'a' - raise ValueError - return BogonIter() - def __getitem__(self, key): - return key -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = ord('a') - def __iter__(self): - return self - def next(self): - if self.i <= ord('z'): - rtn = chr(self.i) - self.i += 1 - return rtn - raise StopIteration - return BogonIter() - def __getitem__(self, key): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError' -print '6.6.3 dict.fromkeys' -# dict.fromkeys() -if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys did not work as a class method' -d = {} -if d.fromkeys('abc') is d: - raise TestFailed, 'dict.fromkeys did not return a new dict' -if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys failed with default value' -if d.fromkeys((4,5),0) != {4:0, 5:0}: - raise TestFailed, 'dict.fromkeys failed with specified value' -if d.fromkeys([]) != {}: - raise TestFailed, 'dict.fromkeys failed with null sequence' -def g(): - yield 1 -if d.fromkeys(g()) != {1:None}: - raise TestFailed, 'dict.fromkeys failed with a generator' -try: {}.fromkeys(3) -except TypeError: pass -else: raise TestFailed, 'dict.fromkeys failed to raise TypeError' -class dictlike(dict): pass -if dictlike.fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if dictlike().fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if type(dictlike.fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' -if type(dictlike().fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' - -from UserDict import UserDict -class mydict(dict): - def __new__(cls): - return UserDict() -ud = mydict.fromkeys('ab') -if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): - raise TestFailed, 'fromkeys did not instantiate using __new__' - -print '6.6.4 dict copy, get, setdefault' - -# dict.copy() -d = {1:1, 2:2, 3:3} -if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy' -if {}.copy() != {}: raise TestFailed, 'empty dict copy' -# dict.get() -d = {} -if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg' -d = {'a' : 1, 'b' : 2} -if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg' -if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg' -if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg' -# dict.setdefault() -d = {} -if d.setdefault('key0') is not None: - raise TestFailed, 'missing {} setdefault, no 2nd arg' -if d.setdefault('key0') is not None: - raise TestFailed, 'present {} setdefault, no 2nd arg' -d.setdefault('key', []).append(3) -if d['key'][0] != 3: - raise TestFailed, 'missing {} setdefault, w/ 2nd arg' -d.setdefault('key', []).append(4) -if len(d['key']) != 2: - raise TestFailed, 'present {} setdefault, w/ 2nd arg' - -print '6.6.5 dict popitem' - -# dict.popitem() -for copymode in -1, +1: - # -1: b has same structure as a - # +1: b is a.copy() - for log2size in range(4):#(12): - size = 2**log2size - a = {} - b = {} - for i in range(size): - a[`i`] = i - if copymode < 0: - b[`i`] = i - if copymode > 0: - b = a.copy() - for i in range(size): - ka, va = ta = a.popitem() - if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta) - kb, vb = tb = b.popitem() - if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb) - if copymode < 0 and ta != tb: - raise TestFailed, "a.popitem != b.popitem: %s, %s" % ( - str(ta), str(tb)) - if a: raise TestFailed, 'a not empty after popitems: %s' % str(a) - if b: raise TestFailed, 'b not empty after popitems: %s' % str(b) - -d.clear() -try: d.popitem() -except KeyError: pass -else: raise TestFailed, "{}.popitem doesn't raise KeyError" - -print '6.6.6 dict pop' - -# Tests for pop with specified key -d.clear() -k, v = 'abc', 'def' -d[k] = v -try: d.pop('ghi') -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary" - -if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair" -if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair" - -try: d.pop(k) -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty" - -# verify longs/ints get same value when key > 32 bits (for 64-bit archs) -# see SF bug #689659 -x = 4503599627370496L -y = 4503599627370496 -h = {x: 'anything', y: 'something else'} -if h[x] != h[y]: - raise TestFailed, "long/int key should match" - -if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value" -d[k] = v -if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair" - -''' TODO: doesn't raise correctly -d[1] = 1 -try: - for i in d: - d[i+1] = 1 -except RuntimeError: - pass -else: - raise TestFailed, "changing dict size during iteration doesn't raise Error" -''' - -print '6.7 type' - -try: type(1, 2) -except TypeError: pass -else: raise TestFailed, 'type(), w/2 args expected TypeError' - -try: type(1, 2, 3, 4) -except TypeError: pass -else: raise TestFailed, 'type(), w/4 args expected TypeError' - -''' TODO: No buffer support yet XXX -print '6.8 buffer' - -try: buffer('asdf', -1) -except ValueError: pass -else: raise TestFailed, "buffer('asdf', -1) should raise ValueError" - -try: buffer(None) -except TypeError: pass -else: raise TestFailed, "buffer(None) should raise TypeError" - -a = buffer('asdf') -hash(a) -b = a * 5 -if a == b: - raise TestFailed, 'buffers should not be equal' -if str(b) != ('asdf' * 5): - raise TestFailed, 'repeated buffer has wrong content' -if str(a * 0) != '': - raise TestFailed, 'repeated buffer zero times has wrong content' -if str(a + buffer('def')) != 'asdfdef': - raise TestFailed, 'concatenation of buffers yields wrong content' - -try: a[1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer assignment should raise TypeError" - -try: a[0:1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer slice assignment should raise TypeError" -''' -print '6.99999999... All tests ran to completion' Deleted: /pypy/branch/src-pytest/pypy/appspace/support_tests.py ============================================================================== --- /pypy/branch/src-pytest/pypy/appspace/support_tests.py Tue Jan 11 13:59:13 2005 +++ (empty file) @@ -1,190 +0,0 @@ -"""Supporting definitions for the Python regression tests.""" - -''' -if __name__ != 'test.test_support': - raise ImportError, 'test_support must be imported from the test package' -''' - -import sys -from os import unlink - -class Error(Exception): - """Base class for regression test exceptions.""" - -class TestFailed(Error): - """Test failed.""" - -class TestSkipped(Error): - """Test skipped. - - This can be raised to indicate that a test was deliberatly - skipped, but not because a feature wasn't available. For - example, if some resource can't be used, such as the network - appears to be unavailable, this should be raised instead of - TestFailed. - """ - -class ResourceDenied(TestSkipped): - """Test skipped because it requested a disallowed resource. - - This is raised when a test calls requires() for a resource that - has not be enabled. It is used to distinguish between expected - and unexpected skips. - """ - -verbose = 1 # Flag set to 0 by regrtest.py -use_resources = None # Flag set to [] by regrtest.py - -# _original_stdout is meant to hold stdout at the time regrtest began. -# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. -# The point is to have some flavor of stdout the user can actually see. -_original_stdout = None -def record_original_stdout(stdout): - global _original_stdout - _original_stdout = stdout - -def get_original_stdout(): - return _original_stdout or sys.stdout - -def unload(name): - try: - del sys.modules[name] - except KeyError: - pass - -def forget(modname): - '''"Forget" a module was ever imported by removing it from sys.modules and - deleting any .pyc and .pyo files.''' - unload(modname) - import os - for dirname in sys.path: - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) - except os.error: - pass - # Deleting the .pyo file cannot be within the 'try' for the .pyc since - # the chance exists that there is no .pyc (and thus the 'try' statement - # is exited) but there is a .pyo file. - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) - except os.error: - pass - -def is_resource_enabled(resource): - """Test whether a resource is enabled. Known resources are set by - regrtest.py.""" - return use_resources is not None and resource in use_resources - -def requires(resource, msg=None): - """Raise ResourceDenied if the specified resource is not available. - - If the caller's module is __main__ then automatically return True. The - possibility of False being returned occurs when regrtest.py is executing.""" - # see if the caller's module is __main__ - if so, treat as if - # the resource was set - if sys._getframe().f_back.f_globals.get("__name__") == "__main__": - return - if not is_resource_enabled(resource): - if msg is None: - msg = "Use of the `%s' resource not enabled" % resource - raise ResourceDenied(msg) - -FUZZ = 1e-6 - -def fcmp(x, y): # fuzzy comparison function - if type(x) == type(0.0) or type(y) == type(0.0): - try: - x, y = float(x), float(y) - fuzz = (abs(x) + abs(y)) * FUZZ - if abs(x-y) <= fuzz: - return 0 - except: - pass - elif type(x) == type(y) and type(x) in (type(()), type([])): - for i in range(min(len(x), len(y))): - outcome = fcmp(x[i], y[i]) - if outcome != 0: - return outcome - return cmp(len(x), len(y)) - return cmp(x, y) - -try: - unicode - have_unicode = 1 -except NameError: - have_unicode = 0 - -is_jython = sys.platform.startswith('java') - -TESTFN = '@test' - -# Make sure we can write to TESTFN, try in /tmp if we can't -fp = None -try: - fp = open(TESTFN, 'w+') -except IOError: - TMP_TESTFN = os.path.join('/tmp', TESTFN) - try: - fp = open(TMP_TESTFN, 'w+') - TESTFN = TMP_TESTFN - del TMP_TESTFN - except IOError: - print ('WARNING: tests will fail, unable to write to: %s or %s' % - (TESTFN, TMP_TESTFN)) -if fp is not None: - fp.close() -del fp - -def findfile(file, here=__file__): - """Try to find a file on sys.path and the working directory. If it is not - found the argument passed to the function is returned (this does not - necessarily signal failure; could still be the legitimate path).""" - import os - if os.path.isabs(file): - return file - path = sys.path - path = [os.path.dirname(here)] + path - for dn in path: - fn = os.path.join(dn, file) - if os.path.exists(fn): return fn - return file - -def verify(condition, reason='test failed'): - """Verify that condition is true. If not, raise TestFailed. - - The optional argument reason can be given to provide - a better error text. - """ - - if not condition: - raise TestFailed(reason) - -def vereq(a, b): - """Raise TestFailed if a == b is false. - - This is better than verify(a == b) because, in case of failure, the - error message incorporates repr(a) and repr(b) so you can see the - inputs. - - Note that "not (a == b)" isn't necessarily the same as "a != b"; the - former is tested. - """ - - if not (a == b): - raise TestFailed, "%r == %r" % (a, b) - -def sortdict(dict): - "Like repr(dict), but in sorted order." - items = dict.items() - items.sort() - reprpairs = ["%r: %r" % pair for pair in items] - withcommas = ", ".join(reprpairs) - return "{%s}" % withcommas - -def check_syntax(statement): - try: - compile(statement, '', 'exec') - except SyntaxError: - pass - else: - print 'Missing SyntaxError: "%s"' % statement Added: pypy/branch/src-pytest/pypy/appspace/test/conftest.py ============================================================================== --- (empty file) +++ pypy/branch/src-pytest/pypy/appspace/test/conftest.py Tue Jan 11 13:59:13 2005 @@ -0,0 +1,25 @@ +from __future__ import generators + +import py +from pypy.conftest import getobjspace, PyPyItem +from pypy.interpreter.main import run_string + +class Directory(py.test.collect.Directory): + def __iter__(self): + for path in self.fspath.listdir(): + if path.check(fnmatch='cpy_test_*.py', file=1): + continue + #XXX yield RunFileAtAppLevelItem(py.path.extpy(path)) + elif self.fil(path): + if path.basename in ('test_complexobject.py',): + continue + yield self.Module(path) + elif self.rec(path): + yield self.Directory(path) + +class RunFileAtAppLevelItem(PyPyItem): + def run(self, driver): + space = getobjspace() + source = self.extpy.root.read() + #self.execute_appex(space, run_string, source, str(self.extpy.root), space) + run_string(source, str(self.extpy.root), space) Copied: pypy/branch/src-pytest/pypy/appspace/test/support_tests.py (from r8175, pypy/branch/src-pytest/pypy/appspace/support_tests.py) ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/support_tests.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/support_tests.py Tue Jan 11 13:59:13 2005 @@ -116,6 +116,7 @@ is_jython = sys.platform.startswith('java') + TESTFN = '@test' # Make sure we can write to TESTFN, try in /tmp if we can't Modified: pypy/branch/src-pytest/pypy/appspace/test/test_cmathmodule.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_cmathmodule.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_cmathmodule.py Tue Jan 11 13:59:13 2005 @@ -15,7 +15,6 @@ import unittest import autopath -from pypy.tool import testit from pypy.appspace import cmathmodule from pypy.appspace.test.test_complexobject import equal @@ -30,7 +29,7 @@ -class TestCMathModule(testit.TestCase): +class TestCMathModule: def assertAEqual(self, a, b): if not equal(a, b): @@ -61,6 +60,3 @@ op1 = cmathmodule.__dict__[op](z) self.assertAEqual(op0, op1) - -if __name__ == "__main__": - testit.main() Modified: pypy/branch/src-pytest/pypy/appspace/test/test_exceptions.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_exceptions.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_exceptions.py Tue Jan 11 13:59:13 2005 @@ -1,10 +1,5 @@ import autopath -from pypy.tool import testit -class A(testit.AppTestCase): - def test_import(self): - import exceptions - assert exceptions.SyntaxError is SyntaxError - -if __name__ == '__main__': - testit.main() +def app_test_import(): + import exceptions + assert exceptions.SyntaxError is SyntaxError Modified: pypy/branch/src-pytest/pypy/appspace/test/test_file.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_file.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_file.py Tue Jan 11 13:59:13 2005 @@ -1,29 +1,24 @@ import os import autopath from pypy.appspace import _file +from py.test import raises import unittest -class FileTestCase(unittest.TestCase): - def setUp(self): +class TestFile: + def setup_method(self, method): filename = os.path.join(autopath.this_dir, 'test_file.py') self.fd = _file.file_(filename, 'r') - def tearDown(self): + def teardown_method(self, method): self.fd.close() def test_case_1(self): - self.assertEquals(self.fd.tell(), 0) + assert self.fd.tell() == 0 def test_case_readonly(self): f=_file.file_('/tmp/tt', 'w') - self.assertEquals(f.name, '/tmp/tt') - self.assertEquals(f.mode, 'w') - self.assertEquals(f.closed, False) - self.assertEquals(f.encoding, None) # Fix when we find out what this is - self.assertRaises(TypeError, setattr, f, 'name', 42) - -def test_main(): - unittest.main() - -if __name__ == "__main__": - test_main() + assert f.name == '/tmp/tt' + assert f.mode == 'w' + assert f.closed == False + assert f.encoding == None # Fix when we find out what this is + raises(TypeError, setattr, f, 'name', 42) Modified: pypy/branch/src-pytest/pypy/appspace/test/test_sha.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_sha.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_sha.py Tue Jan 11 13:59:13 2005 @@ -6,12 +6,11 @@ import autopath from pypy.appspace import sha -import unittest -class SHATestCase(unittest.TestCase): +class TestSHA: def check(self, data, digest): computed = sha.new(data).hexdigest() - self.assert_(computed == digest) + assert computed == digest def test_case_1(self): self.check("abc", @@ -24,10 +23,3 @@ def disabled_too_slow_test_case_3(self): self.check("a" * 1000000, "34aa973cd4c4daa4f61eeb2bdbad27316534016f") - -def test_main(): - unittest.main() - - -if __name__ == "__main__": - test_main() Modified: pypy/branch/src-pytest/pypy/appspace/test/test_sio.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_sio.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_sio.py Tue Jan 11 13:59:13 2005 @@ -3,9 +3,8 @@ import os import time import tempfile -import unittest -import sio +from pypy.appspace import sio class TestSource(object): @@ -146,7 +145,7 @@ self.pos += n return result -class BufferingInputStreamTests(unittest.TestCase): +class TestBufferingInputStreamTests: packets = ["a", "b", "\n", "def", "\nxy\npq\nuv", "wx"] lines = ["ab\n", "def\n", "xy\n", "pq\n", "uvwx"] @@ -161,43 +160,43 @@ def test_readline(self): file = self.makeStream() - self.assertEqual(list(iter(file.readline, "")), self.lines) + assert list(iter(file.readline, "")) == self.lines def test_readlines(self): # This also tests next() and __iter__() file = self.makeStream() - self.assertEqual(file.readlines(), self.lines) + assert file.readlines() == self.lines def test_readlines_small_bufsize(self): file = self.makeStream(bufsize=1) - self.assertEqual(list(file), self.lines) + assert list(file) == self.lines def test_readall(self): file = self.makeStream() - self.assertEqual(file.readall(), "".join(self.lines)) + assert file.readall() == "".join(self.lines) def test_readall_small_bufsize(self): file = self.makeStream(bufsize=1) - self.assertEqual(file.readall(), "".join(self.lines)) + assert file.readall() == "".join(self.lines) def test_readall_after_readline(self): file = self.makeStream() - self.assertEqual(file.readline(), self.lines[0]) - self.assertEqual(file.readline(), self.lines[1]) - self.assertEqual(file.readall(), "".join(self.lines[2:])) + assert file.readline() == self.lines[0] + assert file.readline() == self.lines[1] + assert file.readall() == "".join(self.lines[2:]) def test_read_1_after_readline(self): file = self.makeStream() - self.assertEqual(file.readline(), "ab\n") - self.assertEqual(file.readline(), "def\n") + assert file.readline() == "ab\n" + assert file.readline() == "def\n" blocks = [] while 1: block = file.read(1) if not block: break blocks.append(block) - self.assertEqual(file.read(0), "") - self.assertEqual(blocks, list("".join(self.lines)[7:])) + assert file.read(0) == "" + assert blocks == list("".join(self.lines)[7:]) def test_read_1(self): file = self.makeStream() @@ -207,8 +206,8 @@ if not block: break blocks.append(block) - self.assertEqual(file.read(0), "") - self.assertEqual(blocks, list("".join(self.lines))) + assert file.read(0) == "" + assert blocks == list("".join(self.lines)) def test_read_2(self): file = self.makeStream() @@ -218,9 +217,9 @@ if not block: break blocks.append(block) - self.assertEqual(file.read(0), "") - self.assertEqual(blocks, ["ab", "\nd", "ef", "\nx", "y\n", "pq", - "\nu", "vw", "x"]) + assert file.read(0) == "" + assert blocks == ["ab", "\nd", "ef", "\nx", "y\n", "pq", + "\nu", "vw", "x"] def test_read_4(self): file = self.makeStream() @@ -230,21 +229,21 @@ if not block: break blocks.append(block) - self.assertEqual(file.read(0), "") - self.assertEqual(blocks, ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"]) + assert file.read(0) == "" + assert blocks == ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"] def test_read_4_after_readline(self): file = self.makeStream() - self.assertEqual(file.readline(), "ab\n") - self.assertEqual(file.readline(), "def\n") + assert file.readline() == "ab\n" + assert file.readline() == "def\n" blocks = [file.read(4)] while 1: block = file.read(4) if not block: break blocks.append(block) - self.assertEqual(file.read(0), "") - self.assertEqual(blocks, ["xy\np", "q\nuv", "wx"]) + assert file.read(0) == "" + assert blocks == ["xy\np", "q\nuv", "wx"] def test_read_4_small_bufsize(self): file = self.makeStream(bufsize=1) @@ -254,13 +253,13 @@ if not block: break blocks.append(block) - self.assertEqual(blocks, ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"]) + assert blocks == ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"] def test_tell_1(self): file = self.makeStream(tell=True) pos = 0 while 1: - self.assertEqual(file.tell(), pos) + assert file.tell() == pos n = len(file.read(1)) if not n: break @@ -270,11 +269,11 @@ file = self.makeStream(tell=True) pos = 0 pos += len(file.readline()) - self.assertEqual(file.tell(), pos) + assert file.tell() == pos pos += len(file.readline()) - self.assertEqual(file.tell(), pos) + assert file.tell() == pos while 1: - self.assertEqual(file.tell(), pos) + assert file.tell() == pos n = len(file.read(1)) if not n: break @@ -284,7 +283,7 @@ file = self.makeStream(tell=True) pos = 0 while 1: - self.assertEqual(file.tell(), pos) + assert file.tell() == pos n = len(file.read(2)) if not n: break @@ -294,7 +293,7 @@ file = self.makeStream(tell=True) pos = 0 while 1: - self.assertEqual(file.tell(), pos) + assert file.tell() == pos n = len(file.read(4)) if not n: break @@ -304,7 +303,7 @@ file = self.makeStream(tell=True) pos = 0 while 1: - self.assertEqual(file.tell(), pos) + assert file.tell() == pos n = len(file.readline()) if not n: break @@ -318,9 +317,9 @@ for seekto in range(0, end+1): for whence in 0, 1, 2: file.seek(0) - self.assertEqual(file.tell(), 0) + assert file.tell() == 0 head = file.read(readto) - self.assertEqual(head, all[:readto]) + assert head == all[:readto] if whence == 1: offset = seekto - readto elif whence == 2: @@ -329,9 +328,9 @@ offset = seekto file.seek(offset, whence) here = file.tell() - self.assertEqual(here, seekto) + assert here == seekto rest = file.readall() - self.assertEqual(rest, all[seekto:]) + assert rest == all[seekto:] def test_seek_noseek(self): file = self.makeStream() @@ -342,32 +341,32 @@ for whence in 1, 2: file = self.makeStream() head = file.read(readto) - self.assertEqual(head, all[:readto]) + assert head == all[:readto] if whence == 1: offset = seekto - readto elif whence == 2: offset = seekto - end file.seek(offset, whence) rest = file.readall() - self.assertEqual(rest, all[seekto:]) + assert rest == all[seekto:] -class BufferingOutputStreamTests(unittest.TestCase): +class TestBufferingOutputStream: def test_write(self): base = TestWriter() filter = sio.BufferingOutputStream(base, 4) filter.write("123") - self.assertEqual(base.buf, "") - self.assertEquals(filter.tell(), 3) + assert base.buf == "" + assert filter.tell() == 3 filter.write("456") - self.assertEqual(base.buf, "1234") + assert base.buf == "1234" filter.write("789ABCDEF") - self.assertEqual(base.buf, "123456789ABC") + assert base.buf == "123456789ABC" filter.write("0123") - self.assertEqual(base.buf, "123456789ABCDEF0") - self.assertEquals(filter.tell(), 19) + assert base.buf == "123456789ABCDEF0" + assert filter.tell() == 19 filter.close() - self.assertEqual(base.buf, "123456789ABCDEF0123") + assert base.buf == "123456789ABCDEF0123" def test_write_seek(self): base = TestWriter() @@ -376,7 +375,7 @@ filter.seek(3) filter.write("y"*2) filter.close() - self.assertEqual(base.buf, "x"*3 + "y"*2 + "x"*1) + assert base.buf == "x"*3 + "y"*2 + "x"*1 def test_write_seek_beyond_end(self): "Linux behaviour. May be different on other platforms." @@ -385,7 +384,7 @@ filter.seek(3) filter.write("y"*2) filter.close() - self.assertEqual(base.buf, "\0"*3 + "y"*2) + assert base.buf == "\0"*3 + "y"*2 def test_truncate(self): "Linux behaviour. May be different on other platforms." @@ -395,7 +394,7 @@ filter.truncate(4) filter.write('y') filter.close() - self.assertEqual(base.buf, 'xy' + '\0' * 2) + assert base.buf == 'xy' + '\0' * 2 def test_truncate2(self): "Linux behaviour. May be different on other platforms." @@ -405,26 +404,26 @@ filter.truncate(4) filter.write('y') filter.close() - self.assertEqual(base.buf, '1234' + '\0' * 4 + 'y') + assert base.buf == '1234' + '\0' * 4 + 'y' -class LineBufferingOutputStreamTests(unittest.TestCase): +class TestLineBufferingOutputStreamTests: def test_write(self): base = TestWriter() filter = sio.LineBufferingOutputStream(base) filter.bufsize = 4 # More handy for testing than the default filter.write("123") - self.assertEqual(base.buf, "") - self.assertEquals(filter.tell(), 3) + assert base.buf == "" + assert filter.tell() == 3 filter.write("456") - self.assertEqual(base.buf, "1234") + assert base.buf == "1234" filter.write("789ABCDEF\n") - self.assertEqual(base.buf, "123456789ABCDEF\n") + assert base.buf == "123456789ABCDEF\n" filter.write("0123") - self.assertEqual(base.buf, "123456789ABCDEF\n0123") - self.assertEquals(filter.tell(), 20) + assert base.buf == "123456789ABCDEF\n0123" + assert filter.tell() == 20 filter.close() - self.assertEqual(base.buf, "123456789ABCDEF\n0123") + assert base.buf == "123456789ABCDEF\n0123" def xtest_write_seek(self): base = TestWriter() @@ -433,25 +432,25 @@ filter.seek(3) filter.write("y"*2) filter.close() - self.assertEqual(base.buf, "x"*3 + "y"*2 + "x"*1) + assert base.buf == "x"*3 + "y"*2 + "x"*1 -class BufferingInputOutputStreamTests(unittest.TestCase): +class TestBufferingInputOutputStreamTests: def test_write(self): base = TestReaderWriter() filter = sio.BufferingInputOutputStream(base, 4) filter.write("123456789") - self.assertEqual(base.buf, "12345678") + assert base.buf == "12345678" s = filter.read() - self.assertEqual(base.buf, "123456789") + assert base.buf == "123456789" filter.write("01234") - self.assertEqual(base.buf, "1234567890123") + assert base.buf == "1234567890123" filter.seek(4,0) - self.assertEqual(base.buf, "12345678901234") - self.assertEqual(filter.read(3), "567") + assert base.buf == "12345678901234" + assert filter.read(3) == "567" filter.write('x') filter.flush() - self.assertEqual(base.buf, "1234567x901234") + assert base.buf == "1234567x901234" def test_write_seek_beyond_end(self): "Linux behaviour. May be different on other platforms." @@ -460,9 +459,9 @@ filter.seek(3) filter.write("y"*2) filter.close() - self.assertEqual(base.buf, "\0"*3 + "y"*2) + assert base.buf == "\0"*3 + "y"*2 -class CRLFFilterTests(unittest.TestCase): +class TestCRLFFilter: def test_filter(self): packets = ["abc\ndef\rghi\r\nxyz\r", "123\r", "\n456"] @@ -474,9 +473,9 @@ if not block: break blocks.append(block) - self.assertEqual(blocks, expected) + assert blocks == expected -class MMapFileTests(BufferingInputStreamTests): +class TestMMapFile: tfn = None @@ -503,15 +502,15 @@ file.write("BooHoo\n") file.write("Barf\n") file.writelines(["a\n", "b\n", "c\n"]) - self.assertEqual(file.tell(), len("BooHoo\nBarf\na\nb\nc\n")) + assert file.tell() == len("BooHoo\nBarf\na\nb\nc\n") file.seek(0) - self.assertEqual(file.read(), "BooHoo\nBarf\na\nb\nc\n") + assert file.read() == "BooHoo\nBarf\na\nb\nc\n" file.seek(0) - self.assertEqual(file.readlines(), + assert file.readlines() == ( ["BooHoo\n", "Barf\n", "a\n", "b\n", "c\n"]) - self.assertEqual(file.tell(), len("BooHoo\nBarf\na\nb\nc\n")) + assert file.tell() == len("BooHoo\nBarf\na\nb\nc\n") -class TextInputFilterTests(unittest.TestCase): +class TestTextInputFilter: packets = [ "foo\r", @@ -561,15 +560,15 @@ base = TestReader(self.packets) filter = sio.TextInputFilter(base) for data, pos in self.expected: - self.assertEqual(filter.read(100), data) + assert filter.read(100) == data def test_read_tell(self): base = TestReader(self.packets) filter = sio.TextInputFilter(base) for data, pos in self.expected_with_tell: - self.assertEqual(filter.read(100), data) - self.assertEqual(filter.tell(), pos) - self.assertEqual(filter.tell(), pos) # Repeat the tell() ! + assert filter.read(100) == data + assert filter.tell() == pos + assert filter.tell() == pos # Repeat the tell() ! def test_seek(self): base = TestReader(self.packets) @@ -581,22 +580,22 @@ c = filter.read(1) if not c: break - self.assertEqual(len(c), 1) + assert len(c) == 1 sofar += c all = sofar for i in range(len(pairs)): sofar, pos = pairs[i] filter.seek(pos) - self.assertEqual(filter.tell(), pos) - self.assertEqual(filter.tell(), pos) + assert filter.tell() == pos + assert filter.tell() == pos bufs = [sofar] while True: data = filter.read(100) if not data: - self.assertEqual(filter.read(100), "") + assert filter.read(100) == "" break bufs.append(data) - self.assertEqual("".join(bufs), all) + assert "".join(bufs) == all def test_newlines_attribute(self): @@ -605,9 +604,9 @@ filter = sio.TextInputFilter(base) for e in expected: filter.read(100) - self.assertEquals(filter.newlines, e) + assert filter.newlines == e -class TextOutputFilterTests(unittest.TestCase): +class TestTextOutputFilter: def test_write_nl(self): base = TestWriter() @@ -615,7 +614,7 @@ filter.write("abc") filter.write("def\npqr\nuvw") filter.write("\n123\n") - self.assertEqual(base.buf, "abcdef\npqr\nuvw\n123\n") + assert base.buf == "abcdef\npqr\nuvw\n123\n" def test_write_cr(self): base = TestWriter() @@ -623,7 +622,7 @@ filter.write("abc") filter.write("def\npqr\nuvw") filter.write("\n123\n") - self.assertEqual(base.buf, "abcdef\rpqr\ruvw\r123\r") + assert base.buf == "abcdef\rpqr\ruvw\r123\r" def test_write_crnl(self): base = TestWriter() @@ -631,31 +630,31 @@ filter.write("abc") filter.write("def\npqr\nuvw") filter.write("\n123\n") - self.assertEqual(base.buf, "abcdef\r\npqr\r\nuvw\r\n123\r\n") + assert base.buf == "abcdef\r\npqr\r\nuvw\r\n123\r\n" def test_write_tell_nl(self): base = TestWriter() filter = sio.TextOutputFilter(base, linesep="\n") filter.write("xxx") - self.assertEqual(filter.tell(), 3) + assert filter.tell() == 3 filter.write("\nabc\n") - self.assertEqual(filter.tell(), 8) + assert filter.tell() == 8 def test_write_tell_cr(self): base = TestWriter() filter = sio.TextOutputFilter(base, linesep="\r") filter.write("xxx") - self.assertEqual(filter.tell(), 3) + assert filter.tell() == 3 filter.write("\nabc\n") - self.assertEqual(filter.tell(), 8) + assert filter.tell() == 8 def test_write_tell_crnl(self): base = TestWriter() filter = sio.TextOutputFilter(base, linesep="\r\n") filter.write("xxx") - self.assertEqual(filter.tell(), 3) + assert filter.tell() == 3 filter.write("\nabc\n") - self.assertEqual(filter.tell(), 10) + assert filter.tell() == 10 def test_write_seek(self): base = TestWriter() @@ -663,9 +662,9 @@ filter.write("x"*100) filter.seek(50) filter.write("y"*10) - self.assertEqual(base.buf, "x"*50 + "y"*10 + "x"*40) + assert base.buf == "x"*50 + "y"*10 + "x"*40 -class DecodingInputFilterTests(unittest.TestCase): +class TestDecodingInputFilter: def test_read(self): chars = u"abc\xff\u1234\u4321\x80xyz" @@ -676,13 +675,13 @@ for n in range(1, 11): while 1: c = filter.read(n) - self.assertEqual(type(c), unicode) + assert type(c) == unicode if not c: break bufs.append(c) - self.assertEqual(u"".join(bufs), chars) + assert u"".join(bufs) == chars -class EncodingOutputFilterTests(unittest.TestCase): +class TestEncodingOutputFilterTests: def test_write(self): chars = u"abc\xff\u1234\u4321\x80xyz" @@ -697,7 +696,7 @@ break pos += len(c) filter.write(c) - self.assertEqual(base.buf, data) + assert base.buf == data # Speed test @@ -732,20 +731,3 @@ for i in range(10): print repr(f.readline()) -def makeSuite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(BufferingInputStreamTests)) - suite.addTest(unittest.makeSuite(BufferingOutputStreamTests)) - suite.addTest(unittest.makeSuite(LineBufferingOutputStreamTests)) - suite.addTest(unittest.makeSuite(BufferingInputOutputStreamTests)) - suite.addTest(unittest.makeSuite(CRLFFilterTests)) - suite.addTest(unittest.makeSuite(MMapFileTests)) - suite.addTest(unittest.makeSuite(TextInputFilterTests)) - suite.addTest(unittest.makeSuite(TextOutputFilterTests)) - suite.addTest(unittest.makeSuite(DecodingInputFilterTests)) - suite.addTest(unittest.makeSuite(EncodingOutputFilterTests)) - - return suite - -if __name__ == "__main__": - unittest.TextTestRunner().run(makeSuite()) From hpk at codespeak.net Tue Jan 11 14:01:48 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 14:01:48 +0100 (MET) Subject: [pypy-svn] r8204 - in pypy/branch/src-pytest/pypy/appspace: . test Message-ID: <20050111130148.1563C27BBE@code1.codespeak.net> Author: hpk Date: Tue Jan 11 14:01:47 2005 New Revision: 8204 Added: pypy/branch/src-pytest/pypy/appspace/test/builtin_functions_test.py - copied unchanged from r8203, pypy/branch/src-pytest/pypy/appspace/builtin_functions_test.py Removed: pypy/branch/src-pytest/pypy/appspace/builtin_functions_test.py pypy/branch/src-pytest/pypy/appspace/cpy_test_types.py Log: finalized the move of tests (removed obsolete copy of cpy_test_types.py) Deleted: /pypy/branch/src-pytest/pypy/appspace/builtin_functions_test.py ============================================================================== --- /pypy/branch/src-pytest/pypy/appspace/builtin_functions_test.py Tue Jan 11 14:01:47 2005 +++ (empty file) @@ -1,1243 +0,0 @@ -# Python test set -- built-in functions -import autopath -from pypy.tool import testit -from pypy.interpreter.gateway import app2interp - -def app_init_globals(): - ''' support functionality for these tests ''' - import __builtin__ as b - - from sets import Set - from support_tests import fcmp, have_unicode, TESTFN, unlink - - if not have_unicode: - b.basestring = str - - import sys, cStringIO - - class Squares: - - def __init__(self, max): - self.max = max - self.sofar = [] - - def __len__(self): return len(self.sofar) - - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n += 1 - return self.sofar[i] - - class StrSquares: - - def __init__(self, max): - self.max = max - self.sofar = [] - - def __len__(self): - return len(self.sofar) - - def __getitem__(self, i): - if not 0 <= i < self.max: - raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(str(n*n)) - n += 1 - return self.sofar[i] - - class BitBucket: - def write(self, line): - pass - - L = [ - ('0', 0), - ('1', 1), - ('9', 9), - ('10', 10), - ('99', 99), - ('100', 100), - ('314', 314), - (' 314', 314), - ('314 ', 314), - (' \t\t 314 \t\t ', 314), - (`sys.maxint`, sys.maxint), - (' 1x', ValueError), - (' 1 ', 1), - (' 1\02 ', ValueError), - ('', ValueError), - (' ', ValueError), - (' \t\t ', ValueError) - ] - if have_unicode: - L += [ - (unicode('0'), 0), - (unicode('1'), 1), - (unicode('9'), 9), - (unicode('10'), 10), - (unicode('99'), 99), - (unicode('100'), 100), - (unicode('314'), 314), - (unicode(' 314'), 314), - (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), - (unicode(' \t\t 314 \t\t '), 314), - (unicode(' 1x'), ValueError), - (unicode(' 1 '), 1), - (unicode(' 1\02 '), ValueError), - (unicode(''), ValueError), - (unicode(' '), ValueError), - (unicode(' \t\t '), ValueError), - (unichr(0x200), ValueError), - ] - b.Set = Set - b.fcmp = fcmp - b.have_unicode = have_unicode - b.TESTFN = TESTFN - b.unlink = unlink - b.sys = sys - b.cStringIO = cStringIO - b.Squares = Squares - b.StrSquares = StrSquares - b.BitBucket = BitBucket - b.L = L - - -class BuiltinTest(testit.AppTestCase): - - full_test = 1 - fully_initialized = False - - def setUp(self): - self.space = space = testit.objspace('std') - if self.fully_initialized: - return - - app2interp(app_init_globals).get_function(space)() - self.__class__.fully_initialized = True - - # we use "if 1:" to keep all method definitions indented, making - # it maximally easy to edit this file to pick and choose which - # ones to run (running everything takes 4 minutes or so...) - if 1: - def test_import(self): - __import__('sys') - __import__('time') - __import__('string') - self.assertRaises(ImportError, __import__, 'spamspam') - self.assertRaises(TypeError, __import__, 1, 2, 3, 4) - - def test_abs(self): - # int - self.assertEqual(abs(0), 0) - self.assertEqual(abs(1234), 1234) - self.assertEqual(abs(-1234), 1234) - # float - self.assertEqual(abs(0.0), 0.0) - self.assertEqual(abs(3.14), 3.14) - self.assertEqual(abs(-3.14), 3.14) - # long - self.assertEqual(abs(0L), 0L) - self.assertEqual(abs(1234L), 1234L) - self.assertEqual(abs(-1234L), 1234L) - # str - self.assertRaises(TypeError, abs, 'a') - - def test_apply(self): - def f0(*args): - self.assertEqual(args, ()) - def f1(a1): - self.assertEqual(a1, 1) - def f2(a1, a2): - self.assertEqual(a1, 1) - self.assertEqual(a2, 2) - def f3(a1, a2, a3): - self.assertEqual(a1, 1) - self.assertEqual(a2, 2) - self.assertEqual(a3, 3) - apply(f0, ()) - apply(f1, (1,)) - apply(f2, (1, 2)) - apply(f3, (1, 2, 3)) - - # A PyCFunction that takes only positional parameters should allow - # an empty keyword dictionary to pass without a complaint, but - # raise a TypeError if the dictionary is non-empty. - apply(id, (1,), {}) - self.assertRaises(TypeError, apply, id, (1,), {"foo": 1}) - self.assertRaises(TypeError, apply) - self.assertRaises(TypeError, apply, id, 42) - self.assertRaises(TypeError, apply, id, (42,), 42) - - def test_callable(self): - self.assert_(callable(len)) - def f(): pass - self.assert_(callable(f)) - class C: - def meth(self): pass - self.assert_(callable(C)) - x = C() - self.assert_(callable(x.meth)) - self.assert_(not callable(x)) - class D(C): - def __call__(self): pass - y = D() - self.assert_(callable(y)) - y() - - def test_chr(self): - self.assertEqual(chr(32), ' ') - self.assertEqual(chr(65), 'A') - self.assertEqual(chr(97), 'a') - self.assertEqual(chr(0xff), '\xff') - self.assertRaises(ValueError, chr, 256) - self.assertRaises(TypeError, chr) - - def test_cmp(self): - self.assertEqual(cmp(-1, 1), -1) - self.assertEqual(cmp(1, -1), 1) - self.assertEqual(cmp(1, 1), 0) - ''' TODO XXX Circular objects not handled yet - # verify that circular objects are handled - a = []; a.append(a) - b = []; b.append(b) - from UserList import UserList - c = UserList(); c.append(c) - self.assertEqual(cmp(a, b), 0) - self.assertEqual(cmp(b, c), 0) - self.assertEqual(cmp(c, a), 0) - self.assertEqual(cmp(a, c), 0) - # okay, now break the cycles - a.pop(); b.pop(); c.pop() - ''' - self.assertRaises(TypeError, cmp) - - ''' TODO: XXX Coerce is not implemented - def test_coerce(self): - self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) - self.assertEqual(coerce(1, 1L), (1L, 1L)) - self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) - self.assertRaises(TypeError, coerce) - class BadNumber: - def __coerce__(self, other): - raise ValueError - self.assertRaises(ValueError, coerce, 42, BadNumber()) - self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000)) - ''' - - def test_compile(self): - compile('print 1\n', '', 'exec') - bom = '\xef\xbb\xbf' - compile(bom + 'print 1\n', '', 'exec') - self.assertRaises(TypeError, compile) - self.assertRaises(ValueError, compile, - 'print 42\n', '', 'badmode') - self.assertRaises(ValueError, compile, - 'print 42\n', '', 'single', 0xff) - if have_unicode: - compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') - - def test_delattr(self): - import sys - sys.spam = 1 - delattr(sys, 'spam') - self.assertRaises(TypeError, delattr) - - def test_dir(self): - x = 1 - self.assert_('x' in dir()) - import sys - self.assert_('modules' in dir(sys)) - self.assertRaises(TypeError, dir, 42, 42) - - def test_divmod(self): - self.assertEqual(divmod(12, 7), (1, 5)) - self.assertEqual(divmod(-12, 7), (-2, 2)) - self.assertEqual(divmod(12, -7), (-2, -2)) - self.assertEqual(divmod(-12, -7), (1, -5)) - - self.assertEqual(divmod(12L, 7L), (1L, 5L)) - self.assertEqual(divmod(-12L, 7L), (-2L, 2L)) - self.assertEqual(divmod(12L, -7L), (-2L, -2L)) - self.assertEqual(divmod(-12L, -7L), (1L, -5L)) - - self.assertEqual(divmod(12, 7L), (1, 5L)) - self.assertEqual(divmod(-12, 7L), (-2, 2L)) - self.assertEqual(divmod(12L, -7), (-2L, -2)) - self.assertEqual(divmod(-12L, -7), (1L, -5)) - - self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) - self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) - self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) - self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) - - self.assertRaises(TypeError, divmod) - - ''' XXX TODO No eval() support yet - def test_eval(self): - self.assertEqual(eval('1+1'), 2) - self.assertEqual(eval(' 1+1\n'), 2) - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - self.assertEqual(eval('a', globals) , 1) - self.assertEqual(eval('a', globals, locals), 1) - self.assertEqual(eval('b', globals, locals), 200) - self.assertEqual(eval('c', globals, locals), 300) - if have_unicode: - self.assertEqual(eval(unicode('1+1')), 2) - self.assertEqual(eval(unicode(' 1+1\n')), 2) - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - if have_unicode: - self.assertEqual(eval(unicode('a'), globals), 1) - self.assertEqual(eval(unicode('a'), globals, locals), 1) - self.assertEqual(eval(unicode('b'), globals, locals), 200) - self.assertEqual(eval(unicode('c'), globals, locals), 300) - bom = '\xef\xbb\xbf' - self.assertEqual(eval(bom + 'a', globals, locals), 1) - self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals), - unicode('\xc3\xa5', 'utf8')) - self.assertRaises(TypeError, eval) - self.assertRaises(TypeError, eval, ()) - - '\'' XXX TODO: Figure out later - # Done outside of the method test_z to get the correct scope - z = 0 - f = open(TESTFN, 'w') - f.write('z = z+1\n') - f.write('z = z*2\n') - f.close() - execfile(TESTFN) - - def test_execfile(self): - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - - self.assertEqual(self.__class__.z, 2) - globals['z'] = 0 - execfile(TESTFN, globals) - self.assertEqual(globals['z'], 2) - locals['z'] = 0 - execfile(TESTFN, globals, locals) - self.assertEqual(locals['z'], 2) - unlink(TESTFN) - self.assertRaises(TypeError, execfile) - import os - self.assertRaises(IOError, execfile, os.curdir) - self.assertRaises(IOError, execfile, "I_dont_exist") - '\'' - ''' - - ''' XXX TODO: filter does NOT rely on __getitem__, but rather on - __iter__; it appears to me that the following two tests, - therefore, pass in CPython only because of the accident that - in that implementation str does not define __iter__ (while - list and tuple do, in 2.3). Probably best to substitute - most of these tests with more appropriate ones! - ''' - def test_filter(self): - self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), - 'elloorld') - self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]) - , [1, 'hello', [3], 9]) - self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), - [1, 9, 2]) - self.assertEqual(filter(None, Squares(10)), - [1, 4, 9, 16, 25, 36, 49, 64, 81]) - self.assertEqual(filter(lambda x: x%2, Squares(10)), - [1, 9, 25, 49, 81]) - def identity(item): - return 1 - filter(identity, Squares(5)) - self.assertRaises(TypeError, filter) - ''' XXX rest of test disabled as above explained - class BadSeq(object): - def __getitem__(self, index): - if index<4: - return 42 - raise ValueError - self.assertRaises(ValueError, filter, lambda x: x, BadSeq()) - def badfunc(): - pass - self.assertRaises(TypeError, filter, badfunc, range(5)) - - # test bltinmodule.c::filtertuple() - self.assertEqual(filter(None, (1, 2)), (1, 2)) - self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4)) - self.assertRaises(TypeError, filter, 42, (1, 2)) - - # test bltinmodule.c::filterstring() - self.assertEqual(filter(None, "12"), "12") - self.assertEqual(filter(lambda x: x>="3", "1234"), "34") - self.assertRaises(TypeError, filter, 42, "12") - class badstr(str): - def __getitem__(self, index): - raise ValueError - self.assertRaises(ValueError, filter, - lambda x: x >="3", badstr("1234")) - - class badstr2(str): - def __getitem__(self, index): - return 42 - self.assertRaises(TypeError, filter, - lambda x: x >=42, badstr2("1234")) - - class weirdstr(str): - def __getitem__(self, index): - return weirdstr(2*str.__getitem__(self, index)) - self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), - "3344") - - class shiftstr(str): - def __getitem__(self, index): - return chr(ord(str.__getitem__(self, index))+1) - self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345") - - if have_unicode: - # test bltinmodule.c::filterunicode() - self.assertEqual(filter(None, unicode("12")), unicode("12")) - self.assertEqual(filter(lambda x: x>="3", unicode("1234")), - unicode("34")) - self.assertRaises(TypeError, filter, 42, unicode("12")) - self.assertRaises(ValueError, filter, lambda x: x >="3", - badstr(unicode("1234"))) - - class badunicode(unicode): - def __getitem__(self, index): - return 42 - self.assertRaises(TypeError, filter, lambda x: x >=42, - badunicode("1234")) - - class weirdunicode(unicode): - def __getitem__(self, index): - return weirdunicode(2*unicode.__getitem__(self, index)) - self.assertEqual( - filter(lambda x: x>=unicode("33"), weirdunicode("1234")), - unicode("3344")) - - class shiftunicode(unicode): - def __getitem__(self, index): - return unichr(ord(unicode.__getitem__(self, index))+1) - self.assertEqual( - filter(lambda x: x>=unicode("3"), shiftunicode("1234")), - unicode("345") - ) - - def test_filter_subclasses(self): - # test that filter() never returns tuple, str or unicode subclasses - # and that the result always goes through __getitem__ - funcs = (None, bool, lambda x: True) - class tuple2(tuple): - def __getitem__(self, index): - return 2*tuple.__getitem__(self, index) - class str2(str): - def __getitem__(self, index): - return 2*str.__getitem__(self, index) - inputs = { - tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, - str2: {"": "", "123": "112233"} - } - if have_unicode: - class unicode2(unicode): - def __getitem__(self, index): - return 2*unicode.__getitem__(self, index) - inputs[unicode2] = { - unicode(): unicode(), - unicode("123"): unicode("112233") - } - - for (cls, inps) in inputs.iteritems(): - for (inp, exp) in inps.iteritems(): - # make sure the output goes through __getitem__ - # even if func is None - self.assertEqual( - filter(funcs[0], cls(inp)), - filter(funcs[1], cls(inp)) - ) - for func in funcs: - outp = filter(func, cls(inp)) - self.assertEqual(outp, exp) - self.assert_(not isinstance(outp, cls)) - ''' - - def test_float(self): - self.assertEqual(float(3.14), 3.14) - self.assertEqual(float(314), 314.0) - self.assertEqual(float(314L), 314.0) - self.assertEqual(float(" 3.14 "), 3.14) - if have_unicode: - self.assertEqual(float(unicode(" 3.14 ")), 3.14) - self.assertEqual(float(unicode( - " \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14) - - def test_getattr(self): - import sys - self.assert_(getattr(sys, 'stdout') is sys.stdout) - self.assertRaises(TypeError, getattr, sys, 1) - self.assertRaises(TypeError, getattr, sys, 1, "foo") - self.assertRaises(TypeError, getattr) - if have_unicode: - self.assertRaises(UnicodeError, getattr, sys, - unichr(sys.maxunicode)) - - def test_hasattr(self): - import sys - self.assert_(hasattr(sys, 'stdout')) - self.assertRaises(TypeError, hasattr, sys, 1) - self.assertRaises(TypeError, hasattr) - if have_unicode: - self.assertRaises(UnicodeError, hasattr, sys, - unichr(sys.maxunicode)) - - def test_hash(self): - hash(None) - self.assertEqual(hash(1), hash(1L)) - self.assertEqual(hash(1), hash(1.0)) - hash('spam') - if have_unicode: - self.assertEqual(hash('spam'), hash(unicode('spam'))) - hash((0,1,2,3)) - def f(): pass - self.assertRaises(TypeError, hash, []) - self.assertRaises(TypeError, hash, {}) - - def test_hex(self): - self.assertEqual(hex(16), '0x10') - self.assertEqual(hex(16L), '0x10L') - self.assertEqual(len(hex(-1)), len(hex(sys.maxint))) - self.assert_(hex(-16) in ('0xfffffff0', '0xfffffffffffffff0')) - self.assertEqual(hex(-16L), '-0x10L') - self.assertRaises(TypeError, hex, {}) - - def test_id(self): - id(None) - id(1) - id(1L) - id(1.0) - id('spam') - id((0,1,2,3)) - id([0,1,2,3]) - id({'spam': 1, 'eggs': 2, 'ham': 3}) - - # Test input() later, together with raw_input - - def test_int(self): - self.assertEqual(int(314), 314) - self.assertEqual(int(3.14), 3) - self.assertEqual(int(314L), 314) - # Check that conversion from float truncates towards zero - self.assertEqual(int(-3.14), -3) - self.assertEqual(int(3.9), 3) - self.assertEqual(int(-3.9), -3) - self.assertEqual(int(3.5), 3) - self.assertEqual(int(-3.5), -3) - # Different base: - self.assertEqual(int("10",16), 16L) - if have_unicode: - self.assertEqual(int(unicode("10"),16), 16L) - # Test conversion from strings and various anomalies - for s, v in L: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - self.assertEqual(int(ss), vv) - except v: - pass - - s = `-1-sys.maxint` - self.assertEqual(int(s)+1, -sys.maxint) - # should return long - ''' XXX TODO: Longs not well supported yet - int(s[1:]) - - # should return long - x = int(1e100) - self.assert_(isinstance(x, long)) - x = int(-1e100) - self.assert_(isinstance(x, long)) - ''' - - # SF bug 434186: 0x80000000/2 != 0x80000000>>1. - # Worked by accident in Windows release build, but failed in - # debug build. Failed in all Linux builds. - x = -1-sys.maxint - self.assertEqual(x >> 1, x//2) - - self.assertRaises(ValueError, int, '123\0') - self.assertRaises(ValueError, int, '53', 40) - - ''' XXX TODO: Longs not supported yet - x = int('1' * 600) - self.assert_(isinstance(x, long)) - - if have_unicode: - x = int(unichr(0x661) * 600) - self.assert_(isinstance(x, long)) - - self.assertRaises(TypeError, int, 1, 12) - ''' - - self.assertEqual(int('0123', 0), 83) - - def test_intern(self): - self.assertRaises(TypeError, intern) - s = "never interned before" - self.assert_(intern(s) is s) - s2 = s.swapcase().swapcase() - self.assert_(intern(s2) is s) - - def test_iter(self): - self.assertRaises(TypeError, iter) - self.assertRaises(TypeError, iter, 42, 42) - lists = [("1", "2"), ["1", "2"], "12"] - if have_unicode: - lists.append(unicode("12")) - for l in lists: - i = iter(l) - self.assertEqual(i.next(), '1') - self.assertEqual(i.next(), '2') - self.assertRaises(StopIteration, i.next) - - def test_isinstance(self): - class C: - pass - class D(C): - pass - class E: - pass - c = C() - d = D() - e = E() - self.assert_(isinstance(c, C)) - self.assert_(isinstance(d, C)) - self.assert_(not isinstance(e, C)) - self.assert_(not isinstance(c, D)) - self.assert_(not isinstance('foo', E)) - self.assertRaises(TypeError, isinstance, E, 'foo') - self.assertRaises(TypeError, isinstance) - - def test_issubclass(self): - class C: - pass - class D(C): - pass - class E: - pass - c = C() - d = D() - e = E() - self.assert_(issubclass(D, C)) - self.assert_(issubclass(C, C)) - self.assert_(not issubclass(C, D)) - self.assertRaises(TypeError, issubclass, 'foo', E) - self.assertRaises(TypeError, issubclass, E, 'foo') - self.assertRaises(TypeError, issubclass) - - def test_len(self): - self.assertEqual(len('123'), 3) - self.assertEqual(len(()), 0) - self.assertEqual(len((1, 2, 3, 4)), 4) - self.assertEqual(len([1, 2, 3, 4]), 4) - self.assertEqual(len({}), 0) - self.assertEqual(len({'a':1, 'b': 2}), 2) - class BadSeq: - def __len__(self): - raise ValueError - self.assertRaises(ValueError, len, BadSeq()) - - if 1: - - def test_list(self): - self.assertEqual(list([]), []) - l0_3 = [0, 1, 2, 3] - l0_3_bis = list(l0_3) - self.assertEqual(l0_3, l0_3_bis) - self.assert_(l0_3 is not l0_3_bis) - self.assertEqual(list(()), []) - self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) - self.assertEqual(list(''), []) - self.assertEqual(list('spam'), ['s', 'p', 'a', 'm']) - - ''' XXX TODO: disabled for now -- far too slow! - if sys.maxint == 0x7fffffff: - # This test can currently only work on 32-bit machines. - # XXX If/when PySequence_Length() returns a ssize_t, it should be - # XXX re-enabled. - # Verify clearing of bug #556025. - # This assumes that the max data size (sys.maxint) == max - # address size this also assumes that the address size is at - # least 4 bytes with 8 byte addresses, the bug is not well - # tested - # - # Note: This test is expected to SEGV under Cygwin 1.3.12 or - # earlier due to a newlib bug. See the following mailing list - # thread for the details: - - # http://sources.redhat.com/ml/newlib/2002/msg00369.html - self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) - ''' - - ''' XXX TODO: disabled for now -- long not yet well supported - def test_long(self): - self.assertEqual(long(314), 314L) - self.assertEqual(long(3.14), 3L) - self.assertEqual(long(314L), 314L) - # Check that conversion from float truncates towards zero - self.assertEqual(long(-3.14), -3L) - self.assertEqual(long(3.9), 3L) - self.assertEqual(long(-3.9), -3L) - self.assertEqual(long(3.5), 3L) - self.assertEqual(long(-3.5), -3L) - self.assertEqual(long("-3"), -3L) - if have_unicode: - self.assertEqual(long(unicode("-3")), -3L) - # Different base: - self.assertEqual(long("10",16), 16L) - if have_unicode: - self.assertEqual(long(unicode("10"),16), 16L) - # Check conversions from string (same test set as for int(), and then some) - LL = [ - ('1' + '0'*20, 10L**20), - ('1' + '0'*100, 10L**100) - ] - L2 = L[:] - if have_unicode: - L2 += [ - (unicode('1') + unicode('0')*20, 10L**20), - (unicode('1') + unicode('0')*100, 10L**100), - ] - for s, v in L2 + LL: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - self.assertEqual(long(ss), long(vv)) - except v: - pass - - self.assertRaises(ValueError, long, '123\0') - self.assertRaises(ValueError, long, '53', 40) - self.assertRaises(TypeError, long, 1, 12) - ''' - - def test_map(self): - self.assertEqual( - map(None, 'hello world'), - ['h','e','l','l','o',' ','w','o','r','l','d'] - ) - self.assertEqual( - map(None, 'abcd', 'efg'), - [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)] - ) - self.assertEqual( - map(None, range(10)), - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - ) - self.assertEqual( - map(lambda x: x*x, range(1,4)), - [1, 4, 9] - ) - try: - from math import sqrt - except ImportError: - def sqrt(x): - return pow(x, 0.5) - self.assertEqual( - map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]), - [[4.0, 2.0], [9.0, 3.0]] - ) - self.assertEqual( - map(lambda x, y: x+y, [1,3,2], [9,1,4]), - [10, 4, 6] - ) - - def plus(*v): - accu = 0 - for i in v: accu = accu + i - return accu - self.assertEqual( - map(plus, [1, 3, 7]), - [1, 3, 7] - ) - self.assertEqual( - map(plus, [1, 3, 7], [4, 9, 2]), - [1+4, 3+9, 7+2] - ) - self.assertEqual( - map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]), - [1+4+1, 3+9+1, 7+2+0] - ) - self.assertEqual( - map(None, Squares(10)), - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ) - self.assertEqual( - map(int, Squares(10)), - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ) - self.assertEqual( - map(None, Squares(3), Squares(2)), - [(0,0), (1,1), (4,None)] - ) - self.assertEqual( - map(max, Squares(3), Squares(2)), - [0, 1, 4] - ) - self.assertRaises(TypeError, map) - self.assertRaises(TypeError, map, lambda x: x, 42) - self.assertEqual(map(None, [42]), [42]) - class BadSeq: - def __getitem__(self, index): - raise ValueError - self.assertRaises(ValueError, map, lambda x: x, BadSeq()) - - def test_max(self): - self.assertEqual(max('123123'), '3') - self.assertEqual(max(1, 2, 3), 3) - self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) - self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) - - self.assertEqual(max(1, 2L, 3.0), 3.0) - self.assertEqual(max(1L, 2.0, 3), 3) - self.assertEqual(max(1.0, 2, 3L), 3L) - - def test_min(self): - self.assertEqual(min('123123'), '1') - self.assertEqual(min(1, 2, 3), 1) - self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) - self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) - - self.assertEqual(min(1, 2L, 3.0), 1) - self.assertEqual(min(1L, 2.0, 3), 1L) - self.assertEqual(min(1.0, 2, 3L), 1.0) - - self.assertRaises(TypeError, min) - self.assertRaises(TypeError, min, 42) - self.assertRaises(ValueError, min, ()) - class BadSeq: - def __getitem__(self, index): - raise ValueError - self.assertRaises(ValueError, min, BadSeq()) - ''' XXX TODO: some weird bug in pypy here -- fix later - class BadNumber: - def __cmp__(self, other): - raise ValueError - self.assertRaises(ValueError, min, (42, BadNumber())) - ''' - - def test_oct(self): - self.assertEqual(oct(100), '0144') - self.assertEqual(oct(100L), '0144L') - self.assert_(oct(-100) in ('037777777634', '01777777777777777777634')) - self.assertEqual(oct(-100L), '-0144L') - self.assertRaises(TypeError, oct, ()) - - - def test_open(self): - def write_testfile(): - # NB the first 4 lines are also used to test input and raw_input, below - fp = open(TESTFN, 'w') - try: - fp.write('1+1\n') - fp.write('1+1\n') - fp.write('The quick brown fox jumps over the lazy dog') - fp.write('.\n') - fp.write('Dear John\n') - fp.write('XXX'*100) - fp.write('YYY'*100) - finally: - fp.close() - write_testfile() - fp = open(TESTFN, 'r') - try: - self.assertEqual(fp.readline(4), '1+1\n') - self.assertEqual(fp.readline(4), '1+1\n') - self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') - self.assertEqual(fp.readline(4), 'Dear') - self.assertEqual(fp.readline(100), ' John\n') - self.assertEqual(fp.read(300), 'XXX'*100) - self.assertEqual(fp.read(1000), 'YYY'*100) - finally: - fp.close() - unlink(TESTFN) - - def test_ord(self): - self.assertEqual(ord(' '), 32) - self.assertEqual(ord('A'), 65) - self.assertEqual(ord('a'), 97) - self.assertRaises(TypeError, ord, 42) - if have_unicode: - self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode) - self.assertRaises(TypeError, ord, unicode("12")) - - def test_pow(self): - self.assertEqual(pow(0,0), 1) - self.assertEqual(pow(0,1), 0) - self.assertEqual(pow(1,0), 1) - self.assertEqual(pow(1,1), 1) - - self.assertEqual(pow(2,0), 1) - self.assertEqual(pow(2,10), 1024) - self.assertEqual(pow(2,20), 1024*1024) - self.assertEqual(pow(2,30), 1024*1024*1024) - - self.assertEqual(pow(-2,0), 1) - self.assertEqual(pow(-2,1), -2) - self.assertEqual(pow(-2,2), 4) - self.assertEqual(pow(-2,3), -8) - - self.assertEqual(pow(0L,0), 1) - self.assertEqual(pow(0L,1), 0) - self.assertEqual(pow(1L,0), 1) - self.assertEqual(pow(1L,1), 1) - - self.assertEqual(pow(2L,0), 1) - self.assertEqual(pow(2L,10), 1024) - self.assertEqual(pow(2L,20), 1024*1024) - self.assertEqual(pow(2L,30), 1024*1024*1024) - - self.assertEqual(pow(-2L,0), 1) - self.assertEqual(pow(-2L,1), -2) - self.assertEqual(pow(-2L,2), 4) - self.assertEqual(pow(-2L,3), -8) - - self.assertAlmostEqual(pow(0.,0), 1.) - self.assertAlmostEqual(pow(0.,1), 0.) - self.assertAlmostEqual(pow(1.,0), 1.) - self.assertAlmostEqual(pow(1.,1), 1.) - - self.assertAlmostEqual(pow(2.,0), 1.) - self.assertAlmostEqual(pow(2.,10), 1024.) - self.assertAlmostEqual(pow(2.,20), 1024.*1024.) - self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) - - self.assertAlmostEqual(pow(-2.,0), 1.) - self.assertAlmostEqual(pow(-2.,1), -2.) - self.assertAlmostEqual(pow(-2.,2), 4.) - self.assertAlmostEqual(pow(-2.,3), -8.) - - for x in 2, 2L, 2.0: - for y in 10, 10L, 10.0: - for z in 1000, 1000L, 1000.0: - if isinstance(x, float) or \ - isinstance(y, float) or \ - isinstance(z, float): - self.assertRaises(TypeError, pow, x, y, z) - else: - self.assertAlmostEqual(pow(x, y, z), 24.0) - - self.assertRaises(TypeError, pow, -1, -2, 3) - self.assertRaises(ValueError, pow, 1, 2, 0) - self.assertRaises(TypeError, pow, -1L, -2L, 3L) - self.assertRaises(ValueError, pow, 1L, 2L, 0L) - self.assertRaises(ValueError, pow, -342.43, 0.234) - - self.assertRaises(TypeError, pow) - - def test_range(self): - self.assertEqual(range(3), [0, 1, 2]) - self.assertEqual(range(1, 5), [1, 2, 3, 4]) - self.assertEqual(range(0), []) - self.assertEqual(range(-3), []) - self.assertEqual(range(1, 10, 3), [1, 4, 7]) - self.assertEqual(range(5, -5, -3), [5, 2, -1, -4]) - - # Now test range() with longs - self.assertEqual(range(-2**100), []) - self.assertEqual(range(0, -2**100), []) - self.assertEqual(range(0, 2**100, -1), []) - self.assertEqual(range(0, 2**100, -1), []) - - a = long(10 * sys.maxint) - b = long(100 * sys.maxint) - c = long(50 * sys.maxint) - - self.assertEqual(range(a, a+2), [a, a+1]) - self.assertEqual(range(a+2, a, -1L), [a+2, a+1]) - self.assertEqual(range(a+4, a, -2), [a+4, a+2]) - - seq = range(a, b, c) - self.assert_(a in seq) - self.assert_(b not in seq) - self.assertEqual(len(seq), 2) - - seq = range(b, a, -c) - self.assert_(b in seq) - self.assert_(a not in seq) - self.assertEqual(len(seq), 2) - - seq = range(-a, -b, -c) - self.assert_(-a in seq) - self.assert_(-b not in seq) - self.assertEqual(len(seq), 2) - - self.assertRaises(TypeError, range) - self.assertRaises(TypeError, range, 1, 2, 3, 4) - self.assertRaises(ValueError, range, 1, 2, 0) - - # Reject floats when it would require PyLongs to represent. - # (smaller floats still accepted, but deprecated) - self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) - - self.assertRaises(TypeError, range, 0, "spam") - self.assertRaises(TypeError, range, 0, 42, "spam") - - self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) - self.assertRaises(OverflowError, range, 0, 2*sys.maxint) - - ''' XXX TODO: input and raw_input not supported yet - def test_input_and_raw_input(self): - self.write_testfile() - fp = open(TESTFN, 'r') - savestdin = sys.stdin - savestdout = sys.stdout # Eats the echo - try: - sys.stdin = fp - sys.stdout = BitBucket() - self.assertEqual(input(), 2) - self.assertEqual(input('testing\n'), 2) - self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') - self.assertEqual(raw_input('testing\n'), 'Dear John') - sys.stdin = cStringIO.StringIO("NULL\0") - self.assertRaises(TypeError, input, 42, 42) - sys.stdin = cStringIO.StringIO(" 'whitespace'") - self.assertEqual(input(), 'whitespace') - sys.stdin = cStringIO.StringIO() - self.assertRaises(EOFError, input) - del sys.stdout - self.assertRaises(RuntimeError, input, 'prompt') - del sys.stdin - self.assertRaises(RuntimeError, input, 'prompt') - finally: - sys.stdin = savestdin - sys.stdout = savestdout - fp.close() - unlink(TESTFN) - ''' - - def test_reduce(self): - self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') - self.assertEqual( - reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), - ['a','c','d','w'] - ) - self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040) - self.assertEqual( - reduce(lambda x, y: x*y, range(2,21), 1L), - 2432902008176640000L - ) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0) - self.assertRaises(TypeError, reduce) - self.assertRaises(TypeError, reduce, 42, 42) - self.assertRaises(TypeError, reduce, 42, 42, 42) - self.assertEqual(reduce(42, "1"), "1") # func is never called with one item - self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item - self.assertRaises(TypeError, reduce, 42, (42, 42)) - - class BadSeq: - def __getitem__(self, index): - raise ValueError - self.assertRaises(ValueError, reduce, 42, BadSeq()) - - ''' XXX TODO: we don't have reload yet - def test_reload(self): - import sys - reload(sys) - import string - reload(string) - ## import sys - ## self.assertRaises(ImportError, reload, sys) - ''' - - def test_repr(self): - self.assertEqual(repr(''), '\'\'') - self.assertEqual(repr(0), '0') - self.assertEqual(repr(0L), '0L') - self.assertEqual(repr(()), '()') - self.assertEqual(repr([]), '[]') - self.assertEqual(repr({}), '{}') - ''' XXX TODO: we don't yet support "circular" objects! - a = [] - a.append(a) - self.assertEqual(repr(a), '[[...]]') - a = {} - a[0] = a - self.assertEqual(repr(a), '{0: {...}}') - ''' - - def test_round(self): - self.assertEqual(round(0.0), 0.0) - self.assertEqual(round(1.0), 1.0) - self.assertEqual(round(10.0), 10.0) - self.assertEqual(round(1000000000.0), 1000000000.0) - self.assertEqual(round(1e20), 1e20) - - self.assertEqual(round(-1.0), -1.0) - self.assertEqual(round(-10.0), -10.0) - self.assertEqual(round(-1000000000.0), -1000000000.0) - self.assertEqual(round(-1e20), -1e20) - - self.assertEqual(round(0.1), 0.0) - self.assertEqual(round(1.1), 1.0) - self.assertEqual(round(10.1), 10.0) - self.assertEqual(round(1000000000.1), 1000000000.0) - - self.assertEqual(round(-1.1), -1.0) - self.assertEqual(round(-10.1), -10.0) - self.assertEqual(round(-1000000000.1), -1000000000.0) - - self.assertEqual(round(0.9), 1.0) - self.assertEqual(round(9.9), 10.0) - self.assertEqual(round(999999999.9), 1000000000.0) - - self.assertEqual(round(-0.9), -1.0) - self.assertEqual(round(-9.9), -10.0) - self.assertEqual(round(-999999999.9), -1000000000.0) - - self.assertEqual(round(-8.0, -1), -10.0) - - self.assertRaises(TypeError, round) - - def test_setattr(self): - setattr(sys, 'spam', 1) - self.assertEqual(sys.spam, 1) - self.assertRaises(TypeError, setattr, sys, 1, 'spam') - self.assertRaises(TypeError, setattr) - - def test_str(self): - self.assertEqual(str(''), '') - self.assertEqual(str(0), '0') - self.assertEqual(str(0L), '0') - self.assertEqual(str(()), '()') - self.assertEqual(str([]), '[]') - self.assertEqual(str({}), '{}') - ''' XXX TODO: we don't yet support "circular" objects! - a = [] - a.append(a) - self.assertEqual(str(a), '[[...]]') - a = {} - a[0] = a - self.assertEqual(str(a), '{0: {...}}') - ''' - - def test_sum(self): - self.assertEqual(sum([]), 0) - self.assertEqual(sum(range(2,8)), 27) - self.assertEqual(sum(iter(range(2,8))), 27) - self.assertEqual(sum(Squares(10)), 285) - self.assertEqual(sum(iter(Squares(10))), 285) - self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) - - self.assertRaises(TypeError, sum) - self.assertRaises(TypeError, sum, 42) - self.assertRaises(TypeError, sum, ['a', 'b', 'c']) - self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') - self.assertRaises(TypeError, sum, [[1], [2], [3]]) - self.assertRaises(TypeError, sum, [{2:3}]) - self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) - - class BadSeq: - def __getitem__(self, index): - raise ValueError - self.assertRaises(ValueError, sum, BadSeq()) - - def test_tuple(self): - self.assertEqual(tuple(()), ()) - t0_3 = (0, 1, 2, 3) - t0_3_bis = tuple(t0_3) - ''' XXX TODO: tuples are immutable -- returns same object in CPython ''' - #self.assert_(t0_3 is t0_3_bis) - self.assert_(t0_3 == t0_3_bis) - self.assertEqual(tuple([]), ()) - self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) - self.assertEqual(tuple(''), ()) - self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) - - def test_type(self): - self.assertEqual(type(''), type('123')) - self.assertNotEqual(type(''), type(())) - - def test_unichr(self): - if have_unicode: - self.assertEqual(unichr(32), unicode(' ')) - self.assertEqual(unichr(65), unicode('A')) - self.assertEqual(unichr(97), unicode('a')) - self.assertEqual( - unichr(sys.maxunicode), - unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape') - ) - self.assertRaises(ValueError, unichr, sys.maxunicode+1) - self.assertRaises(TypeError, unichr) - - def test_vars(self): - def get_vars_f0(): - return vars() - def get_vars_f2(): - get_vars_f0() - a = 1 - b = 2 - return vars() - self.assertEqual(Set(vars()), Set(dir())) - import sys - self.assertEqual(Set(vars(sys)), Set(dir(sys))) - self.assertEqual(get_vars_f0(), {}) - self.assertEqual(get_vars_f2(), {'a': 1, 'b': 2}) - self.assertRaises(TypeError, vars, 42, 42) - self.assertRaises(TypeError, vars, 42) - - def test_zip(self): - a = (1, 2, 3) - b = (4, 5, 6) - t = [(1, 4), (2, 5), (3, 6)] - self.assertEqual(zip(a, b), t) - b = [4, 5, 6] - self.assertEqual(zip(a, b), t) - b = (4, 5, 6, 7) - self.assertEqual(zip(a, b), t) - class I: - def __getitem__(self, i): - if i < 0 or i > 2: raise IndexError - return i + 4 - self.assertEqual(zip(a, I()), t) - self.assertRaises(TypeError, zip) - self.assertRaises(TypeError, zip, None) - class G: - pass - self.assertRaises(TypeError, zip, a, G()) - - # Make sure zip doesn't try to allocate a billion elements for the - # result list when one of its arguments doesn't say how long it is. - # A MemoryError is the most likely failure mode. - class SequenceWithoutALength: - def __getitem__(self, i): - if i == 5: - raise IndexError - else: - return i - s = SequenceWithoutALength() - self.assertEqual( - zip(s, xrange(2**30)), - [(x,x) for x in s] - ) - - class BadSeq: - def __getitem__(self, i): - if i == 5: - raise ValueError - else: - return i - self.assertRaises(ValueError, zip, BadSeq(), BadSeq()) - -if __name__ == '__main__': - testit.main() Deleted: /pypy/branch/src-pytest/pypy/appspace/cpy_test_types.py ============================================================================== --- /pypy/branch/src-pytest/pypy/appspace/cpy_test_types.py Tue Jan 11 14:01:47 2005 +++ (empty file) @@ -1,787 +0,0 @@ -# Python test set -- part 6, built-in types -# Slightly edited version for PyPy. - -from support_tests import * - -print '6. Built-in types' - -print '6.1 Truth value testing' -if None: raise TestFailed, 'None is true instead of false' -if 0: raise TestFailed, '0 is true instead of false' -if 0L: raise TestFailed, '0L is true instead of false' -if 0.0: raise TestFailed, '0.0 is true instead of false' -if '': raise TestFailed, '\'\' is true instead of false' -if (): raise TestFailed, '() is true instead of false' -if []: raise TestFailed, '[] is true instead of false' -if {}: raise TestFailed, '{} is true instead of false' -if not 1: raise TestFailed, '1 is false instead of true' -if not 1L: raise TestFailed, '1L is false instead of true' -if not 1.0: raise TestFailed, '1.0 is false instead of true' -if not 'x': raise TestFailed, '\'x\' is false instead of true' -if not (1, 1): raise TestFailed, '(1, 1) is false instead of true' -if not [1]: raise TestFailed, '[1] is false instead of true' -if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true' -def f(): pass -class C: pass -import sys -x = C() -if not f: raise TestFailed, 'f is false instead of true' -if not C: raise TestFailed, 'C is false instead of true' -if not sys: raise TestFailed, 'sys is false instead of true' -if not x: raise TestFailed, 'x is false instead of true' - -print '6.2 Boolean operations' -if 0 or 0: raise TestFailed, '0 or 0 is true instead of false' -if 1 and 1: pass -else: raise TestFailed, '1 and 1 is false instead of false' -if not 1: raise TestFailed, 'not 1 is true instead of false' - -print '6.3 Comparisons' -if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass -else: raise TestFailed, 'int comparisons failed' -if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass -else: raise TestFailed, 'long int comparisons failed' -if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass -else: raise TestFailed, 'float comparisons failed' -if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass -else: raise TestFailed, 'string comparisons failed' -if 0 in [0] and 0 not in [1]: pass -else: raise TestFailed, 'membership test failed' -if None is None and [] is not []: pass -else: raise TestFailed, 'identity test failed' - - -print '6.3.1 Conversion errors' -try: float('') -except ValueError: pass -else: raise TestFailed, "float('') didn't raise ValueError" - -try: float('5\0') -except ValueError: pass -else: raise TestFailed, "float('5\0') didn't raise ValueError" - -print '6.3.2 Division errors' -try: 5.0 / 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError" - -try: 5.0 // 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError" - -try: 5.0 % 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError" - -try: 5L / 0 -except ZeroDivisionError: pass -else: raise TestFailed, "5L / 0 didn't raise ZeroDivisionError" - -try: 5 / 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError" - -try: 5 // 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError" - -try: 5 % 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError" - -print '6.4 Numeric types (mostly conversions)' -if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons' -if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons' -if -1 != -1L or -1 != -1.0 or -1L != -1.0: - raise TestFailed, 'int/long/float value not equal' -# calling built-in types without argument must return 0 -if int() != 0: raise TestFailed, 'int() does not return 0' -if long() != 0L: raise TestFailed, 'long() does not return 0L' -if float() != 0.0: raise TestFailed, 'float() does not return 0.0' -if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass -else: raise TestFailed, 'int() does not round properly' -if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass -else: raise TestFailed, 'long() does not round properly' -if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass -else: raise TestFailed, 'float() does not work properly' -print '6.4.1 32-bit integers' -if 12 + 24 != 36: raise TestFailed, 'int op' -if 12 + (-24) != -12: raise TestFailed, 'int op' -if (-12) + 24 != 12: raise TestFailed, 'int op' -if (-12) + (-24) != -36: raise TestFailed, 'int op' -if not 12 < 24: raise TestFailed, 'int op' -if not -24 < -12: raise TestFailed, 'int op' -# Test for a particular bug in integer multiply -xsize, ysize, zsize = 238, 356, 4 -if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): - raise TestFailed, 'int mul commutativity' -# And another. -m = -sys.maxint - 1 -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - prod = divisor * j - if prod != m: - raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m) - if type(prod) is not int: - raise TestFailed, ("expected type(prod) to be int, not %r" % - type(prod)) -# Check for expected * overflow to long. -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) -# Check for expected * overflow to long. -m = sys.maxint -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor + 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) - -print '6.4.2 Long integers' -if 12L + 24L != 36L: raise TestFailed, 'long op' -if 12L + (-24L) != -12L: raise TestFailed, 'long op' -if (-12L) + 24L != 12L: raise TestFailed, 'long op' -if (-12L) + (-24L) != -36L: raise TestFailed, 'long op' -if not 12L < 24L: raise TestFailed, 'long op' -if not -24L < -12L: raise TestFailed, 'long op' -x = sys.maxint -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)+1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' -x = -x -if int(long(x)) != x: raise TestFailed, 'long op' -x = x-1 -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)-1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' - -try: 5 << -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift <<' - -try: 5L << -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift <<' - -try: 5 >> -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift >>' - -try: 5L >> -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift >>' - -print '6.4.3 Floating point numbers' -if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op' -if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op' -if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op' -if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op' -if not 12.0 < 24.0: raise TestFailed, 'float op' -if not -24.0 < -12.0: raise TestFailed, 'float op' - -print '6.5 Sequence types' - -print '6.5.1 Strings' -if len('') != 0: raise TestFailed, 'len(\'\')' -if len('a') != 1: raise TestFailed, 'len(\'a\')' -if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')' -if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation' -if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3' -if 0*'abcde' != '': raise TestFailed, 'string repetition 0*' -if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string' -if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass -else: raise TestFailed, 'in/not in string' -x = 'x'*103 -if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug' - -#extended slices for strings -a = '0123456789' -vereq(a[::], a) -vereq(a[::2], '02468') -vereq(a[1::2], '13579') -vereq(a[::-1],'9876543210') -vereq(a[::-2], '97531') -vereq(a[3::-2], '31') -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], '02468') - -if have_unicode: - a = unicode('0123456789', 'ascii') - vereq(a[::], a) - vereq(a[::2], unicode('02468', 'ascii')) - vereq(a[1::2], unicode('13579', 'ascii')) - vereq(a[::-1], unicode('9876543210', 'ascii')) - vereq(a[::-2], unicode('97531', 'ascii')) - vereq(a[3::-2], unicode('31', 'ascii')) - vereq(a[-100:100:], a) - vereq(a[100:-100:-1], a[::-1]) - vereq(a[-100L:100L:2L], unicode('02468', 'ascii')) - - -print '6.5.2 Tuples' -# calling built-in types without argument must return empty -if tuple() != (): raise TestFailed,'tuple() does not return ()' -if len(()) != 0: raise TestFailed, 'len(())' -if len((1,)) != 1: raise TestFailed, 'len((1,))' -if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))' -if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation' -if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3' -if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*' -if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple' -if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass -else: raise TestFailed, 'in/not in tuple' -try: ()[0] -except IndexError: pass -else: raise TestFailed, "tuple index error didn't raise IndexError" -x = () -x += () -if x != (): raise TestFailed, 'tuple inplace add from () to () failed' -x += (1,) -if x != (1,): raise TestFailed, 'tuple resize from () failed' - -# extended slicing - subscript only for tuples -a = (0,1,2,3,4) -vereq(a[::], a) -vereq(a[::2], (0,2,4)) -vereq(a[1::2], (1,3)) -vereq(a[::-1], (4,3,2,1,0)) -vereq(a[::-2], (4,2,0)) -vereq(a[3::-2], (3,1)) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], (0,2,4)) - -# Check that a specific bug in _PyTuple_Resize() is squashed. -def f(): - for i in range(1000): - yield i -vereq(list(tuple(f())), range(1000)) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO: this fails with PyPy because overriding __getitem__ will -# really override what the sequence iterator returns -#class T(tuple): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(T((1,2))).next(), 1) - -print '6.5.3 Lists' -# calling built-in types without argument must return empty -if list() != []: raise TestFailed,'list() does not return []' -if len([]) != 0: raise TestFailed, 'len([])' -if len([1,]) != 1: raise TestFailed, 'len([1,])' -if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])' -if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation' -if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3' -if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L' -if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*' -if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*' -if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list' -if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass -else: raise TestFailed, 'in/not in list' -a = [1, 2, 3, 4, 5] -a[:-1] = a -if a != [1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (head)" -a = [1, 2, 3, 4, 5] -a[1:] = a -if a != [1, 1, 2, 3, 4, 5]: - raise TestFailed, "list self-slice-assign (tail)" -a = [1, 2, 3, 4, 5] -a[1:-1] = a -if a != [1, 1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (center)" -try: [][0] -except IndexError: pass -else: raise TestFailed, "list index error didn't raise IndexError" -try: [][0] = 5 -except IndexError: pass -else: raise TestFailed, "list assignment index error didn't raise IndexError" -try: [].pop() -except IndexError: pass -else: raise TestFailed, "empty list.pop() didn't raise IndexError" -try: [1].pop(5) -except IndexError: pass -else: raise TestFailed, "[1].pop(5) didn't raise IndexError" -try: [][0:1] = 5 -except TypeError: pass -else: raise TestFailed, "bad list slice assignment didn't raise TypeError" -try: [].extend(None) -except TypeError: pass -else: raise TestFailed, "list.extend(None) didn't raise TypeError" -a = [1, 2, 3, 4] -a *= 0 -if a != []: - raise TestFailed, "list inplace repeat" - -a = [] -a[:] = tuple(range(10)) -if a != range(10): - raise TestFailed, "assigning tuple to slice" - -print '6.5.3a Additional list operations' -a = [0,1,2,3,4] -a[0L] = 1 -a[1L] = 2 -a[2L] = 3 -if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]' -a[0] = 5 -a[1] = 6 -a[2] = 7 -if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]' -a[-2L] = 88 -a[-1L] = 99 -if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]' -a[-2] = 8 -a[-1] = 9 -if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]' -a[:2] = [0,4] -a[-3:] = [] -a[1:1] = [1,2,3] -if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment' -a[ 1L : 4L] = [7,8,9] -if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints' -del a[1:4] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=range(0,5) -del a[1L:4L] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0L] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1L] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=[] -a.append(0) -a.append(1) -a.append(2) -if a != [0,1,2]: raise TestFailed, 'list append' -a.insert(0, -2) -a.insert(1, -1) -a.insert(2,0) -if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert' -b = a[:] -b.insert(-2, "foo") -b.insert(-200, "left") -b.insert(200, "right") -if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2' -# a = [-2,-1,0,0,1,2] -if a.count(0) != 2: raise TestFailed, ' list count' -if a.index(0) != 2: raise TestFailed, 'list index' -if a.index(0,2) != 2: raise TestFailed, 'list index, start argument' -if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' -if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument' -if a.index(0,3) != 3: raise TestFailed, 'list index, start argument' -if a.index(0,-3) != 3: raise TestFailed, 'list index, -start argument' -if a.index(0,3,4) != 3: raise TestFailed, 'list index, stop argument' -if a.index(0,-3,-2) != 3: raise TestFailed, 'list index, -stop argument' -if a.index(0,-4*sys.maxint,4*sys.maxint) != 2: - raise TestFailed, 'list index, -maxint, maxint argument' -try: - a.index(0, 4*sys.maxint,-4*sys.maxint) -except ValueError: - pass -else: - raise TestFailed, 'list index, maxint,-maxint argument' - -try: - a.index(2,0,-10) -except ValueError: - pass -else: - raise TestFailed, 'list index, very -stop argument' -a.remove(0) -try: - a.index(2,0,4) -except ValueError: - pass -else: - raise TestFailed, 'list index, stop argument.' -if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove' -a.reverse() -if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse' -a.sort() -if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort' -def revcmp(a, b): return cmp(b, a) -a.sort(revcmp) -if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func' -# The following dumps core in unpatched Python 1.5: -def myComparison(x,y): - return cmp(x%3, y%7) -z = range(12) -z.sort(myComparison) - -try: z.sort(2) -except TypeError: pass -else: raise TestFailed, 'list sort compare function is not callable' - -''' XXX TODO: add detection of list modification during sort -def selfmodifyingComparison(x,y): - z.append(1) - return cmp(x, y) -try: z.sort(selfmodifyingComparison) -except ValueError: pass -else: raise TestFailed, 'modifying list during sort' -''' - -try: z.sort(lambda x, y: 's') -except TypeError: pass -else: raise TestFailed, 'list sort compare function does not return int' - -# Test extreme cases with long ints -a = [0,1,2,3,4] -if a[ -pow(2,128L): 3 ] != [0,1,2]: - raise TestFailed, "list slicing with too-small long integer" -if a[ 3: pow(2,145L) ] != [3,4]: - raise TestFailed, "list slicing with too-large long integer" - -# extended slicing - -# subscript -a = [0,1,2,3,4] -vereq(a[::], a) -vereq(a[::2], [0,2,4]) -vereq(a[1::2], [1,3]) -vereq(a[::-1], [4,3,2,1,0]) -vereq(a[::-2], [4,2,0]) -vereq(a[3::-2], [3,1]) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], [0,2,4]) -vereq(a[1000:2000:2], []) -vereq(a[-1000:-2000:-2], []) -# deletion -del a[::2] -vereq(a, [1,3]) -a = range(5) -del a[1::2] -vereq(a, [0,2,4]) -a = range(5) -del a[1::-2] -vereq(a, [0,2,3,4]) -a = range(10) -del a[::1000] -vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9]) -# assignment -a = range(10) -a[::2] = [-1]*5 -vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]) -a = range(10) -a[::-4] = [10]*3 -vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]) -a = range(4) -a[::-1] = a -vereq(a, [3, 2, 1, 0]) -a = range(10) -b = a[:] -c = a[:] -a[2:3] = ["two", "elements"] -b[slice(2,3)] = ["two", "elements"] -c[2:3:] = ["two", "elements"] -vereq(a, b) -vereq(a, c) -a = range(10) -a[::2] = tuple(range(5)) -vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9]) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO same as class T(tuple) above -#class L(list): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(L([1,2])).next(), 1) - - -print '6.6 Mappings == Dictionaries' -# calling built-in types without argument must return empty -if dict() != {}: raise TestFailed,'dict() does not return {}' -d = {} -if d.keys() != []: raise TestFailed, '{}.keys()' -if d.values() != []: raise TestFailed, '{}.values()' -if d.items() != []: raise TestFailed, '{}.items()' -if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')' -if ('a' in d) != 0: raise TestFailed, "'a' in {}" -if ('a' not in d) != 1: raise TestFailed, "'a' not in {}" -if len(d) != 0: raise TestFailed, 'len({})' -d = {'a': 1, 'b': 2} -if len(d) != 2: raise TestFailed, 'len(dict)' -k = d.keys() -k.sort() -if k != ['a', 'b']: raise TestFailed, 'dict keys()' -if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass -else: raise TestFailed, 'dict keys()' -if 'a' in d and 'b' in d and 'c' not in d: pass -else: raise TestFailed, 'dict keys() # in/not in version' -if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item' -d['c'] = 3 -d['a'] = 4 -if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment' -del d['b'] -if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion' -print '6.6.1 dict methods' -# dict.clear() -d = {1:1, 2:2, 3:3} -d.clear() -if d != {}: raise TestFailed, 'dict clear' -# dict.update() -d.update({1:100}) -d.update({2:20}) -d.update({1:1, 2:2, 3:3}) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update' -d.clear() -try: d.update(None) -except AttributeError: pass -else: raise TestFailed, 'dict.update(None), AttributeError expected' -print '6.6.2 user-dict methods' -class SimpleUserDict: - def __init__(self): - self.d = {1:1, 2:2, 3:3} - def keys(self): - return self.d.keys() - def __getitem__(self, i): - return self.d[i] -d.update(SimpleUserDict()) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)' -d.clear() -class FailingUserDict: - def keys(self): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.keys() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __iter__(self): - raise ValueError - return BogonIter() -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()) expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = 1 - def __iter__(self): - return self - def next(self): - if self.i: - self.i = 0 - return 'a' - raise ValueError - return BogonIter() - def __getitem__(self, key): - return key -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = ord('a') - def __iter__(self): - return self - def next(self): - if self.i <= ord('z'): - rtn = chr(self.i) - self.i += 1 - return rtn - raise StopIteration - return BogonIter() - def __getitem__(self, key): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError' -print '6.6.3 dict.fromkeys' -# dict.fromkeys() -if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys did not work as a class method' -d = {} -if d.fromkeys('abc') is d: - raise TestFailed, 'dict.fromkeys did not return a new dict' -if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys failed with default value' -if d.fromkeys((4,5),0) != {4:0, 5:0}: - raise TestFailed, 'dict.fromkeys failed with specified value' -if d.fromkeys([]) != {}: - raise TestFailed, 'dict.fromkeys failed with null sequence' -def g(): - yield 1 -if d.fromkeys(g()) != {1:None}: - raise TestFailed, 'dict.fromkeys failed with a generator' -try: {}.fromkeys(3) -except TypeError: pass -else: raise TestFailed, 'dict.fromkeys failed to raise TypeError' -class dictlike(dict): pass -if dictlike.fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if dictlike().fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if type(dictlike.fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' -if type(dictlike().fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' - -from UserDict import UserDict -class mydict(dict): - def __new__(cls): - return UserDict() -ud = mydict.fromkeys('ab') -if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): - raise TestFailed, 'fromkeys did not instantiate using __new__' - -print '6.6.4 dict copy, get, setdefault' - -# dict.copy() -d = {1:1, 2:2, 3:3} -if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy' -if {}.copy() != {}: raise TestFailed, 'empty dict copy' -# dict.get() -d = {} -if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg' -d = {'a' : 1, 'b' : 2} -if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg' -if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg' -if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg' -# dict.setdefault() -d = {} -if d.setdefault('key0') is not None: - raise TestFailed, 'missing {} setdefault, no 2nd arg' -if d.setdefault('key0') is not None: - raise TestFailed, 'present {} setdefault, no 2nd arg' -d.setdefault('key', []).append(3) -if d['key'][0] != 3: - raise TestFailed, 'missing {} setdefault, w/ 2nd arg' -d.setdefault('key', []).append(4) -if len(d['key']) != 2: - raise TestFailed, 'present {} setdefault, w/ 2nd arg' - -print '6.6.5 dict popitem' - -# dict.popitem() -for copymode in -1, +1: - # -1: b has same structure as a - # +1: b is a.copy() - for log2size in range(4):#(12): - size = 2**log2size - a = {} - b = {} - for i in range(size): - a[`i`] = i - if copymode < 0: - b[`i`] = i - if copymode > 0: - b = a.copy() - for i in range(size): - ka, va = ta = a.popitem() - if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta) - kb, vb = tb = b.popitem() - if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb) - if copymode < 0 and ta != tb: - raise TestFailed, "a.popitem != b.popitem: %s, %s" % ( - str(ta), str(tb)) - if a: raise TestFailed, 'a not empty after popitems: %s' % str(a) - if b: raise TestFailed, 'b not empty after popitems: %s' % str(b) - -d.clear() -try: d.popitem() -except KeyError: pass -else: raise TestFailed, "{}.popitem doesn't raise KeyError" - -print '6.6.6 dict pop' - -# Tests for pop with specified key -d.clear() -k, v = 'abc', 'def' -d[k] = v -try: d.pop('ghi') -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary" - -if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair" -if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair" - -try: d.pop(k) -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty" - -# verify longs/ints get same value when key > 32 bits (for 64-bit archs) -# see SF bug #689659 -x = 4503599627370496L -y = 4503599627370496 -h = {x: 'anything', y: 'something else'} -if h[x] != h[y]: - raise TestFailed, "long/int key should match" - -if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value" -d[k] = v -if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair" - -''' TODO: doesn't raise correctly -d[1] = 1 -try: - for i in d: - d[i+1] = 1 -except RuntimeError: - pass -else: - raise TestFailed, "changing dict size during iteration doesn't raise Error" -''' - -print '6.7 type' - -try: type(1, 2) -except TypeError: pass -else: raise TestFailed, 'type(), w/2 args expected TypeError' - -try: type(1, 2, 3, 4) -except TypeError: pass -else: raise TestFailed, 'type(), w/4 args expected TypeError' - -''' TODO: No buffer support yet XXX -print '6.8 buffer' - -try: buffer('asdf', -1) -except ValueError: pass -else: raise TestFailed, "buffer('asdf', -1) should raise ValueError" - -try: buffer(None) -except TypeError: pass -else: raise TestFailed, "buffer(None) should raise TypeError" - -a = buffer('asdf') -hash(a) -b = a * 5 -if a == b: - raise TestFailed, 'buffers should not be equal' -if str(b) != ('asdf' * 5): - raise TestFailed, 'repeated buffer has wrong content' -if str(a * 0) != '': - raise TestFailed, 'repeated buffer zero times has wrong content' -if str(a + buffer('def')) != 'asdfdef': - raise TestFailed, 'concatenation of buffers yields wrong content' - -try: a[1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer assignment should raise TypeError" - -try: a[0:1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer slice assignment should raise TypeError" -''' -print '6.99999999... All tests ran to completion' From hpk at codespeak.net Tue Jan 11 14:25:15 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 14:25:15 +0100 (MET) Subject: [pypy-svn] r8205 - pypy/branch/src-pytest/pypy/appspace/test Message-ID: <20050111132515.242E127BCC@code1.codespeak.net> Author: hpk Date: Tue Jan 11 14:25:14 2005 New Revision: 8205 Modified: pypy/branch/src-pytest/pypy/appspace/test/builtin_functions_test.py pypy/branch/src-pytest/pypy/appspace/test/conftest.py pypy/branch/src-pytest/pypy/appspace/test/support_tests.py Log: some more fixes to appspace (i don't know why i didn't see the problems on my OSX ...) builtin_functions_test.py is disabled by default but if you run it directly you will see a small number of failures that indicate things to fix within PyPy. Modified: pypy/branch/src-pytest/pypy/appspace/test/builtin_functions_test.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/builtin_functions_test.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/builtin_functions_test.py Tue Jan 11 14:25:14 2005 @@ -1,7 +1,6 @@ # Python test set -- built-in functions import autopath -from pypy.tool import testit -from pypy.interpreter.gateway import app2interp +from pypy.interpreter.gateway import app2interp_temp def app_init_globals(): ''' support functionality for these tests ''' @@ -105,18 +104,13 @@ b.L = L -class BuiltinTest(testit.AppTestCase): +class AppTestBuiltin: + objspacename = 'std' full_test = 1 - fully_initialized = False - def setUp(self): - self.space = space = testit.objspace('std') - if self.fully_initialized: - return - - app2interp(app_init_globals).get_function(space)() - self.__class__.fully_initialized = True + def setup_class(cls): + app2interp_temp(app_init_globals)(cls.space) # we use "if 1:" to keep all method definitions indented, making # it maximally easy to edit this file to pick and choose which @@ -126,37 +120,37 @@ __import__('sys') __import__('time') __import__('string') - self.assertRaises(ImportError, __import__, 'spamspam') - self.assertRaises(TypeError, __import__, 1, 2, 3, 4) + raises(ImportError, __import__, 'spamspam') + raises(TypeError, __import__, 1, 2, 3, 4) def test_abs(self): # int - self.assertEqual(abs(0), 0) - self.assertEqual(abs(1234), 1234) - self.assertEqual(abs(-1234), 1234) + assert abs(0) == 0 + assert abs(1234) == 1234 + assert abs(-1234) == 1234 # float - self.assertEqual(abs(0.0), 0.0) - self.assertEqual(abs(3.14), 3.14) - self.assertEqual(abs(-3.14), 3.14) + assert abs(0.0) == 0.0 + assert abs(3.14) == 3.14 + assert abs(-3.14) == 3.14 # long - self.assertEqual(abs(0L), 0L) - self.assertEqual(abs(1234L), 1234L) - self.assertEqual(abs(-1234L), 1234L) + assert abs(0L) == 0L + assert abs(1234L) == 1234L + assert abs(-1234L) == 1234L # str - self.assertRaises(TypeError, abs, 'a') + raises(TypeError, abs, 'a') def test_apply(self): def f0(*args): - self.assertEqual(args, ()) + assert args == () def f1(a1): - self.assertEqual(a1, 1) + assert a1 == 1 def f2(a1, a2): - self.assertEqual(a1, 1) - self.assertEqual(a2, 2) + assert a1 == 1 + assert a2 == 2 def f3(a1, a2, a3): - self.assertEqual(a1, 1) - self.assertEqual(a2, 2) - self.assertEqual(a3, 3) + assert a1 == 1 + assert a2 == 2 + assert a3 == 3 apply(f0, ()) apply(f1, (1,)) apply(f2, (1, 2)) @@ -166,75 +160,75 @@ # an empty keyword dictionary to pass without a complaint, but # raise a TypeError if the dictionary is non-empty. apply(id, (1,), {}) - self.assertRaises(TypeError, apply, id, (1,), {"foo": 1}) - self.assertRaises(TypeError, apply) - self.assertRaises(TypeError, apply, id, 42) - self.assertRaises(TypeError, apply, id, (42,), 42) + raises(TypeError, apply, id, (1,), {"foo": 1}) + raises(TypeError, apply) + raises(TypeError, apply, id, 42) + raises(TypeError, apply, id, (42,), 42) def test_callable(self): - self.assert_(callable(len)) + assert callable(len) def f(): pass - self.assert_(callable(f)) + assert callable(f) class C: def meth(self): pass - self.assert_(callable(C)) + assert callable(C) x = C() - self.assert_(callable(x.meth)) - self.assert_(not callable(x)) + assert callable(x.meth) + assert not callable(x) class D(C): def __call__(self): pass y = D() - self.assert_(callable(y)) + assert callable(y) y() def test_chr(self): - self.assertEqual(chr(32), ' ') - self.assertEqual(chr(65), 'A') - self.assertEqual(chr(97), 'a') - self.assertEqual(chr(0xff), '\xff') - self.assertRaises(ValueError, chr, 256) - self.assertRaises(TypeError, chr) + assert chr(32) == ' ' + assert chr(65) == 'A' + assert chr(97) == 'a' + assert chr(0xff) == '\xff' + raises(ValueError, chr, 256) + raises(TypeError, chr) def test_cmp(self): - self.assertEqual(cmp(-1, 1), -1) - self.assertEqual(cmp(1, -1), 1) - self.assertEqual(cmp(1, 1), 0) + assert cmp(-1, 1) == -1 + assert cmp(1, -1) == 1 + assert cmp(1, 1) == 0 ''' TODO XXX Circular objects not handled yet # verify that circular objects are handled a = []; a.append(a) b = []; b.append(b) from UserList import UserList c = UserList(); c.append(c) - self.assertEqual(cmp(a, b), 0) - self.assertEqual(cmp(b, c), 0) - self.assertEqual(cmp(c, a), 0) - self.assertEqual(cmp(a, c), 0) + assert cmp(a, b) == 0 + assert cmp(b, c) == 0 + assert cmp(c, a) == 0 + assert cmp(a, c) == 0 # okay, now break the cycles a.pop(); b.pop(); c.pop() ''' - self.assertRaises(TypeError, cmp) + raises(TypeError, cmp) ''' TODO: XXX Coerce is not implemented def test_coerce(self): - self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) - self.assertEqual(coerce(1, 1L), (1L, 1L)) - self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) - self.assertRaises(TypeError, coerce) + assert not fcmp(coerce(1, 1.1), (1.0, 1.1)) + assert coerce(1, 1L) == (1L, 1L) + assert not fcmp(coerce(1L, 1.1), (1.0, 1.1)) + raises(TypeError, coerce) class BadNumber: def __coerce__(self, other): raise ValueError - self.assertRaises(ValueError, coerce, 42, BadNumber()) - self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000)) + raises(ValueError, coerce, 42, BadNumber()) + raises(OverflowError, coerce, 0.5, int("12345" * 1000)) ''' def test_compile(self): compile('print 1\n', '', 'exec') bom = '\xef\xbb\xbf' compile(bom + 'print 1\n', '', 'exec') - self.assertRaises(TypeError, compile) - self.assertRaises(ValueError, compile, + raises(TypeError, compile) + raises(ValueError, compile, 'print 42\n', '', 'badmode') - self.assertRaises(ValueError, compile, + raises(ValueError, compile, 'print 42\n', '', 'single', 0xff) if have_unicode: compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') @@ -243,64 +237,64 @@ import sys sys.spam = 1 delattr(sys, 'spam') - self.assertRaises(TypeError, delattr) + raises(TypeError, delattr) def test_dir(self): x = 1 - self.assert_('x' in dir()) + assert 'x' in dir() import sys - self.assert_('modules' in dir(sys)) - self.assertRaises(TypeError, dir, 42, 42) + assert 'modules' in dir(sys) + raises(TypeError, dir, 42, 42) def test_divmod(self): - self.assertEqual(divmod(12, 7), (1, 5)) - self.assertEqual(divmod(-12, 7), (-2, 2)) - self.assertEqual(divmod(12, -7), (-2, -2)) - self.assertEqual(divmod(-12, -7), (1, -5)) - - self.assertEqual(divmod(12L, 7L), (1L, 5L)) - self.assertEqual(divmod(-12L, 7L), (-2L, 2L)) - self.assertEqual(divmod(12L, -7L), (-2L, -2L)) - self.assertEqual(divmod(-12L, -7L), (1L, -5L)) - - self.assertEqual(divmod(12, 7L), (1, 5L)) - self.assertEqual(divmod(-12, 7L), (-2, 2L)) - self.assertEqual(divmod(12L, -7), (-2L, -2)) - self.assertEqual(divmod(-12L, -7), (1L, -5)) - - self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) - self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) - self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) - self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) + assert divmod(12, 7) == (1, 5) + assert divmod(-12, 7) == (-2, 2) + assert divmod(12, -7) == (-2, -2) + assert divmod(-12, -7) == (1, -5) + + assert divmod(12L, 7L) == (1L, 5L) + assert divmod(-12L, 7L) == (-2L, 2L) + assert divmod(12L, -7L) == (-2L, -2L) + assert divmod(-12L, -7L) == (1L, -5L) + + assert divmod(12, 7L) == (1, 5L) + assert divmod(-12, 7L) == (-2, 2L) + assert divmod(12L, -7) == (-2L, -2) + assert divmod(-12L, -7) == (1L, -5) + + assert not fcmp(divmod(3.25, 1.0), (3.0, 0.25)) + assert not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)) + assert not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)) + assert not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)) - self.assertRaises(TypeError, divmod) + raises(TypeError, divmod) ''' XXX TODO No eval() support yet def test_eval(self): - self.assertEqual(eval('1+1'), 2) - self.assertEqual(eval(' 1+1\n'), 2) + assert eval('1+1') == 2 + assert eval(' 1+1\n') == 2 globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} - self.assertEqual(eval('a', globals) , 1) - self.assertEqual(eval('a', globals, locals), 1) - self.assertEqual(eval('b', globals, locals), 200) - self.assertEqual(eval('c', globals, locals), 300) + assert eval('a', globals) == 1 + assert eval('a', globals, locals) == 1 + assert eval('b', globals, locals) == 200 + assert eval('c', globals, locals) == 300 if have_unicode: - self.assertEqual(eval(unicode('1+1')), 2) - self.assertEqual(eval(unicode(' 1+1\n')), 2) + assert eval(unicode('1+1')) == 2 + assert eval(unicode(' 1+1\n')) == 2 globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} if have_unicode: - self.assertEqual(eval(unicode('a'), globals), 1) - self.assertEqual(eval(unicode('a'), globals, locals), 1) - self.assertEqual(eval(unicode('b'), globals, locals), 200) - self.assertEqual(eval(unicode('c'), globals, locals), 300) + assert eval(unicode('a'), globals) == 1 + assert eval(unicode('a'), globals, locals) == 1 + assert eval(unicode('b'), globals, locals) == 200 + assert eval(unicode('c'), globals, locals) == 300 bom = '\xef\xbb\xbf' - self.assertEqual(eval(bom + 'a', globals, locals), 1) - self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals), + assert eval(bom + 'a', globals, locals) == 1 + assert eval(unicode('u"\xc3\xa5"', 'utf8'), globals) == ( unicode('\xc3\xa5', 'utf8')) - self.assertRaises(TypeError, eval) - self.assertRaises(TypeError, eval, ()) + raises(TypeError, eval) + raises(TypeError, eval, ()) '\'' XXX TODO: Figure out later # Done outside of the method test_z to get the correct scope @@ -315,18 +309,18 @@ globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} - self.assertEqual(self.__class__.z, 2) + assert self.__class__.z == 2 globals['z'] = 0 execfile(TESTFN, globals) - self.assertEqual(globals['z'], 2) + assert globals['z'] == 2 locals['z'] = 0 execfile(TESTFN, globals, locals) - self.assertEqual(locals['z'], 2) + assert locals['z'] == 2 unlink(TESTFN) - self.assertRaises(TypeError, execfile) + raises(TypeError, execfile) import os - self.assertRaises(IOError, execfile, os.curdir) - self.assertRaises(IOError, execfile, "I_dont_exist") + raises(IOError, execfile, os.curdir) + raises(IOError, execfile, "I_dont_exist") '\'' ''' @@ -338,90 +332,90 @@ most of these tests with more appropriate ones! ''' def test_filter(self): - self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), + assert filter(lambda c: 'a' <= c <= 'z', 'Hello World') == ( 'elloorld') - self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]) - , [1, 'hello', [3], 9]) - self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), + assert (filter(None, [1, 'hello', [], [3], '', None, 9, 0]) + ) == [1, 'hello', [3], 9] + assert filter(lambda x: x > 0, [1, -3, 9, 0, 2]) == ( [1, 9, 2]) - self.assertEqual(filter(None, Squares(10)), + assert filter(None, Squares(10)) == ( [1, 4, 9, 16, 25, 36, 49, 64, 81]) - self.assertEqual(filter(lambda x: x%2, Squares(10)), + assert filter(lambda x: x%2, Squares(10)) == ( [1, 9, 25, 49, 81]) def identity(item): return 1 filter(identity, Squares(5)) - self.assertRaises(TypeError, filter) + raises(TypeError, filter) ''' XXX rest of test disabled as above explained class BadSeq(object): def __getitem__(self, index): if index<4: return 42 raise ValueError - self.assertRaises(ValueError, filter, lambda x: x, BadSeq()) + raises(ValueError, filter, lambda x: x, BadSeq()) def badfunc(): pass - self.assertRaises(TypeError, filter, badfunc, range(5)) + raises(TypeError, filter, badfunc, range(5)) # test bltinmodule.c::filtertuple() - self.assertEqual(filter(None, (1, 2)), (1, 2)) - self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4)) - self.assertRaises(TypeError, filter, 42, (1, 2)) + assert filter(None, (1, 2)) == (1, 2) + assert filter(lambda x: x>=3, (1, 2, 3, 4)) == (3, 4) + raises(TypeError, filter, 42, (1, 2)) # test bltinmodule.c::filterstring() - self.assertEqual(filter(None, "12"), "12") - self.assertEqual(filter(lambda x: x>="3", "1234"), "34") - self.assertRaises(TypeError, filter, 42, "12") + assert filter(None, "12") == "12" + assert filter(lambda x: x>="3", "1234") == "34" + raises(TypeError, filter, 42, "12") class badstr(str): def __getitem__(self, index): raise ValueError - self.assertRaises(ValueError, filter, + raises(ValueError, filter, lambda x: x >="3", badstr("1234")) class badstr2(str): def __getitem__(self, index): return 42 - self.assertRaises(TypeError, filter, + raises(TypeError, filter, lambda x: x >=42, badstr2("1234")) class weirdstr(str): def __getitem__(self, index): return weirdstr(2*str.__getitem__(self, index)) - self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), + assert filter(lambda x: x>="33", weirdstr("1234")) == ( "3344") class shiftstr(str): def __getitem__(self, index): return chr(ord(str.__getitem__(self, index))+1) - self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345") + assert filter(lambda x: x>="3", shiftstr("1234")) == "345" if have_unicode: # test bltinmodule.c::filterunicode() - self.assertEqual(filter(None, unicode("12")), unicode("12")) - self.assertEqual(filter(lambda x: x>="3", unicode("1234")), + assert filter(None, unicode("12")) == unicode("12") + assert filter(lambda x: x>="3", unicode("1234")) == ( unicode("34")) - self.assertRaises(TypeError, filter, 42, unicode("12")) - self.assertRaises(ValueError, filter, lambda x: x >="3", + raises(TypeError, filter, 42, unicode("12")) + raises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234"))) class badunicode(unicode): def __getitem__(self, index): return 42 - self.assertRaises(TypeError, filter, lambda x: x >=42, + raises(TypeError, filter, lambda x: x >=42, badunicode("1234")) class weirdunicode(unicode): def __getitem__(self, index): return weirdunicode(2*unicode.__getitem__(self, index)) - self.assertEqual( - filter(lambda x: x>=unicode("33"), weirdunicode("1234")), + assert ( + filter(lambda x: x>=unicode("33"), weirdunicode("1234"))) == ( unicode("3344")) class shiftunicode(unicode): def __getitem__(self, index): return unichr(ord(unicode.__getitem__(self, index))+1) - self.assertEqual( - filter(lambda x: x>=unicode("3"), shiftunicode("1234")), + assert ( + filter(lambda x: x>=unicode("3"), shiftunicode("1234"))) == ( unicode("345") ) @@ -452,64 +446,64 @@ for (inp, exp) in inps.iteritems(): # make sure the output goes through __getitem__ # even if func is None - self.assertEqual( - filter(funcs[0], cls(inp)), + assert ( + filter(funcs[0], cls(inp))) == ( filter(funcs[1], cls(inp)) ) for func in funcs: outp = filter(func, cls(inp)) - self.assertEqual(outp, exp) - self.assert_(not isinstance(outp, cls)) + assert outp == exp + assert not isinstance(outp, cls) ''' def test_float(self): - self.assertEqual(float(3.14), 3.14) - self.assertEqual(float(314), 314.0) - self.assertEqual(float(314L), 314.0) - self.assertEqual(float(" 3.14 "), 3.14) + assert float(3.14) == 3.14 + assert float(314) == 314.0 + assert float(314L) == 314.0 + assert float(" 3.14 ") == 3.14 if have_unicode: - self.assertEqual(float(unicode(" 3.14 ")), 3.14) - self.assertEqual(float(unicode( - " \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14) + assert float(unicode(" 3.14 ")) == 3.14 + assert float(unicode( + " \u0663.\u0661\u0664 ",'raw-unicode-escape')) == 3.14 def test_getattr(self): import sys - self.assert_(getattr(sys, 'stdout') is sys.stdout) - self.assertRaises(TypeError, getattr, sys, 1) - self.assertRaises(TypeError, getattr, sys, 1, "foo") - self.assertRaises(TypeError, getattr) + assert getattr(sys, 'stdout') is sys.stdout + raises(TypeError, getattr, sys, 1) + raises(TypeError, getattr, sys, 1, "foo") + raises(TypeError, getattr) if have_unicode: - self.assertRaises(UnicodeError, getattr, sys, + raises(UnicodeError, getattr, sys, unichr(sys.maxunicode)) def test_hasattr(self): import sys - self.assert_(hasattr(sys, 'stdout')) - self.assertRaises(TypeError, hasattr, sys, 1) - self.assertRaises(TypeError, hasattr) + assert hasattr(sys, 'stdout') + raises(TypeError, hasattr, sys, 1) + raises(TypeError, hasattr) if have_unicode: - self.assertRaises(UnicodeError, hasattr, sys, + raises(UnicodeError, hasattr, sys, unichr(sys.maxunicode)) def test_hash(self): hash(None) - self.assertEqual(hash(1), hash(1L)) - self.assertEqual(hash(1), hash(1.0)) + assert hash(1) == hash(1L) + assert hash(1) == hash(1.0) hash('spam') if have_unicode: - self.assertEqual(hash('spam'), hash(unicode('spam'))) + assert hash('spam') == hash(unicode('spam')) hash((0,1,2,3)) def f(): pass - self.assertRaises(TypeError, hash, []) - self.assertRaises(TypeError, hash, {}) + raises(TypeError, hash, []) + raises(TypeError, hash, {}) def test_hex(self): - self.assertEqual(hex(16), '0x10') - self.assertEqual(hex(16L), '0x10L') - self.assertEqual(len(hex(-1)), len(hex(sys.maxint))) - self.assert_(hex(-16) in ('0xfffffff0', '0xfffffffffffffff0')) - self.assertEqual(hex(-16L), '-0x10L') - self.assertRaises(TypeError, hex, {}) + assert hex(16) == '0x10' + assert hex(16L) == '0x10L' + assert len(hex(-1)) == len(hex(sys.maxint)) + assert hex(-16) in ('0xfffffff0', '0xfffffffffffffff0') + assert hex(-16L) == '-0x10L' + raises(TypeError, hex, {}) def test_id(self): id(None) @@ -524,19 +518,19 @@ # Test input() later, together with raw_input def test_int(self): - self.assertEqual(int(314), 314) - self.assertEqual(int(3.14), 3) - self.assertEqual(int(314L), 314) + assert int(314) == 314 + assert int(3.14) == 3 + assert int(314L) == 314 # Check that conversion from float truncates towards zero - self.assertEqual(int(-3.14), -3) - self.assertEqual(int(3.9), 3) - self.assertEqual(int(-3.9), -3) - self.assertEqual(int(3.5), 3) - self.assertEqual(int(-3.5), -3) + assert int(-3.14) == -3 + assert int(3.9) == 3 + assert int(-3.9) == -3 + assert int(3.5) == 3 + assert int(-3.5) == -3 # Different base: - self.assertEqual(int("10",16), 16L) + assert int("10",16) == 16L if have_unicode: - self.assertEqual(int(unicode("10"),16), 16L) + assert int(unicode("10"),16) == 16L # Test conversion from strings and various anomalies for s, v in L: for sign in "", "+", "-": @@ -546,63 +540,63 @@ if sign == "-" and v is not ValueError: vv = -v try: - self.assertEqual(int(ss), vv) + assert int(ss) == vv except v: pass s = `-1-sys.maxint` - self.assertEqual(int(s)+1, -sys.maxint) + assert int(s)+1 == -sys.maxint # should return long ''' XXX TODO: Longs not well supported yet int(s[1:]) # should return long x = int(1e100) - self.assert_(isinstance(x, long)) + assert isinstance(x, long) x = int(-1e100) - self.assert_(isinstance(x, long)) + assert isinstance(x, long) ''' # SF bug 434186: 0x80000000/2 != 0x80000000>>1. # Worked by accident in Windows release build, but failed in # debug build. Failed in all Linux builds. x = -1-sys.maxint - self.assertEqual(x >> 1, x//2) + assert x >> 1 == x//2 - self.assertRaises(ValueError, int, '123\0') - self.assertRaises(ValueError, int, '53', 40) + raises(ValueError, int, '123\0') + raises(ValueError, int, '53', 40) ''' XXX TODO: Longs not supported yet x = int('1' * 600) - self.assert_(isinstance(x, long)) + assert isinstance(x, long) if have_unicode: x = int(unichr(0x661) * 600) - self.assert_(isinstance(x, long)) + assert isinstance(x, long) - self.assertRaises(TypeError, int, 1, 12) + raises(TypeError, int, 1, 12) ''' - self.assertEqual(int('0123', 0), 83) + assert int('0123', 0) == 83 def test_intern(self): - self.assertRaises(TypeError, intern) + raises(TypeError, intern) s = "never interned before" - self.assert_(intern(s) is s) + assert intern(s) is s s2 = s.swapcase().swapcase() - self.assert_(intern(s2) is s) + assert intern(s2) is s def test_iter(self): - self.assertRaises(TypeError, iter) - self.assertRaises(TypeError, iter, 42, 42) + raises(TypeError, iter) + raises(TypeError, iter, 42, 42) lists = [("1", "2"), ["1", "2"], "12"] if have_unicode: lists.append(unicode("12")) for l in lists: i = iter(l) - self.assertEqual(i.next(), '1') - self.assertEqual(i.next(), '2') - self.assertRaises(StopIteration, i.next) + assert i.next() == '1' + assert i.next() == '2' + raises(StopIteration, i.next) def test_isinstance(self): class C: @@ -614,13 +608,13 @@ c = C() d = D() e = E() - self.assert_(isinstance(c, C)) - self.assert_(isinstance(d, C)) - self.assert_(not isinstance(e, C)) - self.assert_(not isinstance(c, D)) - self.assert_(not isinstance('foo', E)) - self.assertRaises(TypeError, isinstance, E, 'foo') - self.assertRaises(TypeError, isinstance) + assert isinstance(c, C) + assert isinstance(d, C) + assert not isinstance(e, C) + assert not isinstance(c, D) + assert not isinstance('foo', E) + raises(TypeError, isinstance, E, 'foo') + raises(TypeError, isinstance) def test_issubclass(self): class C: @@ -632,37 +626,37 @@ c = C() d = D() e = E() - self.assert_(issubclass(D, C)) - self.assert_(issubclass(C, C)) - self.assert_(not issubclass(C, D)) - self.assertRaises(TypeError, issubclass, 'foo', E) - self.assertRaises(TypeError, issubclass, E, 'foo') - self.assertRaises(TypeError, issubclass) + assert issubclass(D, C) + assert issubclass(C, C) + assert not issubclass(C, D) + raises(TypeError, issubclass, 'foo', E) + raises(TypeError, issubclass, E, 'foo') + raises(TypeError, issubclass) def test_len(self): - self.assertEqual(len('123'), 3) - self.assertEqual(len(()), 0) - self.assertEqual(len((1, 2, 3, 4)), 4) - self.assertEqual(len([1, 2, 3, 4]), 4) - self.assertEqual(len({}), 0) - self.assertEqual(len({'a':1, 'b': 2}), 2) + assert len('123') == 3 + assert len(()) == 0 + assert len((1, 2, 3, 4)) == 4 + assert len([1, 2, 3, 4]) == 4 + assert len({}) == 0 + assert len({'a':1, 'b': 2}) == 2 class BadSeq: def __len__(self): raise ValueError - self.assertRaises(ValueError, len, BadSeq()) + raises(ValueError, len, BadSeq()) if 1: def test_list(self): - self.assertEqual(list([]), []) + assert list([]) == [] l0_3 = [0, 1, 2, 3] l0_3_bis = list(l0_3) - self.assertEqual(l0_3, l0_3_bis) - self.assert_(l0_3 is not l0_3_bis) - self.assertEqual(list(()), []) - self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) - self.assertEqual(list(''), []) - self.assertEqual(list('spam'), ['s', 'p', 'a', 'm']) + assert l0_3 == l0_3_bis + assert l0_3 is not l0_3_bis + assert list(()) == [] + assert list((0, 1, 2, 3)) == [0, 1, 2, 3] + assert list('') == [] + assert list('spam') == ['s', 'p', 'a', 'm'] ''' XXX TODO: disabled for now -- far too slow! if sys.maxint == 0x7fffffff: @@ -680,27 +674,27 @@ # thread for the details: # http://sources.redhat.com/ml/newlib/2002/msg00369.html - self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) + raises(MemoryError, list, xrange(sys.maxint // 2)) ''' ''' XXX TODO: disabled for now -- long not yet well supported def test_long(self): - self.assertEqual(long(314), 314L) - self.assertEqual(long(3.14), 3L) - self.assertEqual(long(314L), 314L) + assert long(314) == 314L + assert long(3.14) == 3L + assert long(314L) == 314L # Check that conversion from float truncates towards zero - self.assertEqual(long(-3.14), -3L) - self.assertEqual(long(3.9), 3L) - self.assertEqual(long(-3.9), -3L) - self.assertEqual(long(3.5), 3L) - self.assertEqual(long(-3.5), -3L) - self.assertEqual(long("-3"), -3L) + assert long(-3.14) == -3L + assert long(3.9) == 3L + assert long(-3.9) == -3L + assert long(3.5) == 3L + assert long(-3.5) == -3L + assert long("-3") == -3L if have_unicode: - self.assertEqual(long(unicode("-3")), -3L) + assert long(unicode("-3")) == -3L # Different base: - self.assertEqual(long("10",16), 16L) + assert long("10",16) == 16L if have_unicode: - self.assertEqual(long(unicode("10"),16), 16L) + assert long(unicode("10"),16) == 16L # Check conversions from string (same test set as for int(), and then some) LL = [ ('1' + '0'*20, 10L**20), @@ -720,30 +714,30 @@ if sign == "-" and v is not ValueError: vv = -v try: - self.assertEqual(long(ss), long(vv)) + assert long(ss) == long(vv) except v: pass - self.assertRaises(ValueError, long, '123\0') - self.assertRaises(ValueError, long, '53', 40) - self.assertRaises(TypeError, long, 1, 12) + raises(ValueError, long, '123\0') + raises(ValueError, long, '53', 40) + raises(TypeError, long, 1, 12) ''' def test_map(self): - self.assertEqual( - map(None, 'hello world'), + assert ( + map(None, 'hello world')) == ( ['h','e','l','l','o',' ','w','o','r','l','d'] ) - self.assertEqual( - map(None, 'abcd', 'efg'), + assert ( + map(None, 'abcd', 'efg')) == ( [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)] ) - self.assertEqual( - map(None, range(10)), + assert ( + map(None, range(10))) == ( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ) - self.assertEqual( - map(lambda x: x*x, range(1,4)), + assert ( + map(lambda x: x*x, range(1,4))) == ( [1, 4, 9] ) try: @@ -751,12 +745,12 @@ except ImportError: def sqrt(x): return pow(x, 0.5) - self.assertEqual( - map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]), + assert ( + map(lambda x: map(sqrt,x), [[16, 4], [81, 9]])) == ( [[4.0, 2.0], [9.0, 3.0]] ) - self.assertEqual( - map(lambda x, y: x+y, [1,3,2], [9,1,4]), + assert ( + map(lambda x, y: x+y, [1,3,2], [9,1,4])) == ( [10, 4, 6] ) @@ -764,82 +758,82 @@ accu = 0 for i in v: accu = accu + i return accu - self.assertEqual( - map(plus, [1, 3, 7]), + assert ( + map(plus, [1, 3, 7])) == ( [1, 3, 7] ) - self.assertEqual( - map(plus, [1, 3, 7], [4, 9, 2]), + assert ( + map(plus, [1, 3, 7], [4, 9, 2])) == ( [1+4, 3+9, 7+2] ) - self.assertEqual( - map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]), + assert ( + map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])) == ( [1+4+1, 3+9+1, 7+2+0] ) - self.assertEqual( - map(None, Squares(10)), + assert ( + map(None, Squares(10))) == ( [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ) - self.assertEqual( - map(int, Squares(10)), + assert ( + map(int, Squares(10))) == ( [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ) - self.assertEqual( - map(None, Squares(3), Squares(2)), + assert ( + map(None, Squares(3), Squares(2))) == ( [(0,0), (1,1), (4,None)] ) - self.assertEqual( - map(max, Squares(3), Squares(2)), + assert ( + map(max, Squares(3), Squares(2))) == ( [0, 1, 4] ) - self.assertRaises(TypeError, map) - self.assertRaises(TypeError, map, lambda x: x, 42) - self.assertEqual(map(None, [42]), [42]) + raises(TypeError, map) + raises(TypeError, map, lambda x: x, 42) + assert map(None, [42]) == [42] class BadSeq: def __getitem__(self, index): raise ValueError - self.assertRaises(ValueError, map, lambda x: x, BadSeq()) + raises(ValueError, map, lambda x: x, BadSeq()) def test_max(self): - self.assertEqual(max('123123'), '3') - self.assertEqual(max(1, 2, 3), 3) - self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) - self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) - - self.assertEqual(max(1, 2L, 3.0), 3.0) - self.assertEqual(max(1L, 2.0, 3), 3) - self.assertEqual(max(1.0, 2, 3L), 3L) + assert max('123123') == '3' + assert max(1, 2, 3) == 3 + assert max((1, 2, 3, 1, 2, 3)) == 3 + assert max([1, 2, 3, 1, 2, 3]) == 3 + + assert max(1, 2L, 3.0) == 3.0 + assert max(1L, 2.0, 3) == 3 + assert max(1.0, 2, 3L) == 3L def test_min(self): - self.assertEqual(min('123123'), '1') - self.assertEqual(min(1, 2, 3), 1) - self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) - self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) - - self.assertEqual(min(1, 2L, 3.0), 1) - self.assertEqual(min(1L, 2.0, 3), 1L) - self.assertEqual(min(1.0, 2, 3L), 1.0) - - self.assertRaises(TypeError, min) - self.assertRaises(TypeError, min, 42) - self.assertRaises(ValueError, min, ()) + assert min('123123') == '1' + assert min(1, 2, 3) == 1 + assert min((1, 2, 3, 1, 2, 3)) == 1 + assert min([1, 2, 3, 1, 2, 3]) == 1 + + assert min(1, 2L, 3.0) == 1 + assert min(1L, 2.0, 3) == 1L + assert min(1.0, 2, 3L) == 1.0 + + raises(TypeError, min) + raises(TypeError, min, 42) + raises(ValueError, min, ()) class BadSeq: def __getitem__(self, index): raise ValueError - self.assertRaises(ValueError, min, BadSeq()) + raises(ValueError, min, BadSeq()) ''' XXX TODO: some weird bug in pypy here -- fix later class BadNumber: def __cmp__(self, other): raise ValueError - self.assertRaises(ValueError, min, (42, BadNumber())) + raises(ValueError, min, (42, BadNumber())) ''' def test_oct(self): - self.assertEqual(oct(100), '0144') - self.assertEqual(oct(100L), '0144L') - self.assert_(oct(-100) in ('037777777634', '01777777777777777777634')) - self.assertEqual(oct(-100L), '-0144L') - self.assertRaises(TypeError, oct, ()) + assert oct(100) == '0144' + assert oct(100L) == '0144L' + assert oct(-100) in ('037777777634', '01777777777777777777634') + assert oct(-100L) == '-0144L' + raises(TypeError, oct, ()) def test_open(self): @@ -859,71 +853,71 @@ write_testfile() fp = open(TESTFN, 'r') try: - self.assertEqual(fp.readline(4), '1+1\n') - self.assertEqual(fp.readline(4), '1+1\n') - self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') - self.assertEqual(fp.readline(4), 'Dear') - self.assertEqual(fp.readline(100), ' John\n') - self.assertEqual(fp.read(300), 'XXX'*100) - self.assertEqual(fp.read(1000), 'YYY'*100) + assert fp.readline(4) == '1+1\n' + assert fp.readline(4) == '1+1\n' + assert fp.readline() == 'The quick brown fox jumps over the lazy dog.\n' + assert fp.readline(4) == 'Dear' + assert fp.readline(100) == ' John\n' + assert fp.read(300) == 'XXX'*100 + assert fp.read(1000) == 'YYY'*100 finally: fp.close() unlink(TESTFN) def test_ord(self): - self.assertEqual(ord(' '), 32) - self.assertEqual(ord('A'), 65) - self.assertEqual(ord('a'), 97) - self.assertRaises(TypeError, ord, 42) + assert ord(' ') == 32 + assert ord('A') == 65 + assert ord('a') == 97 + raises(TypeError, ord, 42) if have_unicode: - self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode) - self.assertRaises(TypeError, ord, unicode("12")) + assert ord(unichr(sys.maxunicode)) == sys.maxunicode + raises(TypeError, ord, unicode("12")) def test_pow(self): - self.assertEqual(pow(0,0), 1) - self.assertEqual(pow(0,1), 0) - self.assertEqual(pow(1,0), 1) - self.assertEqual(pow(1,1), 1) - - self.assertEqual(pow(2,0), 1) - self.assertEqual(pow(2,10), 1024) - self.assertEqual(pow(2,20), 1024*1024) - self.assertEqual(pow(2,30), 1024*1024*1024) - - self.assertEqual(pow(-2,0), 1) - self.assertEqual(pow(-2,1), -2) - self.assertEqual(pow(-2,2), 4) - self.assertEqual(pow(-2,3), -8) - - self.assertEqual(pow(0L,0), 1) - self.assertEqual(pow(0L,1), 0) - self.assertEqual(pow(1L,0), 1) - self.assertEqual(pow(1L,1), 1) - - self.assertEqual(pow(2L,0), 1) - self.assertEqual(pow(2L,10), 1024) - self.assertEqual(pow(2L,20), 1024*1024) - self.assertEqual(pow(2L,30), 1024*1024*1024) - - self.assertEqual(pow(-2L,0), 1) - self.assertEqual(pow(-2L,1), -2) - self.assertEqual(pow(-2L,2), 4) - self.assertEqual(pow(-2L,3), -8) - - self.assertAlmostEqual(pow(0.,0), 1.) - self.assertAlmostEqual(pow(0.,1), 0.) - self.assertAlmostEqual(pow(1.,0), 1.) - self.assertAlmostEqual(pow(1.,1), 1.) - - self.assertAlmostEqual(pow(2.,0), 1.) - self.assertAlmostEqual(pow(2.,10), 1024.) - self.assertAlmostEqual(pow(2.,20), 1024.*1024.) - self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) - - self.assertAlmostEqual(pow(-2.,0), 1.) - self.assertAlmostEqual(pow(-2.,1), -2.) - self.assertAlmostEqual(pow(-2.,2), 4.) - self.assertAlmostEqual(pow(-2.,3), -8.) + assert pow(0,0) == 1 + assert pow(0,1) == 0 + assert pow(1,0) == 1 + assert pow(1,1) == 1 + + assert pow(2,0) == 1 + assert pow(2,10) == 1024 + assert pow(2,20) == 1024*1024 + assert pow(2,30) == 1024*1024*1024 + + assert pow(-2,0) == 1 + assert pow(-2,1) == -2 + assert pow(-2,2) == 4 + assert pow(-2,3) == -8 + + assert pow(0L,0) == 1 + assert pow(0L,1) == 0 + assert pow(1L,0) == 1 + assert pow(1L,1) == 1 + + assert pow(2L,0) == 1 + assert pow(2L,10) == 1024 + assert pow(2L,20) == 1024*1024 + assert pow(2L,30) == 1024*1024*1024 + + assert pow(-2L,0) == 1 + assert pow(-2L,1) == -2 + assert pow(-2L,2) == 4 + assert pow(-2L,3) == -8 + + assert round(pow(0.,0) - 1., 7) == 0 + assert round(pow(0.,1) - 0., 7) == 0 + assert round(pow(1.,0) - 1., 7) == 0 + assert round(pow(1.,1) - 1., 7) == 0 + + assert round(pow(2.,0) - 1., 7) == 0 + assert round(pow(2.,10) - 1024., 7) == 0 + assert round(pow(2.,20) - 1024.*1024., 7) == 0 + assert round(pow(2.,30) - 1024.*1024.*1024., 7) == 0 + + assert round(pow(-2.,0) - 1., 7) == 0 + assert round(pow(-2.,1) - -2., 7) == 0 + assert round(pow(-2.,2) - 4., 7) == 0 + assert round(pow(-2.,3) - -8., 7) == 0 for x in 2, 2L, 2.0: for y in 10, 10L, 10.0: @@ -931,68 +925,68 @@ if isinstance(x, float) or \ isinstance(y, float) or \ isinstance(z, float): - self.assertRaises(TypeError, pow, x, y, z) + raises(TypeError, pow, x, y, z) else: - self.assertAlmostEqual(pow(x, y, z), 24.0) + assert round(pow(x, y, z) - 24.0, 7) == 0 - self.assertRaises(TypeError, pow, -1, -2, 3) - self.assertRaises(ValueError, pow, 1, 2, 0) - self.assertRaises(TypeError, pow, -1L, -2L, 3L) - self.assertRaises(ValueError, pow, 1L, 2L, 0L) - self.assertRaises(ValueError, pow, -342.43, 0.234) + raises(TypeError, pow, -1, -2, 3) + raises(ValueError, pow, 1, 2, 0) + raises(TypeError, pow, -1L, -2L, 3L) + raises(ValueError, pow, 1L, 2L, 0L) + raises(ValueError, pow, -342.43, 0.234) - self.assertRaises(TypeError, pow) + raises(TypeError, pow) def test_range(self): - self.assertEqual(range(3), [0, 1, 2]) - self.assertEqual(range(1, 5), [1, 2, 3, 4]) - self.assertEqual(range(0), []) - self.assertEqual(range(-3), []) - self.assertEqual(range(1, 10, 3), [1, 4, 7]) - self.assertEqual(range(5, -5, -3), [5, 2, -1, -4]) + assert range(3) == [0, 1, 2] + assert range(1, 5) == [1, 2, 3, 4] + assert range(0) == [] + assert range(-3) == [] + assert range(1, 10, 3) == [1, 4, 7] + assert range(5, -5, -3) == [5, 2, -1, -4] # Now test range() with longs - self.assertEqual(range(-2**100), []) - self.assertEqual(range(0, -2**100), []) - self.assertEqual(range(0, 2**100, -1), []) - self.assertEqual(range(0, 2**100, -1), []) + assert range(-2**100) == [] + assert range(0, -2**100) == [] + assert range(0, 2**100, -1) == [] + assert range(0, 2**100, -1) == [] a = long(10 * sys.maxint) b = long(100 * sys.maxint) c = long(50 * sys.maxint) - self.assertEqual(range(a, a+2), [a, a+1]) - self.assertEqual(range(a+2, a, -1L), [a+2, a+1]) - self.assertEqual(range(a+4, a, -2), [a+4, a+2]) + assert range(a, a+2) == [a, a+1] + assert range(a+2, a, -1L) == [a+2, a+1] + assert range(a+4, a, -2) == [a+4, a+2] seq = range(a, b, c) - self.assert_(a in seq) - self.assert_(b not in seq) - self.assertEqual(len(seq), 2) + assert a in seq + assert b not in seq + assert len(seq) == 2 seq = range(b, a, -c) - self.assert_(b in seq) - self.assert_(a not in seq) - self.assertEqual(len(seq), 2) + assert b in seq + assert a not in seq + assert len(seq) == 2 seq = range(-a, -b, -c) - self.assert_(-a in seq) - self.assert_(-b not in seq) - self.assertEqual(len(seq), 2) - - self.assertRaises(TypeError, range) - self.assertRaises(TypeError, range, 1, 2, 3, 4) - self.assertRaises(ValueError, range, 1, 2, 0) + assert -a in seq + assert -b not in seq + assert len(seq) == 2 + + raises(TypeError, range) + raises(TypeError, range, 1, 2, 3, 4) + raises(ValueError, range, 1, 2, 0) # Reject floats when it would require PyLongs to represent. # (smaller floats still accepted, but deprecated) - self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) + raises(TypeError, range, 1e100, 1e101, 1e101) - self.assertRaises(TypeError, range, 0, "spam") - self.assertRaises(TypeError, range, 0, 42, "spam") + raises(TypeError, range, 0, "spam") + raises(TypeError, range, 0, 42, "spam") - self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) - self.assertRaises(OverflowError, range, 0, 2*sys.maxint) + raises(OverflowError, range, -sys.maxint, sys.maxint) + raises(OverflowError, range, 0, 2*sys.maxint) ''' XXX TODO: input and raw_input not supported yet def test_input_and_raw_input(self): @@ -1003,20 +997,20 @@ try: sys.stdin = fp sys.stdout = BitBucket() - self.assertEqual(input(), 2) - self.assertEqual(input('testing\n'), 2) - self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') - self.assertEqual(raw_input('testing\n'), 'Dear John') + assert input() == 2 + assert input('testing\n') == 2 + assert raw_input() == 'The quick brown fox jumps over the lazy dog.' + assert raw_input('testing\n') == 'Dear John' sys.stdin = cStringIO.StringIO("NULL\0") - self.assertRaises(TypeError, input, 42, 42) + raises(TypeError, input, 42, 42) sys.stdin = cStringIO.StringIO(" 'whitespace'") - self.assertEqual(input(), 'whitespace') + assert input() == 'whitespace' sys.stdin = cStringIO.StringIO() - self.assertRaises(EOFError, input) + raises(EOFError, input) del sys.stdout - self.assertRaises(RuntimeError, input, 'prompt') + raises(RuntimeError, input, 'prompt') del sys.stdin - self.assertRaises(RuntimeError, input, 'prompt') + raises(RuntimeError, input, 'prompt') finally: sys.stdin = savestdin sys.stdout = savestdout @@ -1025,30 +1019,30 @@ ''' def test_reduce(self): - self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') - self.assertEqual( - reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), + assert reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') == 'abc' + assert ( + reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], [])) == ( ['a','c','d','w'] ) - self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040) - self.assertEqual( - reduce(lambda x, y: x*y, range(2,21), 1L), + assert reduce(lambda x, y: x*y, range(2,8), 1) == 5040 + assert ( + reduce(lambda x, y: x*y, range(2,21), 1L)) == ( 2432902008176640000L ) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0) - self.assertRaises(TypeError, reduce) - self.assertRaises(TypeError, reduce, 42, 42) - self.assertRaises(TypeError, reduce, 42, 42, 42) - self.assertEqual(reduce(42, "1"), "1") # func is never called with one item - self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item - self.assertRaises(TypeError, reduce, 42, (42, 42)) + assert reduce(lambda x, y: x+y, Squares(10)) == 285 + assert reduce(lambda x, y: x+y, Squares(10), 0) == 285 + assert reduce(lambda x, y: x+y, Squares(0), 0) == 0 + raises(TypeError, reduce) + raises(TypeError, reduce, 42, 42) + raises(TypeError, reduce, 42, 42, 42) + assert reduce(42, "1") == "1" # func is never called with one item + assert reduce(42, "", "1") == "1" # func is never called with one item + raises(TypeError, reduce, 42, (42, 42)) class BadSeq: def __getitem__(self, index): raise ValueError - self.assertRaises(ValueError, reduce, 42, BadSeq()) + raises(ValueError, reduce, 42, BadSeq()) ''' XXX TODO: we don't have reload yet def test_reload(self): @@ -1057,128 +1051,128 @@ import string reload(string) ## import sys - ## self.assertRaises(ImportError, reload, sys) + ## raises(ImportError, reload, sys) ''' def test_repr(self): - self.assertEqual(repr(''), '\'\'') - self.assertEqual(repr(0), '0') - self.assertEqual(repr(0L), '0L') - self.assertEqual(repr(()), '()') - self.assertEqual(repr([]), '[]') - self.assertEqual(repr({}), '{}') + assert repr('') == '\'\'' + assert repr(0) == '0' + assert repr(0L) == '0L' + assert repr(()) == '()' + assert repr([]) == '[]' + assert repr({}) == '{}' ''' XXX TODO: we don't yet support "circular" objects! a = [] a.append(a) - self.assertEqual(repr(a), '[[...]]') + assert repr(a) == '[[...]]' a = {} a[0] = a - self.assertEqual(repr(a), '{0: {...}}') + assert repr(a) == '{0: {...}}' ''' def test_round(self): - self.assertEqual(round(0.0), 0.0) - self.assertEqual(round(1.0), 1.0) - self.assertEqual(round(10.0), 10.0) - self.assertEqual(round(1000000000.0), 1000000000.0) - self.assertEqual(round(1e20), 1e20) - - self.assertEqual(round(-1.0), -1.0) - self.assertEqual(round(-10.0), -10.0) - self.assertEqual(round(-1000000000.0), -1000000000.0) - self.assertEqual(round(-1e20), -1e20) - - self.assertEqual(round(0.1), 0.0) - self.assertEqual(round(1.1), 1.0) - self.assertEqual(round(10.1), 10.0) - self.assertEqual(round(1000000000.1), 1000000000.0) - - self.assertEqual(round(-1.1), -1.0) - self.assertEqual(round(-10.1), -10.0) - self.assertEqual(round(-1000000000.1), -1000000000.0) - - self.assertEqual(round(0.9), 1.0) - self.assertEqual(round(9.9), 10.0) - self.assertEqual(round(999999999.9), 1000000000.0) - - self.assertEqual(round(-0.9), -1.0) - self.assertEqual(round(-9.9), -10.0) - self.assertEqual(round(-999999999.9), -1000000000.0) + assert round(0.0) == 0.0 + assert round(1.0) == 1.0 + assert round(10.0) == 10.0 + assert round(1000000000.0) == 1000000000.0 + assert round(1e20) == 1e20 + + assert round(-1.0) == -1.0 + assert round(-10.0) == -10.0 + assert round(-1000000000.0) == -1000000000.0 + assert round(-1e20) == -1e20 + + assert round(0.1) == 0.0 + assert round(1.1) == 1.0 + assert round(10.1) == 10.0 + assert round(1000000000.1) == 1000000000.0 + + assert round(-1.1) == -1.0 + assert round(-10.1) == -10.0 + assert round(-1000000000.1) == -1000000000.0 + + assert round(0.9) == 1.0 + assert round(9.9) == 10.0 + assert round(999999999.9) == 1000000000.0 + + assert round(-0.9) == -1.0 + assert round(-9.9) == -10.0 + assert round(-999999999.9) == -1000000000.0 - self.assertEqual(round(-8.0, -1), -10.0) + assert round(-8.0, -1) == -10.0 - self.assertRaises(TypeError, round) + raises(TypeError, round) def test_setattr(self): setattr(sys, 'spam', 1) - self.assertEqual(sys.spam, 1) - self.assertRaises(TypeError, setattr, sys, 1, 'spam') - self.assertRaises(TypeError, setattr) + assert sys.spam == 1 + raises(TypeError, setattr, sys, 1, 'spam') + raises(TypeError, setattr) def test_str(self): - self.assertEqual(str(''), '') - self.assertEqual(str(0), '0') - self.assertEqual(str(0L), '0') - self.assertEqual(str(()), '()') - self.assertEqual(str([]), '[]') - self.assertEqual(str({}), '{}') + assert str('') == '' + assert str(0) == '0' + assert str(0L) == '0' + assert str(()) == '()' + assert str([]) == '[]' + assert str({}) == '{}' ''' XXX TODO: we don't yet support "circular" objects! a = [] a.append(a) - self.assertEqual(str(a), '[[...]]') + assert str(a) == '[[...]]' a = {} a[0] = a - self.assertEqual(str(a), '{0: {...}}') + assert str(a) == '{0: {...}}' ''' def test_sum(self): - self.assertEqual(sum([]), 0) - self.assertEqual(sum(range(2,8)), 27) - self.assertEqual(sum(iter(range(2,8))), 27) - self.assertEqual(sum(Squares(10)), 285) - self.assertEqual(sum(iter(Squares(10))), 285) - self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) - - self.assertRaises(TypeError, sum) - self.assertRaises(TypeError, sum, 42) - self.assertRaises(TypeError, sum, ['a', 'b', 'c']) - self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') - self.assertRaises(TypeError, sum, [[1], [2], [3]]) - self.assertRaises(TypeError, sum, [{2:3}]) - self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) + assert sum([]) == 0 + assert sum(range(2,8)) == 27 + assert sum(iter(range(2,8))) == 27 + assert sum(Squares(10)) == 285 + assert sum(iter(Squares(10))) == 285 + assert sum([[1], [2], [3]], []) == [1, 2, 3] + + raises(TypeError, sum) + raises(TypeError, sum, 42) + raises(TypeError, sum, ['a', 'b', 'c']) + raises(TypeError, sum, ['a', 'b', 'c'], '') + raises(TypeError, sum, [[1], [2], [3]]) + raises(TypeError, sum, [{2:3}]) + raises(TypeError, sum, [{2:3}]*2, {2:3}) class BadSeq: def __getitem__(self, index): raise ValueError - self.assertRaises(ValueError, sum, BadSeq()) + raises(ValueError, sum, BadSeq()) def test_tuple(self): - self.assertEqual(tuple(()), ()) + assert tuple(()) == () t0_3 = (0, 1, 2, 3) t0_3_bis = tuple(t0_3) ''' XXX TODO: tuples are immutable -- returns same object in CPython ''' #self.assert_(t0_3 is t0_3_bis) - self.assert_(t0_3 == t0_3_bis) - self.assertEqual(tuple([]), ()) - self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) - self.assertEqual(tuple(''), ()) - self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) + assert t0_3 == t0_3_bis + assert tuple([]) == () + assert tuple([0, 1, 2, 3]) == (0, 1, 2, 3) + assert tuple('') == () + assert tuple('spam') == ('s', 'p', 'a', 'm') def test_type(self): - self.assertEqual(type(''), type('123')) - self.assertNotEqual(type(''), type(())) + assert type('') == type('123') + assert type('') != type(()) def test_unichr(self): if have_unicode: - self.assertEqual(unichr(32), unicode(' ')) - self.assertEqual(unichr(65), unicode('A')) - self.assertEqual(unichr(97), unicode('a')) - self.assertEqual( - unichr(sys.maxunicode), + assert unichr(32) == unicode(' ') + assert unichr(65) == unicode('A') + assert unichr(97) == unicode('a') + assert ( + unichr(sys.maxunicode)) == ( unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape') ) - self.assertRaises(ValueError, unichr, sys.maxunicode+1) - self.assertRaises(TypeError, unichr) + raises(ValueError, unichr, sys.maxunicode+1) + raises(TypeError, unichr) def test_vars(self): def get_vars_f0(): @@ -1188,33 +1182,33 @@ a = 1 b = 2 return vars() - self.assertEqual(Set(vars()), Set(dir())) + assert Set(vars()) == Set(dir()) import sys - self.assertEqual(Set(vars(sys)), Set(dir(sys))) - self.assertEqual(get_vars_f0(), {}) - self.assertEqual(get_vars_f2(), {'a': 1, 'b': 2}) - self.assertRaises(TypeError, vars, 42, 42) - self.assertRaises(TypeError, vars, 42) + assert Set(vars(sys)) == Set(dir(sys)) + assert get_vars_f0() == {} + assert get_vars_f2() == {'a': 1, 'b': 2} + raises(TypeError, vars, 42, 42) + raises(TypeError, vars, 42) def test_zip(self): a = (1, 2, 3) b = (4, 5, 6) t = [(1, 4), (2, 5), (3, 6)] - self.assertEqual(zip(a, b), t) + assert zip(a, b) == t b = [4, 5, 6] - self.assertEqual(zip(a, b), t) + assert zip(a, b) == t b = (4, 5, 6, 7) - self.assertEqual(zip(a, b), t) + assert zip(a, b) == t class I: def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 - self.assertEqual(zip(a, I()), t) - self.assertRaises(TypeError, zip) - self.assertRaises(TypeError, zip, None) + assert zip(a, I()) == t + raises(TypeError, zip) + raises(TypeError, zip, None) class G: pass - self.assertRaises(TypeError, zip, a, G()) + raises(TypeError, zip, a, G()) # Make sure zip doesn't try to allocate a billion elements for the # result list when one of its arguments doesn't say how long it is. @@ -1226,8 +1220,8 @@ else: return i s = SequenceWithoutALength() - self.assertEqual( - zip(s, xrange(2**30)), + assert ( + zip(s, xrange(2**30))) == ( [(x,x) for x in s] ) @@ -1237,7 +1231,4 @@ raise ValueError else: return i - self.assertRaises(ValueError, zip, BadSeq(), BadSeq()) - -if __name__ == '__main__': - testit.main() + raises(ValueError, zip, BadSeq(), BadSeq()) Modified: pypy/branch/src-pytest/pypy/appspace/test/conftest.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/conftest.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/conftest.py Tue Jan 11 14:25:14 2005 @@ -11,7 +11,9 @@ continue #XXX yield RunFileAtAppLevelItem(py.path.extpy(path)) elif self.fil(path): - if path.basename in ('test_complexobject.py',): + if path.basename in ('test_cmathmodule.py', + 'builtin_functions_test.py', + 'test_complexobject.py',): continue yield self.Module(path) elif self.rec(path): Modified: pypy/branch/src-pytest/pypy/appspace/test/support_tests.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/support_tests.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/support_tests.py Tue Jan 11 14:25:14 2005 @@ -110,7 +110,7 @@ try: unicode - have_unicode = 1 + have_unicode = 0 # XXX UNICODE 1 except NameError: have_unicode = 0 From hpk at codespeak.net Tue Jan 11 14:55:51 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 14:55:51 +0100 (MET) Subject: [pypy-svn] r8206 - pypy/branch/src-pytest/pypy/appspace/test Message-ID: <20050111135551.5248827BD8@code1.codespeak.net> Author: hpk Date: Tue Jan 11 14:55:51 2005 New Revision: 8206 Modified: pypy/branch/src-pytest/pypy/appspace/test/support_tests.py Log: get rid of that obnoxious "@test" files which are created if you run the tests in appspace. This now uses the "per-test-session" tempdir and does that by going to py.test.config.tempdir. However, when e.g. running cpy_builtin_functions.py which imports support_tests.py this will now import the py lib at app-level (which fails for shallow reasons). Anyway, i think when caring for regrtests we will certainly substitute support_tests and will try to keep the original regr-tests as much as possible ... in short: this whole current appspace mess will hopefully go away soon. Modified: pypy/branch/src-pytest/pypy/appspace/test/support_tests.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/support_tests.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/support_tests.py Tue Jan 11 14:55:51 2005 @@ -8,6 +8,9 @@ import sys from os import unlink +import py +TESTFN = str(py.test.config.tempdir.join('@test')) + class Error(Exception): """Base class for regression test exceptions.""" @@ -117,21 +120,7 @@ is_jython = sys.platform.startswith('java') -TESTFN = '@test' -# Make sure we can write to TESTFN, try in /tmp if we can't -fp = None -try: - fp = open(TESTFN, 'w+') -except IOError: - TMP_TESTFN = os.path.join('/tmp', TESTFN) - try: - fp = open(TMP_TESTFN, 'w+') - TESTFN = TMP_TESTFN - del TMP_TESTFN - except IOError: - print ('WARNING: tests will fail, unable to write to: %s or %s' % - (TESTFN, TMP_TESTFN)) if fp is not None: fp.close() del fp From hpk at codespeak.net Tue Jan 11 15:01:07 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 15:01:07 +0100 (MET) Subject: [pypy-svn] r8207 - pypy/branch/src-pytest/pypy/tool/test Message-ID: <20050111140107.0F95727BD0@code1.codespeak.net> Author: hpk Date: Tue Jan 11 15:01:06 2005 New Revision: 8207 Modified: pypy/branch/src-pytest/pypy/tool/test/test_cache.py Log: converted another test Modified: pypy/branch/src-pytest/pypy/tool/test/test_cache.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/test/test_cache.py (original) +++ pypy/branch/src-pytest/pypy/tool/test/test_cache.py Tue Jan 11 15:01:06 2005 @@ -1,8 +1,7 @@ import autopath -import unittest from pypy.tool.cache import Cache -class TestCache(unittest.TestCase): +class TestCache: def test_getorbuild(self): cache = Cache() assert cache.getorbuild(1, lambda k,s: 42, None) == 42 @@ -16,9 +15,6 @@ cache.freeze() hash(cache) assert cache.getorbuild(1, lambda k,s: self.fail(), None) == 44 - self.assertRaises(TypeError, cache.clear) - self.assertRaises(AssertionError, cache.getorbuild, + raises(TypeError, cache.clear) + raises(AssertionError, cache.getorbuild, 2, lambda k,s: self.fail(), 4) - -if __name__ == '__main__': - unittest.main() From hpk at codespeak.net Tue Jan 11 15:02:45 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 15:02:45 +0100 (MET) Subject: [pypy-svn] r8208 - pypy/branch/src-pytest/pypy Message-ID: <20050111140245.E4A2C27BD0@code1.codespeak.net> Author: hpk Date: Tue Jan 11 15:02:45 2005 New Revision: 8208 Modified: pypy/branch/src-pytest/pypy/test_all.py Log: maybe we don't want to run pytests-s recursively. Modified: pypy/branch/src-pytest/pypy/test_all.py ============================================================================== --- pypy/branch/src-pytest/pypy/test_all.py (original) +++ pypy/branch/src-pytest/pypy/test_all.py Tue Jan 11 15:02:45 2005 @@ -1,5 +1,6 @@ #! /usr/bin/env python -import tool.autopath -from py.__impl__.test.cmdline import main -main() +if __name__ == '__main__': + import tool.autopath + from py.__impl__.test.cmdline import main + main() From hpk at codespeak.net Tue Jan 11 15:09:28 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 15:09:28 +0100 (MET) Subject: [pypy-svn] r8209 - pypy/branch/src-pytest/pypy/translator/test Message-ID: <20050111140928.69A2B27BD0@code1.codespeak.net> Author: hpk Date: Tue Jan 11 15:09:28 2005 New Revision: 8209 Modified: pypy/branch/src-pytest/pypy/translator/test/run_snippet.py pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py Log: some fixes to the test conversion Modified: pypy/branch/src-pytest/pypy/translator/test/run_snippet.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/run_snippet.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/run_snippet.py Tue Jan 11 15:09:28 2005 @@ -6,7 +6,6 @@ import autopath import traceback import sys -from pypy.tool import testit from pypy.translator.translator import Translator from pypy.translator.test import snippet Modified: pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_cltrans.py Tue Jan 11 15:09:28 2005 @@ -1,7 +1,6 @@ import autopath from pypy.tool.udir import udir - - +import py import os def get_cl(): @@ -44,8 +43,7 @@ def setup_method(self,method): if not global_cl: - raise (testit.TestSkip, - "Common Lisp neither configured nor detected.") + py.test.skip("Common Lisp neither configured nor detected.") def test_if(self): cl_if = make_cl_func(t.if_then_else) From hpk at codespeak.net Tue Jan 11 15:10:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 15:10:08 +0100 (MET) Subject: [pypy-svn] r8210 - pypy/branch/src-pytest/pypy/interpreter Message-ID: <20050111141008.64CFE27BD0@code1.codespeak.net> Author: hpk Date: Tue Jan 11 15:10:08 2005 New Revision: 8210 Removed: pypy/branch/src-pytest/pypy/interpreter/unittest_w.py Log: fruits! Deleted: /pypy/branch/src-pytest/pypy/interpreter/unittest_w.py ============================================================================== --- /pypy/branch/src-pytest/pypy/interpreter/unittest_w.py Tue Jan 11 15:10:08 2005 +++ (empty file) @@ -1,164 +0,0 @@ -import autopath - -import os -import unittest -from pypy.interpreter import gateway - -try: - f = open(os.path.join(autopath.pypydir, 'ignore_tests.txt')) -except IOError: - IGNORE_TESTS = [] -else: - IGNORE_TESTS = [s.strip() for s in f.readlines()] - f.close() - -def make_testcase_class(space, tc_w): - # XXX this is all a bit insane (but it works) - - # collect the test methods into a dictionary - w = space.wrap - w_dict = space.newdict([]) - for name in dir(AppTestCase): - if ( name.startswith('assert') or name.startswith('fail') - and name != 'failureException'): - fn = gateway.app2interp_temp(getattr(tc_w, name).im_func, name) - space.setitem(w_dict, w(name), w(fn)) - - # space-dependent part: make an object-space-level dictionary - # and use it to build the class. - space.setitem(w_dict, w('failureException'), space.w_AssertionError) - w_tc = space.call_function(space.w_type, - w('TestCase'), - space.newtuple([]), - w_dict) - return space.call_function(w_tc) - - -class WrappedFunc(object): - - def __init__(self, testCase, testMethod): - self.testCase = testCase - self.testMethod = testMethod - - def __call__(self): - space = self.testCase.space - - w_tc_attr = 'tc-attr-hacky-thing' - if hasattr(space, w_tc_attr): - w_tc = getattr(space, w_tc_attr) - else: - w_tc = make_testcase_class(space, self.testCase) - setattr(space, w_tc_attr, w_tc) - - f = self.testMethod.im_func - gway = gateway.app2interp_temp(f, f.func_name) - gway(space, w_tc) - - -class IntTestCase(unittest.TestCase): - """ enrich TestCase with wrapped-methods """ - def __init__(self, methodName='runTest'): - self.methodName = methodName - unittest.TestCase.__init__(self, methodName) - - def _answer(self, result, errorfn): - id = self.id() - for ignored in IGNORE_TESTS: - if id.startswith(ignored): - errorfn = result.addIgnored - errorfn(self, self._TestCase__exc_info()) - - def __call__(self, result=None): - from pypy.tool.testit import TestSkip - if result is None: result = self.defaultTestResult() - result.startTest(self) - testMethod = getattr(self, self.methodName) - try: - try: - self.setUp() - except TestSkip: - result.addSkip(self) - return - except KeyboardInterrupt: - raise - except: - self._answer(result, result.addError) - return - - ok = 0 - try: - testMethod() - ok = 1 - except self.failureException, e: - self._answer(result, result.addFailure) - except TestSkip: - result.addSkip(self) - return - except KeyboardInterrupt: - raise - except: - self._answer(result, result.addError) - - try: - self.tearDown() - except KeyboardInterrupt: - raise - except: - self._answer(result, result.addError) - ok = 0 - if ok: result.addSuccess(self) - finally: - result.stopTest(self) - - - def failUnless_w(self, w_condition, msg=None): - condition = self.space.is_true(w_condition) - return self.failUnless(condition, msg) - - def failIf_w(self, w_condition, msg=None): - condition = self.space.is_true(w_condition) - return self.failIf(condition, msg) - - def assertEqual_w(self, w_first, w_second, msg=None): - w_condition = self.space.eq(w_first, w_second) - condition = self.space.is_true(w_condition) - if msg is None: - msg = '%s != %s'%(w_first, w_second) - return self.failUnless(condition, msg) - - def assertNotEqual_w(self, w_first, w_second, msg=None): - w_condition = self.space.eq(w_first, w_second) - condition = self.space.is_true(w_condition) - if msg is None: - msg = '%s == %s'%(w_first, w_second) - return self.failIf(condition, msg) - - def assertRaises_w(self, w_exc_class, callable, *args, **kw): - from pypy.interpreter.baseobjspace import OperationError - try: - callable(*args, **kw) - except OperationError, e: - self.failUnless(e.match(self.space, w_exc_class)) - else: - self.fail('should have got an exception') - - def assertWRaises_w(self, w_exc_class, w_callable, *args_w, **kw_w): - from pypy.objspace.std.objspace import OperationError - try: - self.space.call_function(w_callable, *args_w, **kw_w) - except OperationError, e: - self.failUnless(e.match(self.space, w_exc_class)) - else: - self.fail('should have got an exception') - - -class AppTestCase(IntTestCase): - def __call__(self, result=None): - if type(getattr(self, self.methodName)) != WrappedFunc: - setattr(self, self.methodName, - WrappedFunc(self, getattr(self, self.methodName))) - return IntTestCase.__call__(self, result) - - def setUp(self): - from pypy.tool import testit - self.space = testit.objspace() From tismer at codespeak.net Tue Jan 11 16:07:34 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 11 Jan 2005 16:07:34 +0100 (MET) Subject: [pypy-svn] r8214 - pypy/trunk/src/pypy/translator Message-ID: <20050111150734.4755727BE4@code1.codespeak.net> Author: tismer Date: Tue Jan 11 16:07:34 2005 New Revision: 8214 Modified: pypy/trunk/src/pypy/translator/genrpy.py Log: added struct.py as a demo. Also some fixes in the type mappings. Still, I cannot create true class instances, there are bugs in the faked wrappers, or when they are used and when not. Modified: pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- pypy/trunk/src/pypy/translator/genrpy.py (original) +++ pypy/trunk/src/pypy/translator/genrpy.py Tue Jan 11 16:07:34 2005 @@ -96,9 +96,7 @@ list.append(self, arg) class GenRpy: - def __init__(self, fname, translator, modname=None, ftmpname=None): - self.fname = fname - self.ftmpname = ftmpname + def __init__(self, translator, modname=None): self.translator = translator self.modname = self.trans_funcname(modname or uniquemodulename(translator.functions[0].__name__)) @@ -131,12 +129,6 @@ #self.space = StdObjSpace() # for introspection self.space = FlowObjSpace() # for introspection - # just for debugging - global _gen; _gen = self - - #self.gen_source() - # opening the class to more parameterisation - self.use_fast_call = False def expr(self, v, localnames, wrapped = True): @@ -187,13 +179,13 @@ fmt = "%s = %s([%s])" else: fmt = "%s = %s(%s)" - # specialc ase is_true + # special case is_true wrapped = op.opname != "is_true" oper = "space.%s" % op.opname return fmt % (self.expr(op.result, localnames, wrapped), oper, self.arglist(op.args, localnames)) - def large_assignment(self,left, right, margin=65): + def large_assignment(self, left, right, margin=65): expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) pieces = expr.split(",") res = [pieces.pop(0)] @@ -205,6 +197,18 @@ res[-1] += (","+piece) return res + def large_initialize(self, vars, margin=65): + res = [] + nonestr = "None" + margin -= len(nonestr) + for var in vars: + ass = var+"=" + if not res or len(res[-1]) >= margin: + res.append(ass) + res[-1] += ass + res = [line + nonestr for line in res] + return res + def gen_link(self, link, localvars, blocknum, block, linklocalvars=None): "Generate the code to jump across the given Link." linklocalvars = linklocalvars or {} @@ -274,7 +278,10 @@ def nameof_object(self, value): if type(value) is not object: - raise Exception, "nameof(%r) in %r" % (value, self.current_func) + #raise Exception, "nameof(%r) in %r" % (value, self.currentfunc) + name = self.uniquename('g_unknown_%r' % value) + self.initcode.append('# cannot build %s as %r' % (name, object)) + return name name = self.uniquename('g_object') self.initcode.append('m.%s = object()'%name) return name @@ -301,9 +308,9 @@ return name def nameof_long(self, value): - # allow short longs only, meaning they - # must fit into a machine word. - assert (sys.maxint*2+1)&value==value, "your literal long is too long" + # allow short longs only, meaning they + # must fit into a machine word. + assert (sys.maxint*2+1)&value==value, "your literal long is too long" # assume we want them in hex most of the time if value < 256L: s = "%dL" % value @@ -344,7 +351,7 @@ # debugging only! Generates a placeholder for missing functions # that raises an exception when called. name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('# global decl %s' % (name, name)) + self.globaldecl.append('# global decl %s' % (name, )) self.initcode.append('# build func %s' % name) return name @@ -391,7 +398,7 @@ typ = self.nameof(meth.im_class) name = self.uniquename('gmeth_'+meth.im_func.__name__) self.initcode.append( - '%s = space.getattr(%s, %s))'%(name, ob, func)) + '%s = space.getattr(%s, %s)'%(name, ob, func)) return name def should_translate_attr(self, pbc, attr): @@ -427,10 +434,10 @@ instance.__class__.__name__, name)) else: # this seems to hardly work with the faked stuff - self.initcode.append('import types\n' - '_ins = space.wrap(types.InstanceType)\n' - '_tup = space.newtuple([%s])\n' - 'm.%s = space.call(_ins, _tup)' % ( + self.initcode.append('from types import InstanceType') + self.initcode.append('w_InstanceType = space.wrap(InstanceType)') + self.initcode.append('_tup = space.newtuple([%s])\n' + 'm.%s = space.call(w_InstanceType, _tup)' % ( cls, name)) self.later(initinstance()) return name @@ -470,12 +477,15 @@ raise Exception, "%r should never be reached" % (cls,) metaclass = "space.w_type" + name = self.uniquename('gcls_' + cls.__name__) if issubclass(cls, Exception): if cls.__module__ == 'exceptions': if hasattr(self.space, "w_%s" % cls.__name__): return 'space.w_%s'%cls.__name__ else: - return 'space.wrap(%s)' % cls.__name__ + self.initcode.append('m.%s = space.wrap(%s)' % ( + name, cls.__name__)) + return name #else: # # exceptions must be old-style classes (grr!) # metaclass = "&PyClass_Type" @@ -483,14 +493,13 @@ # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - self.initcode.append("import types\n" - "m.classtype = space.wrap(types.ClassType)\n") + # self.initcode.append("import types\n" + # "m.classtype = space.wrap(types.ClassType)\n") # metaclass = "m.classtype" # XXX I cannot instantiate these. - # XXX using type instead, since we still inherit from excepetion + # XXX using type instead, since we still inherit from exception # XXX what is the future of classes in pypy? - name = self.uniquename('gcls_' + cls.__name__) basenames = [self.nameof(base) for base in cls.__bases__] def initclassobj(): content = cls.__dict__.items() @@ -568,10 +577,12 @@ # XXX here we get , # while eval gives us type(type.__dict__['__dict__']): 'eval_helper(space,'\ - ' "type(type.__dict__[\'__dict__\']))', + ' "type(type.__dict__[\'__dict__\'])")', # type 'member_descriptor': # XXX this does not work in eval! - type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", + # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", + # XXX there seems to be no working support for member descriptors ??? + type(type.__dict__['__basicsize__']): "space.wrap(type(type.__dict__['__basicsize__']))", } def nameof_type(self, cls): @@ -629,14 +640,17 @@ def nameof_file(self, fil): if fil is sys.stdin: - return '#XXX howto: PySys_GetObject("stdin")' + return 'PySys_GetObject("stdin")' if fil is sys.stdout: - return '#XXX howto: PySys_GetObject("stdout")' + return 'PySys_GetObject("stdout")' if fil is sys.stderr: - return '#XXX howto: PySys_GetObject("stderr")' + return 'PySys_GetObject("stderr")' raise Exception, 'Cannot translate an already-open file: %r' % (fil,) - def gen_source(self): + def gen_source(self, fname, ftmpname=None): + self.fname = fname + self.ftmpname = ftmpname + # generate unordered source file, first. # I prefer this over ordering everything in memory. fname = self.fname @@ -697,7 +711,7 @@ # function implementations while self.pendingfunctions: func = self.pendingfunctions.pop() - self.current_func = func + self.currentfunc = func self.gen_rpyfunction(func) # collect more of the latercode after each function while self.latercode: @@ -780,8 +794,7 @@ fast_set = dict(zip(fast_args, fast_args)) # create function declaration - name = func.__name__ # change this - #args = [self.expr(var, localnames) for var in fast_args] + name = func.__name__ argstr = ", ".join(fast_args) fast_function_header = ('def %s(space, %s):' % (fast_name, argstr)) @@ -810,18 +823,7 @@ return fmt % ', '.join(seq) print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) - # code not used: - fmt = 'O'*min_number_of_args - if min_number_of_args < len(positional_args): - fmt += '|' + 'O'*(len(positional_args)-min_number_of_args) - lst = ['args', 'kwds', - '"%s:%s"' % (fmt, func.__name__), - 'kwlist', - ] - lst += ['&' + a.name for a in positional_args] - #print >> f, '\tif (!PyArg_ParseTupleAndKeywords(%s))' % ', '.join(lst), - print >> f, ' # XXX should parse args here, but no keyword support in gateway' theargs = [arg for arg in fast_args if arg != varname] txt = ('from pypy.translator.genrpy import PyArg_ParseMini\n' 'm.PyArg_ParseMini = PyArg_ParseMini\n' @@ -842,7 +844,11 @@ print >> f, fast_function_header fast_locals = [arg for arg in localnames if arg not in fast_set] - + if fast_locals: + print >> f + for line in self.large_initialize(fast_locals): + print >> f, " %s" % line + print >> f # generate an incref for each input argument # skipped @@ -979,7 +985,7 @@ RPY_INIT_HEADER = RPY_SEP + ''' def init%(modname)s(space): - """NOT RPYTHON""" + """NOT_RPYTHON""" class m: pass # fake module m.__dict__ = globals() ''' @@ -1061,11 +1067,16 @@ def ff(a, b, c=3,*rest): try: - raise SystemError, 42 - return a+b - finally: - a = 7 - return len(rest),c + try: + if rest: + raise SystemError, 42 + return a+b + finally: + a = 7 + if rest: + return len(rest),c + except TypeError: + print "eek" glob = 100 def fff(): @@ -1129,21 +1140,29 @@ return (strutil.string_to_int("42"), strutil.string_to_long("12345678901234567890")) +def test_struct(): + from pypy.appspace import struct + import struct as stru + res1 = stru.pack('f',1.23), struct.pack('f',1.23) + res2 = struct.unpack('f', struct.pack('f',1.23)) + return res1, res2 + def all_entries(): res = [func() for func in entry_points[:-1]] return res entry_points = (lambda: f(2, 3), - lambda: ff(2, 3, 5), - fff, - lambda: app_str_decode__String_ANY_ANY("hugo"), - test_mod, - test_md5, - test_join, - test_iter, - test_strutil, + lambda: ff(2, 3, 5), + fff, + lambda: app_str_decode__String_ANY_ANY("hugo"), + test_mod, + test_md5, + test_join, + test_iter, + test_strutil, + test_struct, all_entries) -entry_point = entry_points[-1] +entry_point = entry_points[-2] if __name__ == "__main__": import os, sys @@ -1154,18 +1173,31 @@ if appdir not in sys.path: sys.path.insert(0, appdir) - fname = "d:/tmp/look.py" t = Translator(entry_point, verbose=False, simplifying=True) - gen = GenRpy(fname, t) - gen.use_fast_call= True - gen.gen_source() + gen = GenRpy(t) + gen.use_fast_call = True import pypy.appspace.generated as tmp pth = os.path.dirname(tmp.__file__) + ftmpname = "d:/tmp/look.py" fname = os.path.join(pth, gen.modname+".py") - file(fname, "w").write(file(fname).read()) + gen.gen_source(fname, ftmpname) #t.simplify() #t.view() # debugging graph = t.getflowgraph() ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab + +def crazy_test(): + """ this thingy is generating the whole interpreter in itself""" + # but doesn't work, my goto's give a problem for flow space + dic = {"__builtins__": __builtins__, "__name__": "__main__"} + execfile("d:/tmp/look.py", dic) + + def test(): + f_ff(space, 2, 3) + test = type(test)(test.func_code, dic) + + t = Translator(test, verbose=False, simplifying=True) + gen = GenRpy(t) + gen.gen_source("d:/tmp/look2.py") From tismer at codespeak.net Tue Jan 11 16:10:40 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 11 Jan 2005 16:10:40 +0100 (MET) Subject: [pypy-svn] r8215 - pypy/trunk/src/pypy/objspace/std Message-ID: <20050111151040.1473F27BF0@code1.codespeak.net> Author: tismer Date: Tue Jan 11 16:10:39 2005 New Revision: 8215 Modified: pypy/trunk/src/pypy/objspace/std/objspace.py Log: I think there are some inconsistencies. At least, with commenting complex out, it seems to produce better results. Still, the result of space.eval("1j", dic, dic) cannot be unwrapped. Modified: pypy/trunk/src/pypy/objspace/std/objspace.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/objspace.py (original) +++ pypy/trunk/src/pypy/objspace/std/objspace.py Tue Jan 11 16:10:39 2005 @@ -243,15 +243,15 @@ return W_ListObject(self, wrappeditems) if isinstance(x, long): return W_LongObject(self, x) - if isinstance(x, complex): - # XXX is this right? - c = self.getitem(self.w_builtins, self.wrap("complex")) - return self.call_function(c, - self.wrap(x.real), - self.wrap(x.imag)) +## if isinstance(x, complex): +## # XXX is this right? YYY no, this is wrong right now (CT) +## c = self.getitem(self.w_builtins, self.wrap("complex")) +## return self.call_function(c, +## self.wrap(x.real), +## self.wrap(x.imag)) if isinstance(x, BaseWrappable): w_result = x.__spacebind__(self) - #print 'wrapping', x, '->', w_result + print 'wrapping', x, '->', w_result #XXX return w_result # anything below this line is implicitly XXX'ed if isinstance(x, type(Exception)) and issubclass(x, Exception): From tismer at codespeak.net Tue Jan 11 16:54:50 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 11 Jan 2005 16:54:50 +0100 (MET) Subject: [pypy-svn] r8216 - pypy/trunk/src/pypy/objspace/std Message-ID: <20050111155450.2E60627BF7@code1.codespeak.net> Author: tismer Date: Tue Jan 11 16:54:50 2005 New Revision: 8216 Modified: pypy/trunk/src/pypy/objspace/std/objspace.py Log: oops, forgot to undo an uncomment... Modified: pypy/trunk/src/pypy/objspace/std/objspace.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/objspace.py (original) +++ pypy/trunk/src/pypy/objspace/std/objspace.py Tue Jan 11 16:54:50 2005 @@ -251,7 +251,7 @@ ## self.wrap(x.imag)) if isinstance(x, BaseWrappable): w_result = x.__spacebind__(self) - print 'wrapping', x, '->', w_result #XXX + #print 'wrapping', x, '->', w_result return w_result # anything below this line is implicitly XXX'ed if isinstance(x, type(Exception)) and issubclass(x, Exception): From arigo at codespeak.net Tue Jan 11 17:25:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 11 Jan 2005 17:25:09 +0100 (MET) Subject: [pypy-svn] r8217 - in pypy/trunk/src/pypy: interpreter objspace/flow Message-ID: <20050111162509.790CE27BF6@code1.codespeak.net> Author: arigo Date: Tue Jan 11 17:25:09 2005 New Revision: 8217 Modified: pypy/trunk/src/pypy/interpreter/error.py pypy/trunk/src/pypy/interpreter/pyopcode.py pypy/trunk/src/pypy/objspace/flow/model.py pypy/trunk/src/pypy/objspace/flow/objspace.py Log: Moved the hacks for the flowobjspace out of pyopcode.py and into OperationError.__init__(). The flow objspace now provides a w_NameError and a UnboundLocalError, both None. Modified: pypy/trunk/src/pypy/interpreter/error.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/error.py (original) +++ pypy/trunk/src/pypy/interpreter/error.py Tue Jan 11 17:25:09 2005 @@ -21,6 +21,7 @@ """ def __init__(self, w_type, w_value, tb=None): + assert w_type is not None, w_value self.w_type = w_type self.w_value = w_value self.application_traceback = tb Modified: pypy/trunk/src/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/pyopcode.py (original) +++ pypy/trunk/src/pypy/interpreter/pyopcode.py Tue Jan 11 17:25:09 2005 @@ -91,14 +91,7 @@ if w_value is UNDEFINED: varname = f.getlocalvarname(varindex) message = "local variable '%s' referenced before assignment" % varname - try: - w_exc_type = f.space.w_UnboundLocalError - w_exc_value = f.space.wrap(message) - except AttributeError: - # object space does not support it, so crash really - raise UnboundLocalError, (message + - ", but %s has no UnboundLocalError!" % f.space) - raise OperationError(w_exc_type, w_exc_value) + raise OperationError(f.space.w_UnboundLocalError, f.space.wrap(message)) f.valuestack.push(w_value) def LOAD_CONST(f, constindex): @@ -532,13 +525,8 @@ if not e.match(f.space, f.space.w_KeyError): raise message = "global name '%s' is not defined" % varname - try: - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) - except AttributeError: - # object space does not support it, so crash really - raise NameError, (message + - ", but %s has no NameError!" % f.space) + w_exc_type = f.space.w_NameError + w_exc_value = f.space.wrap(message) raise OperationError(w_exc_type, w_exc_value) f.valuestack.push(w_value) Modified: pypy/trunk/src/pypy/objspace/flow/model.py ============================================================================== --- pypy/trunk/src/pypy/objspace/flow/model.py (original) +++ pypy/trunk/src/pypy/objspace/flow/model.py Tue Jan 11 17:25:09 2005 @@ -153,7 +153,7 @@ if (r.startswith('<') and r.endswith('>') and hasattr(self.value, '__name__')): r = '%s %s' % (type(self.value).__name__, self.value.__name__) - elif len(r) > 30: + elif len(r) > 60 or (len(r) > 30 and type(self.value) is not str): r = r[:20] + '...' + r[-8:] return '(%s)' % r Modified: pypy/trunk/src/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/trunk/src/pypy/objspace/flow/objspace.py (original) +++ pypy/trunk/src/pypy/objspace/flow/objspace.py Tue Jan 11 17:25:09 2005 @@ -34,6 +34,12 @@ AssertionError]: clsname = exc.__name__ setattr(self, 'w_'+clsname, Constant(exc)) + # the following exceptions are the ones that should not show up + # during flow graph construction; they are triggered by + # non-R-Pythonic constructs or real bugs like typos. + for exc in [NameError, UnboundLocalError]: + clsname = exc.__name__ + setattr(self, 'w_'+clsname, None) self.specialcases = {} #self.make_builtins() #self.make_sys() From arigo at codespeak.net Tue Jan 11 17:32:49 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 11 Jan 2005 17:32:49 +0100 (MET) Subject: [pypy-svn] r8219 - pypy/trunk/src/pypy/translator Message-ID: <20050111163249.D9F9E27BF6@code1.codespeak.net> Author: arigo Date: Tue Jan 11 17:32:49 2005 New Revision: 8219 Modified: pypy/trunk/src/pypy/translator/gencl.py Log: Adrien Di Mascio's bug report on pypy-dev. Modified: pypy/trunk/src/pypy/translator/gencl.py ============================================================================== --- pypy/trunk/src/pypy/translator/gencl.py (original) +++ pypy/trunk/src/pypy/translator/gencl.py Tue Jan 11 17:32:49 2005 @@ -193,7 +193,7 @@ return "'last-exc-value" else: return "#<%r>" % (val,) - def emitcode(self): + def emitcode(self, public=True): import sys from cStringIO import StringIO out = StringIO() From hpk at codespeak.net Tue Jan 11 18:10:37 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 18:10:37 +0100 (MET) Subject: [pypy-svn] r8220 - pypy/branch/src-pytest/pypy/interpreter/test Message-ID: <20050111171037.29C3327C00@code1.codespeak.net> Author: hpk Date: Tue Jan 11 18:10:36 2005 New Revision: 8220 Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_main.py Log: read file with universal readline (fixes bug on win) and use asserts more directly. Modified: pypy/branch/src-pytest/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/test/test_main.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/test/test_main.py Tue Jan 11 18:10:36 2005 @@ -27,7 +27,7 @@ finally: space.setattr(w_sys, space.wrap("stdout"), w_oldout) capturefile.close() - return capturefn.read() == expected_output + assert capturefn.read(mode='rU') == expected_output testfn = 'tmp_hello_world.py' @@ -43,10 +43,10 @@ os.remove(testfn) def test_run_file(self): - assert checkoutput(self.space, testresultoutput,main.run_file,testfn) + checkoutput(self.space, testresultoutput,main.run_file,testfn) def test_run_string(self): - assert checkoutput(self.space, testresultoutput, + checkoutput(self.space, testresultoutput, main.run_string,testcode,testfn) def test_eval_string(self): From hpk at codespeak.net Tue Jan 11 18:33:15 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 18:33:15 +0100 (MET) Subject: [pypy-svn] r8222 - pypy/branch/src-pytest/pypy/appspace/test Message-ID: <20050111173315.1984E27C00@code1.codespeak.net> Author: hpk Date: Tue Jan 11 18:33:14 2005 New Revision: 8222 Modified: pypy/branch/src-pytest/pypy/appspace/test/test_sio.py Log: fixed a wrongly converted test Modified: pypy/branch/src-pytest/pypy/appspace/test/test_sio.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/test/test_sio.py (original) +++ pypy/branch/src-pytest/pypy/appspace/test/test_sio.py Tue Jan 11 18:33:14 2005 @@ -475,11 +475,10 @@ blocks.append(block) assert blocks == expected -class TestMMapFile: - +class TestMMapFile(TestBufferingInputStreamTests): tfn = None - def tearDown(self): + def teardown_method(self, method): tfn = self.tfn if tfn: self.tfn = None From hpk at codespeak.net Tue Jan 11 18:52:42 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 11 Jan 2005 18:52:42 +0100 (MET) Subject: [pypy-svn] r8223 - in pypy/branch/src-pytest/pypy: . tool Message-ID: <20050111175242.66F0F27C00@code1.codespeak.net> Author: hpk Date: Tue Jan 11 18:52:42 2005 New Revision: 8223 Added: pypy/branch/src-pytest/pypy/tool/example_pytest.py - copied unchanged from r8203, pypy/branch/src-pytest/pypy/example_pytest.py Removed: pypy/branch/src-pytest/pypy/example_pytest.py Log: moved the example-file for common pypy test failures out the way. Deleted: /pypy/branch/src-pytest/pypy/example_pytest.py ============================================================================== --- /pypy/branch/src-pytest/pypy/example_pytest.py Tue Jan 11 18:52:42 2005 +++ (empty file) @@ -1,14 +0,0 @@ -class AppTestTest: - def test_app_method(self): - assert 42 == 41 - -def app_test_app_func(): - assert 41 == 42 - -def test_interp_func(space): - assert space.is_true(space.w_None) - -class TestInterpTest: - def test_interp_method(self): - assert self.space.is_true(self.space.w_False) - From tismer at codespeak.net Tue Jan 11 20:11:41 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 11 Jan 2005 20:11:41 +0100 (MET) Subject: [pypy-svn] r8224 - pypy/trunk/src/pypy/translator Message-ID: <20050111191141.BF1B027C12@code1.codespeak.net> Author: tismer Date: Tue Jan 11 20:11:41 2005 New Revision: 8224 Added: pypy/trunk/src/pypy/translator/geninterplevel.py - copied unchanged from r8214, pypy/trunk/src/pypy/translator/genrpy.py Log: renamed genrpy.py to geninterplevel.py From pedronis at codespeak.net Wed Jan 12 11:15:26 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 12 Jan 2005 11:15:26 +0100 (MET) Subject: [pypy-svn] r8225 - pypy/trunk/src/pypy/objspace/std Message-ID: <20050112101526.9052827BEC@code1.codespeak.net> Author: pedronis Date: Wed Jan 12 11:15:26 2005 New Revision: 8225 Modified: pypy/trunk/src/pypy/objspace/std/longobject.py Log: now both these cases works: PyPy in StdObjSpace on top of Python 2.3.4 >>>> [0,1][1L] 1 >>>> 2**31+1.0 2147483649.0 >>>> the problem was shallow, the MM mechanics as they stand are likely still disorienting nevertheless. Modified: pypy/trunk/src/pypy/objspace/std/longobject.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/longobject.py (original) +++ pypy/trunk/src/pypy/objspace/std/longobject.py Wed Jan 12 11:15:26 2005 @@ -19,29 +19,6 @@ registerimplementation(W_LongObject) -# int-to-long delegation -def delegate__Int(space, w_intobj): - return W_LongObject(space, long(w_intobj.intval)) -delegate__Int.result_class = W_LongObject -delegate__Int.priority = PRIORITY_CHANGE_TYPE - -# long-to-int delegation -def delegate__Long(space, w_longobj): - if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: - return W_IntObject(space, int(w_longobj.longval)) - else: - # note the 'return' here -- hack - return FailedToImplement(space.w_OverflowError, - space.wrap("long int too large to convert to int")) -delegate__Long.result_class = W_IntObject -delegate__Long.priority = PRIORITY_CHANGE_TYPE -delegate__Long.can_fail = True - -## # long-to-float delegation -## def delegate__Long(space, w_longobj): -## return W_FloatObject(space, float(w_longobj.longval)) -## delegate__Long.result_class = W_FloatObject -## delegate__Long.priority = PRIORITY_CHANGE_TYPE # long__Long is supposed to do nothing, unless it has # a derived long object, where it should return @@ -224,3 +201,36 @@ register_all(vars()) + +# delegations must be registered manually because we have more than one +# long-to-something delegation + +# int-to-long delegation +def delegate_from_int(space, w_intobj): + return W_LongObject(space, long(w_intobj.intval)) +delegate_from_int.result_class = W_LongObject +delegate_from_int.priority = PRIORITY_CHANGE_TYPE + +StdObjSpace.delegate.register(delegate_from_int, W_IntObject) + +# long-to-int delegation +def delegate_to_int(space, w_longobj): + if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: + return W_IntObject(space, int(w_longobj.longval)) + else: + # note the 'return' here -- hack + return FailedToImplement(space.w_OverflowError, + space.wrap("long int too large to convert to int")) +delegate_to_int.result_class = W_IntObject +delegate_to_int.priority = PRIORITY_CHANGE_TYPE +delegate_to_int.can_fail = True + +StdObjSpace.delegate.register(delegate_to_int, W_LongObject) + +# long-to-float delegation +def delegate_to_float(space, w_longobj): + return W_FloatObject(space, float(w_longobj.longval)) +delegate_to_float.result_class = W_FloatObject +delegate_to_float.priority = PRIORITY_CHANGE_TYPE + +StdObjSpace.delegate.register(delegate_to_float, W_LongObject) From pedronis at codespeak.net Wed Jan 12 15:31:13 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 12 Jan 2005 15:31:13 +0100 (MET) Subject: [pypy-svn] r8227 - in pypy/branch/src-pytest/pypy: appspace interpreter objspace/flow objspace/std tool translator translator/java translator/java/test translator/test translator/tool Message-ID: <20050112143113.ECE2727BDB@code1.codespeak.net> Author: pedronis Date: Wed Jan 12 15:31:13 2005 New Revision: 8227 Added: pypy/branch/src-pytest/pypy/appspace/struct.py - copied unchanged from r8225, pypy/trunk/src/pypy/appspace/struct.py pypy/branch/src-pytest/pypy/translator/geninterplevel.py (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/geninterplevel.py pypy/branch/src-pytest/pypy/translator/java/ (props changed) - copied from r8225, pypy/trunk/src/pypy/translator/java/ pypy/branch/src-pytest/pypy/translator/java/PyBool.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PyBool.java pypy/branch/src-pytest/pypy/translator/java/PyInt.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PyInt.java pypy/branch/src-pytest/pypy/translator/java/PyList.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PyList.java pypy/branch/src-pytest/pypy/translator/java/PyObject.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PyObject.java pypy/branch/src-pytest/pypy/translator/java/PySequence.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PySequence.java pypy/branch/src-pytest/pypy/translator/java/PyTuple.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/PyTuple.java pypy/branch/src-pytest/pypy/translator/java/TypeError.java (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/TypeError.java pypy/branch/src-pytest/pypy/translator/java/__init__.py (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/__init__.py pypy/branch/src-pytest/pypy/translator/java/autopath.py (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/autopath.py pypy/branch/src-pytest/pypy/translator/java/genjava.py (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/genjava.py pypy/branch/src-pytest/pypy/translator/java/test/ (props changed) - copied from r8225, pypy/trunk/src/pypy/translator/java/test/ pypy/branch/src-pytest/pypy/translator/java/test/__init__.py - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/test/__init__.py pypy/branch/src-pytest/pypy/translator/java/test/autopath.py (props changed) - copied unchanged from r8225, pypy/trunk/src/pypy/translator/java/test/autopath.py pypy/branch/src-pytest/pypy/translator/java/test/test_javatrans.py (contents, props changed) - copied, changed from r8225, pypy/trunk/src/pypy/translator/java/test/test_javatrans.py Modified: pypy/branch/src-pytest/pypy/appspace/_formatting.py pypy/branch/src-pytest/pypy/appspace/md5.py pypy/branch/src-pytest/pypy/interpreter/error.py pypy/branch/src-pytest/pypy/objspace/flow/model.py pypy/branch/src-pytest/pypy/objspace/flow/objspace.py pypy/branch/src-pytest/pypy/objspace/std/longobject.py pypy/branch/src-pytest/pypy/objspace/std/objspace.py pypy/branch/src-pytest/pypy/tool/hack.py pypy/branch/src-pytest/pypy/translator/genc.h pypy/branch/src-pytest/pypy/translator/genc.py pypy/branch/src-pytest/pypy/translator/gencl.py pypy/branch/src-pytest/pypy/translator/genrpy.py pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py Log: merged changes happened on the head into src-pytest branch Modified: pypy/branch/src-pytest/pypy/appspace/_formatting.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/_formatting.py (original) +++ pypy/branch/src-pytest/pypy/appspace/_formatting.py Wed Jan 12 15:31:13 2005 @@ -225,7 +225,7 @@ class FloatFFormatter(FloatFormatter): def _format(self, v): if v/1e25 > 1e25: - return floatGFormatter('g', self.flags, self.width, + return FloatGFormatter('g', self.flags, self.width, self.prec, self.value).format() ds, k = flonum2digits(v) digits = self.fDigits(ds, k) Modified: pypy/branch/src-pytest/pypy/appspace/md5.py ============================================================================== --- pypy/branch/src-pytest/pypy/appspace/md5.py (original) +++ pypy/branch/src-pytest/pypy/appspace/md5.py Wed Jan 12 15:31:13 2005 @@ -32,6 +32,7 @@ __date__ = '2004-11-17' __version__ = 0.91 # Modernised by J. Hall?n and L. Creighton for Pypy +__metaclass__ = type # or genrpy won't work import struct, copy Modified: pypy/branch/src-pytest/pypy/interpreter/error.py ============================================================================== --- pypy/branch/src-pytest/pypy/interpreter/error.py (original) +++ pypy/branch/src-pytest/pypy/interpreter/error.py Wed Jan 12 15:31:13 2005 @@ -21,6 +21,7 @@ """ def __init__(self, w_type, w_value, tb=None): + assert w_type is not None, w_value self.w_type = w_type self.w_value = w_value self.application_traceback = tb Modified: pypy/branch/src-pytest/pypy/objspace/flow/model.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/flow/model.py (original) +++ pypy/branch/src-pytest/pypy/objspace/flow/model.py Wed Jan 12 15:31:13 2005 @@ -153,7 +153,7 @@ if (r.startswith('<') and r.endswith('>') and hasattr(self.value, '__name__')): r = '%s %s' % (type(self.value).__name__, self.value.__name__) - elif len(r) > 30: + elif len(r) > 60 or (len(r) > 30 and type(self.value) is not str): r = r[:20] + '...' + r[-8:] return '(%s)' % r Modified: pypy/branch/src-pytest/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-pytest/pypy/objspace/flow/objspace.py Wed Jan 12 15:31:13 2005 @@ -34,6 +34,12 @@ AssertionError]: clsname = exc.__name__ setattr(self, 'w_'+clsname, Constant(exc)) + # the following exceptions are the ones that should not show up + # during flow graph construction; they are triggered by + # non-R-Pythonic constructs or real bugs like typos. + for exc in [NameError, UnboundLocalError]: + clsname = exc.__name__ + setattr(self, 'w_'+clsname, None) self.specialcases = {} #self.make_builtins() #self.make_sys() Modified: pypy/branch/src-pytest/pypy/objspace/std/longobject.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/longobject.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/longobject.py Wed Jan 12 15:31:13 2005 @@ -19,29 +19,6 @@ registerimplementation(W_LongObject) -# int-to-long delegation -def delegate__Int(space, w_intobj): - return W_LongObject(space, long(w_intobj.intval)) -delegate__Int.result_class = W_LongObject -delegate__Int.priority = PRIORITY_CHANGE_TYPE - -# long-to-int delegation -def delegate__Long(space, w_longobj): - if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: - return W_IntObject(space, int(w_longobj.longval)) - else: - # note the 'return' here -- hack - return FailedToImplement(space.w_OverflowError, - space.wrap("long int too large to convert to int")) -delegate__Long.result_class = W_IntObject -delegate__Long.priority = PRIORITY_CHANGE_TYPE -delegate__Long.can_fail = True - -## # long-to-float delegation -## def delegate__Long(space, w_longobj): -## return W_FloatObject(space, float(w_longobj.longval)) -## delegate__Long.result_class = W_FloatObject -## delegate__Long.priority = PRIORITY_CHANGE_TYPE # long__Long is supposed to do nothing, unless it has # a derived long object, where it should return @@ -224,3 +201,36 @@ register_all(vars()) + +# delegations must be registered manually because we have more than one +# long-to-something delegation + +# int-to-long delegation +def delegate_from_int(space, w_intobj): + return W_LongObject(space, long(w_intobj.intval)) +delegate_from_int.result_class = W_LongObject +delegate_from_int.priority = PRIORITY_CHANGE_TYPE + +StdObjSpace.delegate.register(delegate_from_int, W_IntObject) + +# long-to-int delegation +def delegate_to_int(space, w_longobj): + if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: + return W_IntObject(space, int(w_longobj.longval)) + else: + # note the 'return' here -- hack + return FailedToImplement(space.w_OverflowError, + space.wrap("long int too large to convert to int")) +delegate_to_int.result_class = W_IntObject +delegate_to_int.priority = PRIORITY_CHANGE_TYPE +delegate_to_int.can_fail = True + +StdObjSpace.delegate.register(delegate_to_int, W_LongObject) + +# long-to-float delegation +def delegate_to_float(space, w_longobj): + return W_FloatObject(space, float(w_longobj.longval)) +delegate_to_float.result_class = W_FloatObject +delegate_to_float.priority = PRIORITY_CHANGE_TYPE + +StdObjSpace.delegate.register(delegate_to_float, W_LongObject) Modified: pypy/branch/src-pytest/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/src-pytest/pypy/objspace/std/objspace.py (original) +++ pypy/branch/src-pytest/pypy/objspace/std/objspace.py Wed Jan 12 15:31:13 2005 @@ -243,12 +243,12 @@ return W_ListObject(self, wrappeditems) if isinstance(x, long): return W_LongObject(self, x) - if isinstance(x, complex): - # XXX is this right? - c = self.getitem(self.w_builtins, self.wrap("complex")) - return self.call_function(c, - self.wrap(x.real), - self.wrap(x.imag)) +## if isinstance(x, complex): +## # XXX is this right? YYY no, this is wrong right now (CT) +## c = self.getitem(self.w_builtins, self.wrap("complex")) +## return self.call_function(c, +## self.wrap(x.real), +## self.wrap(x.imag)) if isinstance(x, BaseWrappable): w_result = x.__spacebind__(self) #print 'wrapping', x, '->', w_result Modified: pypy/branch/src-pytest/pypy/tool/hack.py ============================================================================== --- pypy/branch/src-pytest/pypy/tool/hack.py (original) +++ pypy/branch/src-pytest/pypy/tool/hack.py Wed Jan 12 15:31:13 2005 @@ -2,7 +2,7 @@ import new, sys -if sys.version_info > (2, 2): +if sys.version_info >= (2, 3): def func_with_new_name(func, newname): f = new.function(func.func_code, func.func_globals, Modified: pypy/branch/src-pytest/pypy/translator/genc.h ============================================================================== --- pypy/branch/src-pytest/pypy/translator/genc.h (original) +++ pypy/branch/src-pytest/pypy/translator/genc.h Wed Jan 12 15:31:13 2005 @@ -199,6 +199,11 @@ #if defined(USE_CALL_TRACE) +#define TRACE_CALL __f, __tstate, +#define TRACE_ARGS PyFrameObject *__f, PyThreadState *__tstate, +#define TRACE_CALL_VOID __f, __tstate +#define TRACE_ARGS_VOID PyFrameObject *__f, PyThreadState *__tstate + #define FAIL(err) { __f->f_lineno = __f->f_code->co_firstlineno = __LINE__; goto err; } #define FUNCTION_HEAD(signature, self, args, names, file, line) \ @@ -215,6 +220,11 @@ #else /* !defined(USE_CALL_TRACE) */ +#define TRACE_CALL /* nothing */ +#define TRACE_ARGS /* nothing */ +#define TRACE_CALL_VOID /* nothing */ +#define TRACE_ARGS_VOID void + #define FAIL(err) { goto err; } #define FUNCTION_HEAD(signature, self, args, names, file, line) Modified: pypy/branch/src-pytest/pypy/translator/genc.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/genc.py (original) +++ pypy/branch/src-pytest/pypy/translator/genc.py Wed Jan 12 15:31:13 2005 @@ -38,8 +38,6 @@ class GenC: MODNAMES = {} - # XXX - I don't know how to make a macro do this.. so.. - USE_CALL_TRACE = True def __init__(self, f, translator, modname=None, f2=None, f2name=None): self.f = f @@ -454,8 +452,6 @@ 'entrypoint': self.nameof(self.translator.functions[0]), } # header - if self.USE_CALL_TRACE: - print >> f, '#define USE_CALL_TRACE' print >> f, self.C_HEADER # function implementations @@ -510,9 +506,9 @@ self.gen_global_declarations() # print header - name = self.nameof(func) - assert name.startswith('gfunc_') - f_name = 'f_' + name[6:] + cname = self.nameof(func) + assert cname.startswith('gfunc_') + f_name = 'f_' + cname[6:] # collect all the local variables graph = self.translator.getflowgraph(func) @@ -540,22 +536,31 @@ fast_set = dict(zip(fast_args, fast_args)) declare_fast_args = [('PyObject *' + a) for a in fast_args] - if self.USE_CALL_TRACE: - declare_fast_args[:0] = ['PyFrameObject *__f', 'PyThreadState *__tstate'] + if declare_fast_args: + declare_fast_args = 'TRACE_ARGS ' + ', '.join(declare_fast_args) + else: + declare_fast_args = 'TRACE_ARGS_VOID' + fast_function_header = ('static PyObject *\n' + '%s(%s)' % (fast_name, declare_fast_args)) - print >> f, 'static PyObject *' - print >> f, '%s(%s);' % (fast_name, ', '.join(declare_fast_args)) + print >> f, fast_function_header + ';' # forward print >> f print >> f, 'static PyObject *' - print >> f, '%s(PyObject* self, PyObject* args)' % (f_name,) + print >> f, '%s(PyObject* self, PyObject* args, PyObject* kwds)' % ( + f_name,) print >> f, '{' print >> f, '\tFUNCTION_HEAD(%s, %s, args, %s, __FILE__, __LINE__ - 2)' % ( - c_string('%s(%s)' % (name, ', '.join(name_of_defaults))), - name, + c_string('%s(%s)' % (cname, ', '.join(name_of_defaults))), + cname, '(%s)' % (', '.join(map(c_string, name_of_defaults) + ['NULL']),), ) + kwlist = ['"%s"' % name for name in + func.func_code.co_varnames[:func.func_code.co_argcount]] + kwlist.append('0') + print >> f, '\tstatic char* kwlist[] = {%s};' % (', '.join(kwlist),) + if fast_args: print >> f, '\tPyObject *%s;' % (', *'.join(fast_args)) print >> f @@ -586,24 +591,27 @@ print >> f, '\t%s = %s;' % ( positional_args[min_number_of_args+i], name_of_defaults[i]) - lst = ['args', - '"%s"' % func.__name__, - '%d' % min_number_of_args, - '%d' % len(positional_args), + fmt = 'O'*min_number_of_args + if min_number_of_args < len(positional_args): + fmt += '|' + 'O'*(len(positional_args)-min_number_of_args) + lst = ['args', 'kwds', + '"%s:%s"' % (fmt, func.__name__), + 'kwlist', ] lst += ['&' + a.name for a in positional_args] - print >> f, '\tif (!PyArg_UnpackTuple(%s))' % ', '.join(lst), + print >> f, '\tif (!PyArg_ParseTupleAndKeywords(%s))' % ', '.join(lst), print >> f, tail call_fast_args = list(fast_args) - if self.USE_CALL_TRACE: - call_fast_args[:0] = ['__f', '__tstate'] - print >> f, '\treturn %s(%s);' % (fast_name, ', '.join(call_fast_args)) + if call_fast_args: + call_fast_args = 'TRACE_CALL ' + ', '.join(call_fast_args) + else: + call_fast_args = 'TRACE_CALL_VOID' + print >> f, '\treturn %s(%s);' % (fast_name, call_fast_args) print >> f, '}' print >> f - print >> f, 'static PyObject *' - print >> f, '%s(%s)' % (fast_name, ', '.join(declare_fast_args)) + print >> f, fast_function_header print >> f, '{' fast_locals = [arg for arg in localnames if arg not in fast_set] @@ -630,8 +638,9 @@ print >> f, '}' # print the PyMethodDef - print >> f, 'static PyMethodDef ml_%s = { "%s", %s, METH_VARARGS };' % ( - name, func.__name__, f_name) + print >> f, ('static PyMethodDef ml_%s = {\n' + ' "%s", (PyCFunction)%s, METH_VARARGS|METH_KEYWORDS };' % ( + cname, func.__name__, f_name)) print >> f if not self.translator.frozen: Modified: pypy/branch/src-pytest/pypy/translator/gencl.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/gencl.py (original) +++ pypy/branch/src-pytest/pypy/translator/gencl.py Wed Jan 12 15:31:13 2005 @@ -193,7 +193,7 @@ return "'last-exc-value" else: return "#<%r>" % (val,) - def emitcode(self): + def emitcode(self, public=True): import sys from cStringIO import StringIO out = StringIO() Modified: pypy/branch/src-pytest/pypy/translator/genrpy.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/genrpy.py (original) +++ pypy/branch/src-pytest/pypy/translator/genrpy.py Wed Jan 12 15:31:13 2005 @@ -10,22 +10,53 @@ that globals are constants, for instance. This definition is not exact and might change. -This module is very much under construction and not yet usable for much -more than testing. +This module appears to be already quite usable. +But I need to ask how we want to integrate it. + +XXX open questions: +- do we wantamoduleperapp-spaceoperation? +- do we want to auto-generate stuff? +- do we want to create code that is more similar to the app code? +- do we want to create specialized code for constants? +- do we want to use small tail-functions instead of goto? +- do we want to inline small functions? +- do we want to translate non-rpythonic code as well? """ -from pypy.objspace.flow.model import traverse -from pypy.objspace.flow import FlowObjSpace -from pypy.objspace.flow.model import FunctionGraph, Block, Link, Variable, Constant +from __future__ import generators +import autopath, os, sys, exceptions +from pypy.objspace.flow.model import Variable, Constant, SpaceOperation +from pypy.objspace.flow.model import FunctionGraph, Block, Link from pypy.objspace.flow.model import last_exception, last_exc_value -from pypy.translator.simplify import simplify_graph +from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph +from pypy.translator.simplify import remove_direct_loops +from pypy.interpreter.pycode import CO_VARARGS +from pypy.annotation import model as annmodel +from types import FunctionType, CodeType from pypy.interpreter.error import OperationError -from types import FunctionType +from pypy.objspace.std.restricted_int import r_int, r_uint from pypy.translator.translator import Translator +from pypy.objspace.std import StdObjSpace +from pypy.objspace.flow import FlowObjSpace + +from pypy.interpreter.gateway import app2interp, interp2app + -import sys +# ____________________________________________________________ +def c_string(s): + return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\"'),) + +def uniquemodulename(name, SEEN={}): + # never reuse the same module name within a Python session! + i = 0 + while True: + i += 1 + result = '%s_%d' % (name, i) + if result not in SEEN: + SEEN[result] = True + return result def ordered_blocks(graph): # collect all blocks @@ -49,65 +80,167 @@ # print ofs, txt, block return [block for ofs, txt, block in allblocks] +class UniqueList(list): + def __init__(self, *args, **kwds): + list.__init__(self, *args, **kwds) + self.dic = {} + def append(self, arg): + try: + self.dic[arg] + except KeyError: + self.dic[arg] = 1 + list.append(self, arg) + except TypeError: # not hashable + if arg not in self: + list.append(self, arg) + class GenRpy: - def __init__(self, f, translator, modname=None): - self.f = f + def __init__(self, translator, modname=None): self.translator = translator - self.modname = (modname or - translator.functions[0].__name__) - self.rpynames = {Constant(None).key: 'w(None)', - Constant(False).key: 'w(False)', - Constant(True).key: 'w(True)', + self.modname = self.trans_funcname(modname or + uniquemodulename(translator.functions[0].__name__)) + self.rpynames = {Constant(None).key: 'space.w_None', + Constant(False).key: 'space.w_False', + Constant(True).key: 'space.w_True', } self.seennames = {} - self.initcode = [] # list of lines for the module's initxxx() - self.latercode = [] # list of generators generating extra lines + u = UniqueList + self.initcode = u() # list of lines for the module's initxxx() + self.latercode = u() # list of generators generating extra lines # for later in initxxx() -- for recursive # objects self.globaldecl = [] self.globalobjects = [] self.pendingfunctions = [] + self.currentfunc = None + self.debugstack = () # linked list of nested nameof() # special constructors: self.has_listarg = {} for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - self.current_globals = {} - self.glob_names = [] - self.glob_values = [] - - self.gen_source() - - def adjust_namespace(self): - """ inspect the globals of self.current_func and build a searchable list - of the globals. - """ - g = self.current_func.func_globals - if g is self.current_globals: - return - self.current_globals = g - order = [(value, key) for key, value in g.items()] - order.sort() - self.glob_names = [key for value, key in order] - self.glob_values = [value for value, key in order] - - def find_global_name(self, obj): - for i in xrange(len(self.glob_values)): - if self.glob_values[i] is obj: - return self.glob_names[i] - return None + # XXX I guess it is cleaner to use the flow space? + # we just want to look into the operations, + # but we don't break into the implementation. + # Or should it be the base space, ARMIN? + #self.space = StdObjSpace() # for introspection + self.space = FlowObjSpace() # for introspection - def nameof(self, obj): + self.use_fast_call = False + + def expr(self, v, localnames, wrapped = True): + if isinstance(v, Variable): + n = v.name + if n.startswith("v") and n[1:].isdigit(): + ret = localnames.get(v.name) + if not ret: + if wrapped: + localnames[v.name] = ret = "w_%d" % len(localnames) + else: + localnames[v.name] = ret = "v%d" % len(localnames) + return ret + elif isinstance(v, Constant): + return self.nameof(v.value, + debug=('Constant in the graph of', self.currentfunc)) + else: + raise TypeError, "expr(%r)" % (v,) + + def arglist(self, args, localnames): + res = [self.expr(arg, localnames) for arg in args] + return ", ".join(res) + + def oper(self, op, localnames): + if op.opname == "simple_call": + v = op.args[0] + exv = self.expr(v, localnames) + if exv.startswith("space.") and not exv.startswith("space.w_"): + # it is a space method + fmt = "%(res)s = %(func)s(%(args)s)" + else: + # default for a spacecall: + fmt = ("_tup = space.newtuple([%(args)s])\n" + "%(res)s = space.call(%(func)s, _tup)") + # see if we can optimize for a fast call. + # we justdo the very simple ones. + if self.use_fast_call and (isinstance(v, Constant) + and exv.startswith('gfunc_')): + func = v.value + if (not func.func_code.co_flags & CO_VARARGS) and ( + func.func_defaults is None): + fmt = "%(res)s = fastf_%(func)s(space, %(args)s)" + exv = exv[6:] + return fmt % {"res" : self.expr(op.result, localnames), + "func": exv, + "args": self.arglist(op.args[1:], localnames) } + if op.opname in self.has_listarg: + fmt = "%s = %s([%s])" + else: + fmt = "%s = %s(%s)" + # special case is_true + wrapped = op.opname != "is_true" + oper = "space.%s" % op.opname + return fmt % (self.expr(op.result, localnames, wrapped), oper, + self.arglist(op.args, localnames)) + + def large_assignment(self, left, right, margin=65): + expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) + pieces = expr.split(",") + res = [pieces.pop(0)] + for piece in pieces: + if len(res[-1])+len(piece)+1 > margin: + res[-1] += "," + res.append(piece) + else: + res[-1] += (","+piece) + return res + + def large_initialize(self, vars, margin=65): + res = [] + nonestr = "None" + margin -= len(nonestr) + for var in vars: + ass = var+"=" + if not res or len(res[-1]) >= margin: + res.append(ass) + res[-1] += ass + res = [line + nonestr for line in res] + return res + + def gen_link(self, link, localvars, blocknum, block, linklocalvars=None): + "Generate the code to jump across the given Link." + linklocalvars = linklocalvars or {} + left, right = [], [] + for a1, a2 in zip(link.args, link.target.inputargs): + if a1 in linklocalvars: + src = linklocalvars[a1] + else: + src = self.expr(a1, localvars) + left.append(self.expr(a2, localvars)) + right.append(src) + txt = "%s = %s" % (", ".join(left), ", ".join(right)) + if len(txt) <= 65: # arbitrary + yield txt + else: + for line in self.large_assignment(left, right): + yield line + goto = blocknum[link.target] + yield 'goto = %d' % goto + if goto <= blocknum[block]: + yield 'continue' + + def nameof(self, obj, debug=None, namehint=None): key = Constant(obj).key try: return self.rpynames[key] except KeyError: - #name = "w(%s)" % str(obj) - #self.rpynames[key] = name - #return name + if debug: + stackentry = debug, obj + else: + stackentry = obj + self.debugstack = (self.debugstack, stackentry) if (type(obj).__module__ != '__builtin__' and not isinstance(obj, type)): # skip user-defined metaclasses # assume it's a user defined thingy @@ -120,26 +253,37 @@ if meth: break else: - raise Exception, "nameof(%r) in %r" % (obj, self.current_func) - name = meth(obj) + raise Exception, "nameof(%r)" % (obj,) + + code=meth.im_func.func_code + if namehint and 'namehint' in code.co_varnames[:code.co_argcount]: + name = meth(obj, namehint=namehint) + else: + name = meth(obj) + self.debugstack, x = self.debugstack + assert x is stackentry self.rpynames[key] = name return name def uniquename(self, basename): + basename = basename.translate(C_IDENTIFIER) n = self.seennames.get(basename, 0) self.seennames[basename] = n+1 if n == 0: self.globalobjects.append(basename) - self.globaldecl.append('static PyObject *%s;' % (basename,)) + self.globaldecl.append('# global object %s' % (basename,)) return basename else: return self.uniquename('%s_%d' % (basename, n)) def nameof_object(self, value): if type(value) is not object: - raise Exception, "nameof(%r) in %r" % (value, self.current_func) + #raise Exception, "nameof(%r) in %r" % (value, self.currentfunc) + name = self.uniquename('g_unknown_%r' % value) + self.initcode.append('# cannot build %s as %r' % (name, object)) + return name name = self.uniquename('g_object') - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*)&PyBaseObject_Type, ""))'%name) + self.initcode.append('m.%s = object()'%name) return name def nameof_module(self, value): @@ -148,44 +292,75 @@ value.__file__.endswith('.py') or value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value - name = self.uniquename('mod%s'%value.__name__) - self.initcode.append('INITCHK(%s = PyImport_ImportModule("%s"))'%(name, value.__name__)) + name = self.uniquename('mod_%s'%value.__name__) + self.initcode.append('import %s as _tmp' % value.__name__) + self.initcode.append('m.%s = space.wrap(_tmp)' % (name)) return name def nameof_int(self, value): - return "w(%d)" % value + if value >= 0: + name = 'gi_%d' % value + else: + name = 'gim_%d' % abs(value) + name = self.uniquename(name) + self.initcode.append('m.%s = space.newint(%d)' % (name, value)) + return name def nameof_long(self, value): + # allow short longs only, meaning they + # must fit into a machine word. + assert (sys.maxint*2+1)&value==value, "your literal long is too long" # assume we want them in hex most of the time if value < 256L: - return "%dL" % value + s = "%dL" % value + else: + s = "0x%08xL" % value + if value >= 0: + name = 'glong_%s' % s else: - return "0x%08xL" % value + name = 'glongm_%d' % abs(value) + name = self.uniquename(name) + self.initcode.append('m.%s = space.wrap(%s) # XXX implement long!' % (name, s)) + return name def nameof_float(self, value): - return "w(%s)" % value - + name = 'gfloat_%s' % value + name = (name.replace('-', 'minus') + .replace('.', 'dot')) + name = self.uniquename(name) + self.initcode.append('m.%s = space.newfloat(%r)' % (name, value)) + return name + def nameof_str(self, value): - name = self.find_global_name(value) - if name: - return "w(%s)" % name - return "w(%s)" % repr(value) + if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']: + # non-printable string + namestr = repr(value)[1:-1] + else: + # printable string + namestr = value + if not namestr: + namestr = "_emptystr_" + name = self.uniquename('gs_' + namestr[:32]) + # self.initcode.append('m.%s = space.newstring(%r)' % (name, value)) + # ick! very unhandy + self.initcode.append('m.%s = space.wrap(%r)' % (name, value)) + return name def skipped_function(self, func): # debugging only! Generates a placeholder for missing functions # that raises an exception when called. name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('static PyMethodDef ml_%s = { "%s", &skipped, METH_VARARGS };' % (name, name)) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\tPy_INCREF(%s);' % name) - self.initcode.append('\tPyCFunction_GET_SELF(%s) = %s;' % (name, name)) + self.globaldecl.append('# global decl %s' % (name, )) + self.initcode.append('# build func %s' % name) return name - def nameof_function(self, func): + def trans_funcname(self, s): + return s.translate(C_IDENTIFIER) + + def nameof_function(self, func, namehint=''): printable_name = '(%s:%d) %s' % ( - func.func_globals.get('__name__', '?'), + self.trans_funcname(func.func_globals.get('__name__', '?')), func.func_code.co_firstlineno, func.__name__) if self.translator.frozen: @@ -197,10 +372,11 @@ func.func_doc.lstrip().startswith('NOT_RPYTHON')): print "skipped", printable_name return self.skipped_function(func) - name = func.__name__ - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\t%s->ob_type = &PyGenCFunction_Type;' % name) + name = self.uniquename('gfunc_' + self.trans_funcname( + namehint + func.__name__)) + f_name = 'f_' + name[6:] + self.initcode.append('from pypy.interpreter.gateway import interp2app') + self.initcode.append('m.%s = space.wrap(interp2app(%s))' % (name, f_name)) self.pendingfunctions.append(func) return name @@ -209,22 +385,20 @@ func = sm.__get__(42.5) name = self.uniquename('gsm_' + func.__name__) functionname = self.nameof(func) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, functionname)) + self.initcode.append('m.%s = space.wrap(%s)' % (name, functionname)) return name def nameof_instancemethod(self, meth): if meth.im_self is None: # no error checking here - return self.nameof(meth.im_func) + return self.nameof(meth.im_func, namehint="%s_" % meth.im_class.__name__) else: ob = self.nameof(meth.im_self) func = self.nameof(meth.im_func) typ = self.nameof(meth.im_class) name = self.uniquename('gmeth_'+meth.im_func.__name__) self.initcode.append( - 'INITCHK(%s = gencfunc_descr_get(%s, %s, %s))'%( - name, func, ob, typ)) + '%s = space.getattr(%s, %s)'%(name, ob, func)) return name def should_translate_attr(self, pbc, attr): @@ -235,16 +409,13 @@ return False else: return "probably" # True - if attr in ann.getpbcattrs(pbc): - return True classdef = ann.getuserclasses().get(pbc.__class__) - if (classdef and - classdef.about_attribute(attr) != annmodel.SomeImpossibleValue()): + if classdef and classdef.about_attribute(attr) is not None: return True return False def later(self, gen): - self.latercode.append(gen) + self.latercode.append((gen, self.debugstack)) def nameof_instance(self, instance): name = self.uniquename('ginst_' + instance.__class__.__name__) @@ -254,24 +425,67 @@ content.sort() for key, value in content: if self.should_translate_attr(instance, key): - yield 'INITCHK(SETUP_INSTANCE_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) - self.initcode.append('INITCHK(SETUP_INSTANCE(%s, %s))' % ( - name, cls)) + yield 'space.setattr(%s, %s, %s)' % ( + name, self.nameof(key), self.nameof(value)) + if isinstance(instance, Exception): + # specialcase for exception instances: wrap them directly + self.initcode.append('_ins = %s()\n' + 'm.%s = space.wrap(_ins)' % ( + instance.__class__.__name__, name)) + else: + # this seems to hardly work with the faked stuff + self.initcode.append('from types import InstanceType') + self.initcode.append('w_InstanceType = space.wrap(InstanceType)') + self.initcode.append('_tup = space.newtuple([%s])\n' + 'm.%s = space.call(w_InstanceType, _tup)' % ( + cls, name)) self.later(initinstance()) return name def nameof_builtin_function_or_method(self, func): - return "w(%s)" % func.__name__ + if func.__self__ is None: + # builtin function + if hasattr(self.space, func.__name__): + return "space.%s" % func.__name__ + # where does it come from? Python2.2 doesn't have func.__module__ + for modname, module in sys.modules.items(): + if hasattr(module, '__file__'): + if (module.__file__.endswith('.py') or + module.__file__.endswith('.pyc') or + module.__file__.endswith('.pyo')): + continue # skip non-builtin modules + if func is getattr(module, func.__name__, None): + break + else: + raise Exception, '%r not found in any built-in module' % (func,) + name = self.uniquename('gbltin_' + func.__name__) + if modname == '__builtin__': + self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( + name, self.nameof(func.__name__))) + else: + self.initcode.append('m.%s = space.getattr(%s, %s)' % ( + name, self.nameof(module), self.nameof(func.__name__))) + else: + # builtin (bound) method + name = self.uniquename('gbltinmethod_' + func.__name__) + self.initcode.append('m.%s = space.getattr(%s, %s)' % ( + name, self.nameof(func.__self__), self.nameof(func.__name__))) + return name def nameof_classobj(self, cls): if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): raise Exception, "%r should never be reached" % (cls,) - metaclass = "&PyType_Type" + metaclass = "space.w_type" + name = self.uniquename('gcls_' + cls.__name__) if issubclass(cls, Exception): if cls.__module__ == 'exceptions': - return 'w(%s)'%cls.__name__ + if hasattr(self.space, "w_%s" % cls.__name__): + return 'space.w_%s'%cls.__name__ + else: + self.initcode.append('m.%s = space.wrap(%s)' % ( + name, cls.__name__)) + return name #else: # # exceptions must be old-style classes (grr!) # metaclass = "&PyClass_Type" @@ -279,9 +493,13 @@ # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - metaclass = "&PyClass_Type" + # self.initcode.append("import types\n" + # "m.classtype = space.wrap(types.ClassType)\n") + # metaclass = "m.classtype" + # XXX I cannot instantiate these. + # XXX using type instead, since we still inherit from exception + # XXX what is the future of classes in pypy? - name = self.uniquename('gcls_' + cls.__name__) basenames = [self.nameof(base) for base in cls.__bases__] def initclassobj(): content = cls.__dict__.items() @@ -293,34 +511,83 @@ continue # XXX some __NAMES__ are important... nicer solution sought #raise Exception, "unexpected name %r in class %s"%(key, cls) + + # redirect value through class interface, in order to + # get methods instead of functions. + value = getattr(cls, key) + if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: - print value + print "skipped staticmethod:", value continue if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: - print value + print "skippedfunction:", value continue - yield 'INITCHK(SETUP_CLASS_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) + yield 'space.setattr(%s, %s, %s)' % ( + name, self.nameof(key), self.nameof(value)) baseargs = ", ".join(basenames) - if baseargs: - baseargs = ', '+baseargs - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*) %s,' - %(name, metaclass)) - self.initcode.append('\t\t"s(%s){}", "%s"%s))' - %("O"*len(basenames), cls.__name__, baseargs)) + self.initcode.append('_dic = space.newdict([])\n' + '_bases = space.newtuple([%(bases)s])\n' + '_args = space.newtuple([%(name)s, _bases, _dic])\n' + 'm.%(klass)s = space.call(%(meta)s, _args)' + % {"bases": baseargs, + "klass": name, + "name" : self.nameof(cls.__name__), + "meta" : metaclass} ) self.later(initclassobj()) return name nameof_class = nameof_classobj # for Python 2.2 + typename_mapping = { + object: 'space.w_object', + int: 'space.w_int', + long: 'space.w_long', + bool: 'space.w_bool', + list: 'space.w_list', + tuple: 'space.w_tuple', + dict: 'space.w_dict', + str: 'space.w_str', + float: 'space.w_float', + type(Exception()): 'space.wrap(types.InstanceType)', + type: 'space.w_type', + complex:'space.wrap(types.ComplexType)', + unicode:'space.w_unicode', + file: 'space.wrap(file)', + type(None): 'space.wrap(types.NoneType)', + CodeType: 'space.wrap(types.CodeType)', + + ##r_int: 'space.w_int', + ##r_uint: 'space.w_int', + + # XXX we leak 5 references here, but that's the least of the + # problems with this section of code + # type 'builtin_function_or_method': + type(len): 'space.wrap(types.FunctionType)', + # type 'method_descriptor': + # XXX small problem here: + # XXX with space.eval, we get + # XXX but with wrap, we get + type(list.append): 'eval_helper(space, "list.append")', + # type 'wrapper_descriptor': + type(type(None).__repr__): 'eval_helper(space, ".type(None).__repr__")', + # type 'getset_descriptor': + # XXX here we get , + # while eval gives us + type(type.__dict__['__dict__']): 'eval_helper(space,'\ + ' "type(type.__dict__[\'__dict__\'])")', + # type 'member_descriptor': + # XXX this does not work in eval! + # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", + # XXX there seems to be no working support for member descriptors ??? + type(type.__dict__['__basicsize__']): "space.wrap(type(type.__dict__['__basicsize__']))", + } def nameof_type(self, cls): - return "w(%s)" % cls.__name__ ##?? if cls in self.typename_mapping: - return '(PyObject*) %s' % self.typename_mapping[cls] + return self.typename_mapping[cls] assert cls.__module__ != '__builtin__', \ "built-in class %r not found in typename_mapping" % (cls,) return self.nameof_classobj(cls) @@ -328,9 +595,8 @@ def nameof_tuple(self, tup): name = self.uniquename('g%dtuple' % len(tup)) args = [self.nameof(x) for x in tup] - args.insert(0, '%d' % len(tup)) args = ', '.join(args) - self.initcode.append('INITCHK(%s = PyTuple_Pack(%s))' % (name, args)) + self.initcode.append('m.%s = space.newtuple([%s])' % (name, args)) return name def nameof_list(self, lis): @@ -338,32 +604,23 @@ def initlist(): for i in range(len(lis)): item = self.nameof(lis[i]) - yield '\tPy_INCREF(%s);' % item - yield '\tPyList_SET_ITEM(%s, %d, %s);' % (name, i, item) - self.initcode.append('INITCHK(%s = PyList_New(%d))' % (name, len(lis))) + yield 'space.setitem(%s, %s, %s);' % ( + name, self.nameof(i), self.nameof(item)) + self.initcode.append('m.%s = space.newlist(%s)' % (name, self.nameof(0))) + self.initcode.append('m.%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) self.later(initlist()) return name def nameof_dict(self, dic): - name = self.find_global_name(dic) - if name: - return name - return 'space.newdict([w("sorry", "not yet"])' assert dic is not __builtins__ assert '__builtins__' not in dic, 'Seems to be the globals of %s' % ( dic.get('__name__', '?'),) name = self.uniquename('g%ddict' % len(dic)) def initdict(): for k in dic: - if type(k) is str: - yield ('\tINITCHK(PyDict_SetItemString' - '(%s, "%s", %s) >= 0)'%( - name, k, self.nameof(dic[k]))) - else: - yield ('\tINITCHK(PyDict_SetItem' - '(%s, %s, %s) >= 0)'%( - name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('INITCHK(%s = PyDict_New())' % (name,)) + yield ('space.setitem(%s, %s, %s)'%( + name, self.nameof(k), self.nameof(dic[k]))) + self.initcode.append('m.%s = space.newdict([])' % (name,)) self.later(initdict()) return name @@ -373,11 +630,9 @@ name = self.uniquename('gdescriptor_%s_%s' % ( md.__objclass__.__name__, md.__name__)) cls = self.nameof(md.__objclass__) - self.initcode.append('INITCHK(PyType_Ready((PyTypeObject*) %s) >= 0)' % - cls) - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - '((PyTypeObject*) %s)->tp_dict, "%s"))' % - (name, cls, md.__name__)) + # do I need to take the dict and then getitem??? + self.initcode.append('m.%s = space.getattr(%s, %s)' % + (name, cls, self.nameof(md.__name__))) return name nameof_getset_descriptor = nameof_member_descriptor nameof_method_descriptor = nameof_member_descriptor @@ -392,103 +647,236 @@ return 'PySys_GetObject("stderr")' raise Exception, 'Cannot translate an already-open file: %r' % (fil,) - def gen_source(self): + def gen_source(self, fname, ftmpname=None): + self.fname = fname + self.ftmpname = ftmpname + + # generate unordered source file, first. + # I prefer this over ordering everything in memory. + fname = self.fname + if self.ftmpname: + fname = self.ftmpname + f = file(fname, "w") + # generate ordered source file + try: + self.f = f + self.gen_source_temp() + finally: + f.close() + + def copyfile(source, target): + file(target, "w").write(file(source).read()) + + def order_sections(fname): + sep = "\n##SECTION##\n" + txt = file(fname).read() + pieces = txt.split(sep) + prelude = pieces.pop(0) + postlude = pieces.pop() + dic = {} + while pieces: + func = pieces.pop() + head = pieces.pop() + key = makekey(head, len(pieces)) + dic[key] = head + sep + func + lis = dic.items() + lis.sort() + lis = [prelude] + [func for head, func in lis] + [postlude] + txt = sep.join(lis) + file(fname, "w").write(txt) + + def makekey(txt, uniqueno): + dic = {} + for line in txt.split("\n"): + ign, name, value = line.split(None, 2) + dic[name] = eval(value) + key = dic["filename"], dic["firstlineno"], uniqueno + return key + + order_sections(fname) + if self.ftmpname: + copyfile(self.ftmpname, self.fname) + + def gen_source_temp(self): f = self.f info = { 'modname': self.modname, - 'entrypointname': self.translator.functions[0].__name__, + 'entrypointname': self.trans_funcname( + self.translator.functions[0].__name__), 'entrypoint': self.nameof(self.translator.functions[0]), } - - # make sure + # header + print >> f, self.RPY_HEADER # function implementations while self.pendingfunctions: - func = self.current_func = self.pendingfunctions.pop() - self.adjust_namespace() + func = self.pendingfunctions.pop() + self.currentfunc = func self.gen_rpyfunction(func) # collect more of the latercode after each function while self.latercode: - #gen, self.debugstack = self.latercode.pop() - gen = self.latercode.pop() + gen, self.debugstack = self.latercode.pop() #self.initcode.extend(gen) -- eats TypeError! bad CPython! for line in gen: self.initcode.append(line) self.debugstack = () - #self.gen_global_declarations() - print >> f + self.gen_global_declarations() + # set the final splitter + print >> f, "##SECTION##" # footer - # maybe not needed - return - print >> f, self.C_INIT_HEADER % info - if self.f2name is not None: - print >> f, '#include "%s"' % self.f2name - for codeline in self.initcode: - print >> f, '\t' + codeline - print >> f, self.C_INIT_FOOTER % info + print >> f, self.RPY_INIT_HEADER % info + for codelines in self.initcode: + for codeline in codelines.split("\n"): + print >> f, " %s" % codeline + print >> f, self.RPY_INIT_FOOTER % info + f.close() + + def gen_global_declarations(self): + g = self.globaldecl + if g: + f = self.f + print >> f, '# global declaration%s' % ('s'*(len(g)>1)) + for line in g: + print >> f, line + print >> f + del g[:] + g = self.globalobjects + for name in g: + pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) + del g[:] def gen_rpyfunction(self, func): - local_names = {} + f = self.f + print >> f, "##SECTION##" # simple to split, afterwards + print >> f, ("## filename %r\n" + "## function %r\n" + "## firstlineno %d") % ( + func.func_code.co_filename, + func.func_code.co_name, + func.func_code.co_firstlineno) + print >> f, "##SECTION##" + locals = {} + body = list(self.rpyfunction_body(func, locals)) + name_of_defaults = [self.nameof(x, debug=('Default argument of', func)) + for x in (func.func_defaults or ())] + self.gen_global_declarations() + + # print header + cname = self.nameof(func) + assert cname.startswith('gfunc_') + f_name = 'f_' + cname[6:] + + # collect all the local variables + graph = self.translator.getflowgraph(func) + localslst = [] + def visit(node): + if isinstance(node, Block): + localslst.extend(node.getvariables()) + traverse(visit, graph) + localnames = [self.expr(a, locals) for a in uniqueitems(localslst)] + + # collect all the arguments + if func.func_code.co_flags & CO_VARARGS: + vararg = graph.getargs()[-1] + positional_args = graph.getargs()[:-1] + else: + vararg = None + positional_args = graph.getargs() + min_number_of_args = len(positional_args) - len(name_of_defaults) + + fast_args = [self.expr(a, locals) for a in positional_args] + if vararg is not None: + fast_args.append(self.expr(vararg, locals)) + fast_name = 'fast' + f_name + + fast_set = dict(zip(fast_args, fast_args)) - def expr(v, wrapped = True): - if isinstance(v, Variable): - n = v.name - if n.startswith("v") and n[1:].isdigit(): - ret = local_names.get(v.name) - if not ret: - if wrapped: - local_names[v.name] = ret = "w_%d" % len(local_names) - else: - local_names[v.name] = ret = "v%d" % len(local_names) - return ret - return v.name - elif isinstance(v, Constant): - return self.nameof(v.value) - else: - #raise TypeError, "expr(%r)" % (v,) - # XXX how do I resolve these? - return "space.%s" % str(v) - - def arglist(args): - res = [expr(arg) for arg in args] - return ", ".join(res) - - def oper(op): - print op.opname, op.args - if op.opname == "simple_call": - v = op.args[0] - if isinstance(v, Constant) and self.find_global_name(v.value): - fmt = "%s = %s(space, %s)" - else: - fmt = "%s = space.call(%s, space.newtuple([%s]))" - return fmt % (expr(op.result), expr(op.args[0]), arglist(op.args[1:])) - if op.opname in self.has_listarg: - fmt = "%s = %s([%s])" - else: - fmt = "%s = %s(%s)" - # specialcase is_true - if op.opname == "is_true": - return fmt % (expr(op.result, False), expr(op.opname), arglist(op.args)) - return fmt % (expr(op.result), expr(op.opname), arglist(op.args)) - - def gen_link(link, linklocalvars=None): - "Generate the code to jump across the given Link." - linklocalvars = linklocalvars or {} - left, right = [], [] - for a1, a2 in zip(link.args, link.target.inputargs): - if a1 in linklocalvars: - src = linklocalvars[a1] - else: - src = expr(a1) - left.append(expr(a2)) - right.append(src) - yield "%s = %s" % (", ".join(left), ", ".join(right)) - goto = blocknum[link.target] - yield 'goto = %d' % goto - if goto <= blocknum[block]: - yield 'continue' + # create function declaration + name = func.__name__ + argstr = ", ".join(fast_args) + fast_function_header = ('def %s(space, %s):' + % (fast_name, argstr)) + + print >> f, 'def %s(space, *args_w):' % (f_name,) + kwlist = ['"%s"' % name for name in + func.func_code.co_varnames[:func.func_code.co_argcount]] + print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) + + # argument unpacking + if vararg is not None: + varname = self.expr(vararg, locals) + lenargs = len(positional_args) + print >> f, ' %s = space.newtuple(list(args_w[%d:]))' % ( + varname, lenargs) + print >> f, ' _args_w = args_w[:%d]' % (lenargs,) + else: + print >> f, ' _args_w = args_w' + varname = None + + def tupstr(seq): + if len(seq) == 1: + fmt = '%s,' + else: + fmt = '%s' + return fmt % ', '.join(seq) + + print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) + + theargs = [arg for arg in fast_args if arg != varname] + txt = ('from pypy.translator.genrpy import PyArg_ParseMini\n' + 'm.PyArg_ParseMini = PyArg_ParseMini\n' + 'from pypy.interpreter.error import OperationError\n' + 'm.OperationError = OperationError') + self.initcode.append(txt) + print >> f, ' funcname = "%s"' % func.__name__ + if theargs: + txt = ' %s = PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' + print >>f, txt % (tupstr(theargs), + min_number_of_args, len(positional_args)) + else: + txt = ' PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' + print >>f, txt % (min_number_of_args, len(positional_args)) + print >> f, ' return %s(space, %s)' % (fast_name, ', '.join(fast_args)) + print >> f + + print >> f, fast_function_header + + fast_locals = [arg for arg in localnames if arg not in fast_set] + if fast_locals: + print >> f + for line in self.large_initialize(fast_locals): + print >> f, " %s" % line + print >> f + # generate an incref for each input argument + # skipped + + # print the body + for line in body: + print >> f, line + print >> f + + # print the PyMethodDef + # skipped + + if not self.translator.frozen: + # this is only to keep the RAM consumption under control + del self.translator.flowgraphs[func] + Variable.instances.clear() + + def rpyfunction_body(self, func, localvars): + try: + graph = self.translator.getflowgraph(func) + except Exception, e: + print 20*"*", e + print func + raise + # not needed, we use tuple assignment! + # remove_direct_loops(graph) + checkgraph(graph) + + allblocks = [] f = self.f t = self.translator @@ -496,65 +884,68 @@ graph = t.getflowgraph(func) start = graph.startblock - blocks = ordered_blocks(graph) - nblocks = len(blocks) + allblocks = ordered_blocks(graph) + nblocks = len(allblocks) blocknum = {} - for block in blocks: + for block in allblocks: blocknum[block] = len(blocknum)+1 - # create function declaration - name = func.__name__ # change this - args = [expr(var) for var in start.inputargs] - argstr = ", ".join(args) - print >> f, "def %s(space, %s):" % (name, argstr) - print >> f, " w = space.wrap" - print >> f, " goto = %d # startblock" % blocknum[start] - print >> f, " while True:" - + yield " goto = %d # startblock" % blocknum[start] + yield " while True:" + def render_block(block): catch_exception = block.exitswitch == Constant(last_exception) regular_op = len(block.operations) - catch_exception # render all but maybe the last op for op in block.operations[:regular_op]: - yield "%s" % oper(op) + for line in self.oper(op, localvars).split("\n"): + yield "%s" % line # render the last op if it is exception handled for op in block.operations[regular_op:]: yield "try:" - yield " %s" % oper(op) + for line in self.oper(op, localvars).split("\n"): + yield " %s" % line if len(block.exits) == 0: if len(block.inputargs) == 2: # exc_cls, exc_value # exceptional return block - exc_cls = expr(block.inputargs[0]) - exc_val = expr(block.inputargs[1]) + exc_cls = self.expr(block.inputargs[0], localvars) + exc_val = self.expr(block.inputargs[1], localvars) yield "raise OperationError(%s, %s)" % (exc_cls, exc_val) else: # regular return block - retval = expr(block.inputargs[0]) + retval = self.expr(block.inputargs[0], localvars) yield "return %s" % retval return elif block.exitswitch is None: # single-exit block assert len(block.exits) == 1 - for op in gen_link(block.exits[0]): + for op in self.gen_link(block.exits[0], localvars, blocknum, block): yield "%s" % op elif catch_exception: # block catching the exceptions raised by its last operation # we handle the non-exceptional case first link = block.exits[0] assert link.exitcase is None - for op in gen_link(link): + for op in self.gen_link(link, localvars, blocknum, block): yield " %s" % op # we must catch the exception raised by the last operation, # which goes to the last err%d_%d label written above. + # Since we only have OperationError, we need to select: + yield "except OperationError, e:" + q = "if" for link in block.exits[1:]: assert issubclass(link.exitcase, Exception) - yield "except OperationError, e:" - for op in gen_link(link, { + # Exeption classes come unwrapped in link.exitcase + yield " %s space.is_true(space.issubtype(e.w_type, %s)):" % (q, + self.nameof(link.exitcase)) + q = "elif" + for op in self.gen_link(link, localvars, blocknum, block, { Constant(last_exception): 'e.w_type', Constant(last_exc_value): 'e.w_value'}): - yield " %s" % op + yield " %s" % op + yield " else:raise # unhandled case, should not happen" else: # block ending in a switch on a value exits = list(block.exits) @@ -564,34 +955,101 @@ exits.reverse() q = "if" for link in exits[:-1]: - yield "%s %s == %s:" % (q, expr(block.exitswitch), + yield "%s %s == %s:" % (q, self.expr(block.exitswitch, + localvars), link.exitcase) - for op in gen_link(link): + for op in self.gen_link(link, localvars, blocknum, block): yield " %s" % op q = "elif" link = exits[-1] yield "else:" - yield " assert %s == %s" % (expr(block.exitswitch), + yield " assert %s == %s" % (self.expr(block.exitswitch, + localvars), link.exitcase) - for op in gen_link(exits[-1]): + for op in self.gen_link(exits[-1], localvars, blocknum, block): yield " %s" % op - for block in blocks: + for block in allblocks: blockno = blocknum[block] - print >> f - print >> f, " if goto == %d:" % blockno + yield "" + yield " if goto == %d:" % blockno for line in render_block(block): - print >> f, " %s" % line + yield " %s" % line + +# ____________________________________________________________ + + RPY_HEADER = '#!/bin/env python\n# -*- coding: LATIN-1 -*-' + + RPY_SEP = "#*************************************************************" + + RPY_INIT_HEADER = RPY_SEP + ''' + +def init%(modname)s(space): + """NOT_RPYTHON""" + class m: pass # fake module + m.__dict__ = globals() +''' + + RPY_INIT_FOOTER = ''' +# entry point: %(entrypointname)s, %(entrypoint)s) +if __name__ == "__main__": + from pypy.objspace.std import StdObjSpace + space = StdObjSpace() + init%(modname)s(space) + print space.unwrap(space.call( + gfunc_%(entrypointname)s, space.newtuple([]))) +''' + +# a translation table suitable for str.translate() to remove +# non-C characters from an identifier +C_IDENTIFIER = ''.join([(('0' <= chr(i) <= '9' or + 'a' <= chr(i) <= 'z' or + 'A' <= chr(i) <= 'Z') and chr(i) or '_') + for i in range(256)]) + +# temporary arg parsing +# what about keywords? Gateway doesn't support it. +def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): + err = None + if len(args_w) < minargs: + txt = "%s() takes at least %d argument%s (%d given)" + plural = ['s', ''][minargs == 1] + err = (name, minargs, plural, len(args_w)) + if len(args_w) > maxargs: + plural = ['s', ''][maxargs == 1] + if minargs == maxargs: + if minargs == 0: + txt = '%s() takes no arguments (%d given)' + err = (name, len(args_w)) + elif minargs == 1: + txt = '%s() takes exactly %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + else: + txt = '%s() takes at most %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + if err: + w_txt = space.wrap(txt) + w_tup = space.wrap(err) + w_txt = space.mod(w_txt, w_tup) + raise OperationError(space.w_TypeError, w_txt) + + # finally, we create the result ;-) + res_w = args_w + defaults_w[len(args_w) - minargs:] + assert len(res_w) == maxargs + return res_w +# _____________________________________________________________________ + +## this should go into some test file def somefunc(arg): pass def f(a,b): - print "start" +## print "start" a = [] a.append(3) for i in range(3): - print i + pass#print i if a > b: try: if b == 123: @@ -605,12 +1063,20 @@ dummy = somefunc(23) return 42 -def ff(a, b): +class TestClass:pass + +def ff(a, b, c=3,*rest): try: - raise SystemError, 42 - return a+b - finally: - a = 7 + try: + if rest: + raise SystemError, 42 + return a+b + finally: + a = 7 + if rest: + return len(rest),c + except TypeError: + print "eek" glob = 100 def fff(): @@ -640,39 +1106,98 @@ #import md5 # how do I avoid the builtin module? from pypy.appspace import md5 - digest = md5.new("hello") + digest = md5.new("hello").hexdigest() + return digest def test_mod(): return app_mod__String_ANY("-%s-", ["hallo"]) -entry_point = (f, ff, fff, app_str_decode__String_ANY_ANY, test_mod, test_md5) [-2] +def test_join(): + return " ".join(["hi", "there"]) + +# cannot nest local classes, yet +# this appears to be a problem in flow space. +class AnIterClass(object): + def __init__(self): + self.lis = [c for c in "test"] + def next(self): + if self.lis: + return self.lis.pop() + raise StopIteration + def __iter__(self): + return self + +def test_iter(): + res = [] + for i in "hallo": + res.append(i) + for i in AnIterClass(): + res.append(i) + return res + +def test_strutil(): + from pypy.objspace.std import strutil + return (strutil.string_to_int("42"), + strutil.string_to_long("12345678901234567890")) + +def test_struct(): + from pypy.appspace import struct + import struct as stru + res1 = stru.pack('f',1.23), struct.pack('f',1.23) + res2 = struct.unpack('f', struct.pack('f',1.23)) + return res1, res2 + +def all_entries(): + res = [func() for func in entry_points[:-1]] + return res + +entry_points = (lambda: f(2, 3), + lambda: ff(2, 3, 5), + fff, + lambda: app_str_decode__String_ANY_ANY("hugo"), + test_mod, + test_md5, + test_join, + test_iter, + test_strutil, + test_struct, + all_entries) +entry_point = entry_points[-2] + +if __name__ == "__main__": + import os, sys + from pypy.interpreter import autopath + srcdir = os.path.dirname(autopath.pypydir) + appdir = os.path.join(autopath.pypydir, 'appspace') + + if appdir not in sys.path: + sys.path.insert(0, appdir) -import os, sys -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -appdir = os.path.join(autopath.pypydir, 'appspace') - -try: - hold = sys.path[:] - sys.path.insert(0, appdir) t = Translator(entry_point, verbose=False, simplifying=True) - if 0: - gen = GenRpy(sys.stdout, t) - else: - fil= file("d:/tmp/look.py", "w") - gen = GenRpy(fil, t) - print >> fil, \ -""" -from pypy.objspace.std import StdObjSpace -space = StdObjSpace() -space.simple_call = space.call -test_mod(space) -""" - fil.close() -finally: - sys.path[:] = hold -#t.simplify() -#t.view() -# debugging -graph = t.getflowgraph() -ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab + gen = GenRpy(t) + gen.use_fast_call = True + import pypy.appspace.generated as tmp + pth = os.path.dirname(tmp.__file__) + ftmpname = "d:/tmp/look.py" + fname = os.path.join(pth, gen.modname+".py") + gen.gen_source(fname, ftmpname) + + #t.simplify() + #t.view() + # debugging + graph = t.getflowgraph() + ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab + +def crazy_test(): + """ this thingy is generating the whole interpreter in itself""" + # but doesn't work, my goto's give a problem for flow space + dic = {"__builtins__": __builtins__, "__name__": "__main__"} + execfile("d:/tmp/look.py", dic) + + def test(): + f_ff(space, 2, 3) + test = type(test)(test.func_code, dic) + + t = Translator(test, verbose=False, simplifying=True) + gen = GenRpy(t) + gen.gen_source("d:/tmp/look2.py") Copied: pypy/branch/src-pytest/pypy/translator/java/test/test_javatrans.py (from r8225, pypy/trunk/src/pypy/translator/java/test/test_javatrans.py) ============================================================================== --- pypy/trunk/src/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/java/test/test_javatrans.py Wed Jan 12 15:31:13 2005 @@ -1,16 +1,14 @@ import autopath, os from py.process import cmdexec -from pypy.tool import testit from pypy.tool.udir import udir from pypy.translator.java.genjava import GenJava from pypy.translator.test import snippet from pypy.translator.translator import Translator -class NoTypeCGenTestCase(testit.IntTestCase): +class TestNoTypeCGenTestCase: - def setUp(self): - self.space = testit.objspace('flow') + objspacename = 'flow' def build_jfunc(self, func): try: func = func.im_func @@ -27,7 +25,7 @@ try: os.chdir(str(self.jdir)) cmdexec('javac *.java') - self.assertEquals(cmdexec('java test').strip(), 'OK') + assert cmdexec('java test').strip() == 'OK' finally: os.chdir(cwd) @@ -48,7 +46,3 @@ def test_sieve_of_eratosthenes(self): self.build_jfunc(snippet.sieve_of_eratosthenes) self.check([], 1028) - - -if __name__ == '__main__': - testit.main() Modified: pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py (original) +++ pypy/branch/src-pytest/pypy/translator/test/test_ctrans.py Wed Jan 12 15:31:13 2005 @@ -150,7 +150,7 @@ raises(TypeError, call_with_star, [4,7,12,63]) raises(TypeError, call_with_star, 521) - def XXX_test_call_with_keyword(self): + def test_call_with_keyword(self): call_with_keyword = self.build_cfunc(snippet.call_with_keyword) assert call_with_keyword(100) == 82 Modified: pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py ============================================================================== --- pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py (original) +++ pypy/branch/src-pytest/pypy/translator/tool/buildpyxmodule.py Wed Jan 12 15:31:13 2005 @@ -53,7 +53,7 @@ lastdir = path.local() os.chdir(str(dirpath)) try: - modname = cfile.purebasename + modname = cfile.purebasename if debug: print "modname", modname c = stdoutcapture.Capture(mixed_out_err = True) try: From pedronis at codespeak.net Wed Jan 12 16:30:40 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 12 Jan 2005 16:30:40 +0100 (MET) Subject: [pypy-svn] r8236 - in pypy: branch/src-pytest trunk/src Message-ID: <20050112153040.4C86127BDB@code1.codespeak.net> Author: pedronis Date: Wed Jan 12 16:30:40 2005 New Revision: 8236 Added: pypy/trunk/src/ - copied from r8235, pypy/branch/src-pytest/ Removed: pypy/branch/src-pytest/ Log: swapping branch and head From pedronis at codespeak.net Wed Jan 12 16:47:26 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 12 Jan 2005 16:47:26 +0100 (MET) Subject: [pypy-svn] r8237 - pypy/trunk/src/pypy/translator Message-ID: <20050112154726.ACC6F27BDB@code1.codespeak.net> Author: pedronis Date: Wed Jan 12 16:47:26 2005 New Revision: 8237 Removed: pypy/trunk/src/pypy/translator/genrpy.py Log: removed spurious file from merge, now it's geninterplevel.py Deleted: /pypy/trunk/src/pypy/translator/genrpy.py ============================================================================== --- /pypy/trunk/src/pypy/translator/genrpy.py Wed Jan 12 16:47:26 2005 +++ (empty file) @@ -1,1203 +0,0 @@ -""" -Implementation of a translator from application Python to interpreter level RPython. - -The idea is that we can automatically transform app-space implementations -of methods into some equivalent representation at interpreter level. -Then, the RPython to C translation might hopefully spit out some -more efficient code than always interpreting these methods. - -Note that the appspace functions are treated as rpythonic, in a sense -that globals are constants, for instance. This definition is not -exact and might change. - -This module appears to be already quite usable. -But I need to ask how we want to integrate it. - -XXX open questions: -- do we wantamoduleperapp-spaceoperation? -- do we want to auto-generate stuff? -- do we want to create code that is more similar to the app code? -- do we want to create specialized code for constants? -- do we want to use small tail-functions instead of goto? -- do we want to inline small functions? -- do we want to translate non-rpythonic code as well? -""" - -from __future__ import generators -import autopath, os, sys, exceptions -from pypy.objspace.flow.model import Variable, Constant, SpaceOperation -from pypy.objspace.flow.model import FunctionGraph, Block, Link -from pypy.objspace.flow.model import last_exception, last_exc_value -from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph -from pypy.translator.simplify import remove_direct_loops -from pypy.interpreter.pycode import CO_VARARGS -from pypy.annotation import model as annmodel -from types import FunctionType, CodeType -from pypy.interpreter.error import OperationError -from pypy.objspace.std.restricted_int import r_int, r_uint - -from pypy.translator.translator import Translator -from pypy.objspace.std import StdObjSpace -from pypy.objspace.flow import FlowObjSpace - -from pypy.interpreter.gateway import app2interp, interp2app - - -# ____________________________________________________________ - -def c_string(s): - return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\"'),) - -def uniquemodulename(name, SEEN={}): - # never reuse the same module name within a Python session! - i = 0 - while True: - i += 1 - result = '%s_%d' % (name, i) - if result not in SEEN: - SEEN[result] = True - return result - -def ordered_blocks(graph): - # collect all blocks - allblocks = [] - def visit(block): - if isinstance(block, Block): - # first we order by offset in the code string - if block.operations: - ofs = block.operations[0].offset - else: - ofs = sys.maxint - # then we order by input variable name or value - if block.inputargs: - txt = str(block.inputargs[0]) - else: - txt = "dummy" - allblocks.append((ofs, txt, block)) - traverse(visit, graph) - allblocks.sort() - #for ofs, txt, block in allblocks: - # print ofs, txt, block - return [block for ofs, txt, block in allblocks] - -class UniqueList(list): - def __init__(self, *args, **kwds): - list.__init__(self, *args, **kwds) - self.dic = {} - - def append(self, arg): - try: - self.dic[arg] - except KeyError: - self.dic[arg] = 1 - list.append(self, arg) - except TypeError: # not hashable - if arg not in self: - list.append(self, arg) - -class GenRpy: - def __init__(self, translator, modname=None): - self.translator = translator - self.modname = self.trans_funcname(modname or - uniquemodulename(translator.functions[0].__name__)) - self.rpynames = {Constant(None).key: 'space.w_None', - Constant(False).key: 'space.w_False', - Constant(True).key: 'space.w_True', - } - - self.seennames = {} - u = UniqueList - self.initcode = u() # list of lines for the module's initxxx() - self.latercode = u() # list of generators generating extra lines - # for later in initxxx() -- for recursive - # objects - self.globaldecl = [] - self.globalobjects = [] - self.pendingfunctions = [] - self.currentfunc = None - self.debugstack = () # linked list of nested nameof() - - # special constructors: - self.has_listarg = {} - for name in "newtuple newlist newdict newstring".split(): - self.has_listarg[name] = name - - # XXX I guess it is cleaner to use the flow space? - # we just want to look into the operations, - # but we don't break into the implementation. - # Or should it be the base space, ARMIN? - #self.space = StdObjSpace() # for introspection - self.space = FlowObjSpace() # for introspection - - self.use_fast_call = False - - def expr(self, v, localnames, wrapped = True): - if isinstance(v, Variable): - n = v.name - if n.startswith("v") and n[1:].isdigit(): - ret = localnames.get(v.name) - if not ret: - if wrapped: - localnames[v.name] = ret = "w_%d" % len(localnames) - else: - localnames[v.name] = ret = "v%d" % len(localnames) - return ret - elif isinstance(v, Constant): - return self.nameof(v.value, - debug=('Constant in the graph of', self.currentfunc)) - else: - raise TypeError, "expr(%r)" % (v,) - - def arglist(self, args, localnames): - res = [self.expr(arg, localnames) for arg in args] - return ", ".join(res) - - def oper(self, op, localnames): - if op.opname == "simple_call": - v = op.args[0] - exv = self.expr(v, localnames) - if exv.startswith("space.") and not exv.startswith("space.w_"): - # it is a space method - fmt = "%(res)s = %(func)s(%(args)s)" - else: - # default for a spacecall: - fmt = ("_tup = space.newtuple([%(args)s])\n" - "%(res)s = space.call(%(func)s, _tup)") - # see if we can optimize for a fast call. - # we justdo the very simple ones. - if self.use_fast_call and (isinstance(v, Constant) - and exv.startswith('gfunc_')): - func = v.value - if (not func.func_code.co_flags & CO_VARARGS) and ( - func.func_defaults is None): - fmt = "%(res)s = fastf_%(func)s(space, %(args)s)" - exv = exv[6:] - return fmt % {"res" : self.expr(op.result, localnames), - "func": exv, - "args": self.arglist(op.args[1:], localnames) } - if op.opname in self.has_listarg: - fmt = "%s = %s([%s])" - else: - fmt = "%s = %s(%s)" - # special case is_true - wrapped = op.opname != "is_true" - oper = "space.%s" % op.opname - return fmt % (self.expr(op.result, localnames, wrapped), oper, - self.arglist(op.args, localnames)) - - def large_assignment(self, left, right, margin=65): - expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right)) - pieces = expr.split(",") - res = [pieces.pop(0)] - for piece in pieces: - if len(res[-1])+len(piece)+1 > margin: - res[-1] += "," - res.append(piece) - else: - res[-1] += (","+piece) - return res - - def large_initialize(self, vars, margin=65): - res = [] - nonestr = "None" - margin -= len(nonestr) - for var in vars: - ass = var+"=" - if not res or len(res[-1]) >= margin: - res.append(ass) - res[-1] += ass - res = [line + nonestr for line in res] - return res - - def gen_link(self, link, localvars, blocknum, block, linklocalvars=None): - "Generate the code to jump across the given Link." - linklocalvars = linklocalvars or {} - left, right = [], [] - for a1, a2 in zip(link.args, link.target.inputargs): - if a1 in linklocalvars: - src = linklocalvars[a1] - else: - src = self.expr(a1, localvars) - left.append(self.expr(a2, localvars)) - right.append(src) - txt = "%s = %s" % (", ".join(left), ", ".join(right)) - if len(txt) <= 65: # arbitrary - yield txt - else: - for line in self.large_assignment(left, right): - yield line - goto = blocknum[link.target] - yield 'goto = %d' % goto - if goto <= blocknum[block]: - yield 'continue' - - def nameof(self, obj, debug=None, namehint=None): - key = Constant(obj).key - try: - return self.rpynames[key] - except KeyError: - if debug: - stackentry = debug, obj - else: - stackentry = obj - self.debugstack = (self.debugstack, stackentry) - if (type(obj).__module__ != '__builtin__' and - not isinstance(obj, type)): # skip user-defined metaclasses - # assume it's a user defined thingy - name = self.nameof_instance(obj) - else: - for cls in type(obj).__mro__: - meth = getattr(self, - 'nameof_' + cls.__name__.replace(' ', ''), - None) - if meth: - break - else: - raise Exception, "nameof(%r)" % (obj,) - - code=meth.im_func.func_code - if namehint and 'namehint' in code.co_varnames[:code.co_argcount]: - name = meth(obj, namehint=namehint) - else: - name = meth(obj) - self.debugstack, x = self.debugstack - assert x is stackentry - self.rpynames[key] = name - return name - - def uniquename(self, basename): - basename = basename.translate(C_IDENTIFIER) - n = self.seennames.get(basename, 0) - self.seennames[basename] = n+1 - if n == 0: - self.globalobjects.append(basename) - self.globaldecl.append('# global object %s' % (basename,)) - return basename - else: - return self.uniquename('%s_%d' % (basename, n)) - - def nameof_object(self, value): - if type(value) is not object: - #raise Exception, "nameof(%r) in %r" % (value, self.currentfunc) - name = self.uniquename('g_unknown_%r' % value) - self.initcode.append('# cannot build %s as %r' % (name, object)) - return name - name = self.uniquename('g_object') - self.initcode.append('m.%s = object()'%name) - return name - - def nameof_module(self, value): - assert value is os or not hasattr(value, "__file__") or \ - not (value.__file__.endswith('.pyc') or - value.__file__.endswith('.py') or - value.__file__.endswith('.pyo')), \ - "%r is not a builtin module (probably :)"%value - name = self.uniquename('mod_%s'%value.__name__) - self.initcode.append('import %s as _tmp' % value.__name__) - self.initcode.append('m.%s = space.wrap(_tmp)' % (name)) - return name - - - def nameof_int(self, value): - if value >= 0: - name = 'gi_%d' % value - else: - name = 'gim_%d' % abs(value) - name = self.uniquename(name) - self.initcode.append('m.%s = space.newint(%d)' % (name, value)) - return name - - def nameof_long(self, value): - # allow short longs only, meaning they - # must fit into a machine word. - assert (sys.maxint*2+1)&value==value, "your literal long is too long" - # assume we want them in hex most of the time - if value < 256L: - s = "%dL" % value - else: - s = "0x%08xL" % value - if value >= 0: - name = 'glong_%s' % s - else: - name = 'glongm_%d' % abs(value) - name = self.uniquename(name) - self.initcode.append('m.%s = space.wrap(%s) # XXX implement long!' % (name, s)) - return name - - def nameof_float(self, value): - name = 'gfloat_%s' % value - name = (name.replace('-', 'minus') - .replace('.', 'dot')) - name = self.uniquename(name) - self.initcode.append('m.%s = space.newfloat(%r)' % (name, value)) - return name - - def nameof_str(self, value): - if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']: - # non-printable string - namestr = repr(value)[1:-1] - else: - # printable string - namestr = value - if not namestr: - namestr = "_emptystr_" - name = self.uniquename('gs_' + namestr[:32]) - # self.initcode.append('m.%s = space.newstring(%r)' % (name, value)) - # ick! very unhandy - self.initcode.append('m.%s = space.wrap(%r)' % (name, value)) - return name - - def skipped_function(self, func): - # debugging only! Generates a placeholder for missing functions - # that raises an exception when called. - name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('# global decl %s' % (name, )) - self.initcode.append('# build func %s' % name) - return name - - def trans_funcname(self, s): - return s.translate(C_IDENTIFIER) - - def nameof_function(self, func, namehint=''): - printable_name = '(%s:%d) %s' % ( - self.trans_funcname(func.func_globals.get('__name__', '?')), - func.func_code.co_firstlineno, - func.__name__) - if self.translator.frozen: - if func not in self.translator.flowgraphs: - print "NOT GENERATING", printable_name - return self.skipped_function(func) - else: - if (func.func_doc and - func.func_doc.lstrip().startswith('NOT_RPYTHON')): - print "skipped", printable_name - return self.skipped_function(func) - name = self.uniquename('gfunc_' + self.trans_funcname( - namehint + func.__name__)) - f_name = 'f_' + name[6:] - self.initcode.append('from pypy.interpreter.gateway import interp2app') - self.initcode.append('m.%s = space.wrap(interp2app(%s))' % (name, f_name)) - self.pendingfunctions.append(func) - return name - - def nameof_staticmethod(self, sm): - # XXX XXX XXXX - func = sm.__get__(42.5) - name = self.uniquename('gsm_' + func.__name__) - functionname = self.nameof(func) - self.initcode.append('m.%s = space.wrap(%s)' % (name, functionname)) - return name - - def nameof_instancemethod(self, meth): - if meth.im_self is None: - # no error checking here - return self.nameof(meth.im_func, namehint="%s_" % meth.im_class.__name__) - else: - ob = self.nameof(meth.im_self) - func = self.nameof(meth.im_func) - typ = self.nameof(meth.im_class) - name = self.uniquename('gmeth_'+meth.im_func.__name__) - self.initcode.append( - '%s = space.getattr(%s, %s)'%(name, ob, func)) - return name - - def should_translate_attr(self, pbc, attr): - ann = self.translator.annotator - if ann is None: - ignore = getattr(pbc.__class__, 'NOT_RPYTHON_ATTRIBUTES', []) - if attr in ignore: - return False - else: - return "probably" # True - classdef = ann.getuserclasses().get(pbc.__class__) - if classdef and classdef.about_attribute(attr) is not None: - return True - return False - - def later(self, gen): - self.latercode.append((gen, self.debugstack)) - - def nameof_instance(self, instance): - name = self.uniquename('ginst_' + instance.__class__.__name__) - cls = self.nameof(instance.__class__) - def initinstance(): - content = instance.__dict__.items() - content.sort() - for key, value in content: - if self.should_translate_attr(instance, key): - yield 'space.setattr(%s, %s, %s)' % ( - name, self.nameof(key), self.nameof(value)) - if isinstance(instance, Exception): - # specialcase for exception instances: wrap them directly - self.initcode.append('_ins = %s()\n' - 'm.%s = space.wrap(_ins)' % ( - instance.__class__.__name__, name)) - else: - # this seems to hardly work with the faked stuff - self.initcode.append('from types import InstanceType') - self.initcode.append('w_InstanceType = space.wrap(InstanceType)') - self.initcode.append('_tup = space.newtuple([%s])\n' - 'm.%s = space.call(w_InstanceType, _tup)' % ( - cls, name)) - self.later(initinstance()) - return name - - def nameof_builtin_function_or_method(self, func): - if func.__self__ is None: - # builtin function - if hasattr(self.space, func.__name__): - return "space.%s" % func.__name__ - # where does it come from? Python2.2 doesn't have func.__module__ - for modname, module in sys.modules.items(): - if hasattr(module, '__file__'): - if (module.__file__.endswith('.py') or - module.__file__.endswith('.pyc') or - module.__file__.endswith('.pyo')): - continue # skip non-builtin modules - if func is getattr(module, func.__name__, None): - break - else: - raise Exception, '%r not found in any built-in module' % (func,) - name = self.uniquename('gbltin_' + func.__name__) - if modname == '__builtin__': - self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( - name, self.nameof(func.__name__))) - else: - self.initcode.append('m.%s = space.getattr(%s, %s)' % ( - name, self.nameof(module), self.nameof(func.__name__))) - else: - # builtin (bound) method - name = self.uniquename('gbltinmethod_' + func.__name__) - self.initcode.append('m.%s = space.getattr(%s, %s)' % ( - name, self.nameof(func.__self__), self.nameof(func.__name__))) - return name - - def nameof_classobj(self, cls): - if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): - raise Exception, "%r should never be reached" % (cls,) - - metaclass = "space.w_type" - name = self.uniquename('gcls_' + cls.__name__) - if issubclass(cls, Exception): - if cls.__module__ == 'exceptions': - if hasattr(self.space, "w_%s" % cls.__name__): - return 'space.w_%s'%cls.__name__ - else: - self.initcode.append('m.%s = space.wrap(%s)' % ( - name, cls.__name__)) - return name - #else: - # # exceptions must be old-style classes (grr!) - # metaclass = "&PyClass_Type" - # For the moment, use old-style classes exactly when the - # pypy source uses old-style classes, to avoid strange problems. - if not isinstance(cls, type): - assert type(cls) is type(Exception) - # self.initcode.append("import types\n" - # "m.classtype = space.wrap(types.ClassType)\n") - # metaclass = "m.classtype" - # XXX I cannot instantiate these. - # XXX using type instead, since we still inherit from exception - # XXX what is the future of classes in pypy? - - basenames = [self.nameof(base) for base in cls.__bases__] - def initclassobj(): - content = cls.__dict__.items() - content.sort() - for key, value in content: - if key.startswith('__'): - if key in ['__module__', '__doc__', '__dict__', - '__weakref__', '__repr__', '__metaclass__']: - continue - # XXX some __NAMES__ are important... nicer solution sought - #raise Exception, "unexpected name %r in class %s"%(key, cls) - - # redirect value through class interface, in order to - # get methods instead of functions. - value = getattr(cls, key) - - if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: - print "skipped staticmethod:", value - continue - if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: - print "skippedfunction:", value - continue - - yield 'space.setattr(%s, %s, %s)' % ( - name, self.nameof(key), self.nameof(value)) - - baseargs = ", ".join(basenames) - self.initcode.append('_dic = space.newdict([])\n' - '_bases = space.newtuple([%(bases)s])\n' - '_args = space.newtuple([%(name)s, _bases, _dic])\n' - 'm.%(klass)s = space.call(%(meta)s, _args)' - % {"bases": baseargs, - "klass": name, - "name" : self.nameof(cls.__name__), - "meta" : metaclass} ) - - self.later(initclassobj()) - return name - - nameof_class = nameof_classobj # for Python 2.2 - - typename_mapping = { - object: 'space.w_object', - int: 'space.w_int', - long: 'space.w_long', - bool: 'space.w_bool', - list: 'space.w_list', - tuple: 'space.w_tuple', - dict: 'space.w_dict', - str: 'space.w_str', - float: 'space.w_float', - type(Exception()): 'space.wrap(types.InstanceType)', - type: 'space.w_type', - complex:'space.wrap(types.ComplexType)', - unicode:'space.w_unicode', - file: 'space.wrap(file)', - type(None): 'space.wrap(types.NoneType)', - CodeType: 'space.wrap(types.CodeType)', - - ##r_int: 'space.w_int', - ##r_uint: 'space.w_int', - - # XXX we leak 5 references here, but that's the least of the - # problems with this section of code - # type 'builtin_function_or_method': - type(len): 'space.wrap(types.FunctionType)', - # type 'method_descriptor': - # XXX small problem here: - # XXX with space.eval, we get - # XXX but with wrap, we get - type(list.append): 'eval_helper(space, "list.append")', - # type 'wrapper_descriptor': - type(type(None).__repr__): 'eval_helper(space, ".type(None).__repr__")', - # type 'getset_descriptor': - # XXX here we get , - # while eval gives us - type(type.__dict__['__dict__']): 'eval_helper(space,'\ - ' "type(type.__dict__[\'__dict__\'])")', - # type 'member_descriptor': - # XXX this does not work in eval! - # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", - # XXX there seems to be no working support for member descriptors ??? - type(type.__dict__['__basicsize__']): "space.wrap(type(type.__dict__['__basicsize__']))", - } - - def nameof_type(self, cls): - if cls in self.typename_mapping: - return self.typename_mapping[cls] - assert cls.__module__ != '__builtin__', \ - "built-in class %r not found in typename_mapping" % (cls,) - return self.nameof_classobj(cls) - - def nameof_tuple(self, tup): - name = self.uniquename('g%dtuple' % len(tup)) - args = [self.nameof(x) for x in tup] - args = ', '.join(args) - self.initcode.append('m.%s = space.newtuple([%s])' % (name, args)) - return name - - def nameof_list(self, lis): - name = self.uniquename('g%dlist' % len(lis)) - def initlist(): - for i in range(len(lis)): - item = self.nameof(lis[i]) - yield 'space.setitem(%s, %s, %s);' % ( - name, self.nameof(i), self.nameof(item)) - self.initcode.append('m.%s = space.newlist(%s)' % (name, self.nameof(0))) - self.initcode.append('m.%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) - self.later(initlist()) - return name - - def nameof_dict(self, dic): - assert dic is not __builtins__ - assert '__builtins__' not in dic, 'Seems to be the globals of %s' % ( - dic.get('__name__', '?'),) - name = self.uniquename('g%ddict' % len(dic)) - def initdict(): - for k in dic: - yield ('space.setitem(%s, %s, %s)'%( - name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('m.%s = space.newdict([])' % (name,)) - self.later(initdict()) - return name - - # strange prebuilt instances below, don't look too closely - # XXX oh well. - def nameof_member_descriptor(self, md): - name = self.uniquename('gdescriptor_%s_%s' % ( - md.__objclass__.__name__, md.__name__)) - cls = self.nameof(md.__objclass__) - # do I need to take the dict and then getitem??? - self.initcode.append('m.%s = space.getattr(%s, %s)' % - (name, cls, self.nameof(md.__name__))) - return name - nameof_getset_descriptor = nameof_member_descriptor - nameof_method_descriptor = nameof_member_descriptor - nameof_wrapper_descriptor = nameof_member_descriptor - - def nameof_file(self, fil): - if fil is sys.stdin: - return 'PySys_GetObject("stdin")' - if fil is sys.stdout: - return 'PySys_GetObject("stdout")' - if fil is sys.stderr: - return 'PySys_GetObject("stderr")' - raise Exception, 'Cannot translate an already-open file: %r' % (fil,) - - def gen_source(self, fname, ftmpname=None): - self.fname = fname - self.ftmpname = ftmpname - - # generate unordered source file, first. - # I prefer this over ordering everything in memory. - fname = self.fname - if self.ftmpname: - fname = self.ftmpname - f = file(fname, "w") - # generate ordered source file - try: - self.f = f - self.gen_source_temp() - finally: - f.close() - - def copyfile(source, target): - file(target, "w").write(file(source).read()) - - def order_sections(fname): - sep = "\n##SECTION##\n" - txt = file(fname).read() - pieces = txt.split(sep) - prelude = pieces.pop(0) - postlude = pieces.pop() - dic = {} - while pieces: - func = pieces.pop() - head = pieces.pop() - key = makekey(head, len(pieces)) - dic[key] = head + sep + func - lis = dic.items() - lis.sort() - lis = [prelude] + [func for head, func in lis] + [postlude] - txt = sep.join(lis) - file(fname, "w").write(txt) - - def makekey(txt, uniqueno): - dic = {} - for line in txt.split("\n"): - ign, name, value = line.split(None, 2) - dic[name] = eval(value) - key = dic["filename"], dic["firstlineno"], uniqueno - return key - - order_sections(fname) - if self.ftmpname: - copyfile(self.ftmpname, self.fname) - - def gen_source_temp(self): - f = self.f - info = { - 'modname': self.modname, - 'entrypointname': self.trans_funcname( - self.translator.functions[0].__name__), - 'entrypoint': self.nameof(self.translator.functions[0]), - } - # header - print >> f, self.RPY_HEADER - - # function implementations - while self.pendingfunctions: - func = self.pendingfunctions.pop() - self.currentfunc = func - self.gen_rpyfunction(func) - # collect more of the latercode after each function - while self.latercode: - gen, self.debugstack = self.latercode.pop() - #self.initcode.extend(gen) -- eats TypeError! bad CPython! - for line in gen: - self.initcode.append(line) - self.debugstack = () - self.gen_global_declarations() - - # set the final splitter - print >> f, "##SECTION##" - # footer - print >> f, self.RPY_INIT_HEADER % info - for codelines in self.initcode: - for codeline in codelines.split("\n"): - print >> f, " %s" % codeline - print >> f, self.RPY_INIT_FOOTER % info - f.close() - - def gen_global_declarations(self): - g = self.globaldecl - if g: - f = self.f - print >> f, '# global declaration%s' % ('s'*(len(g)>1)) - for line in g: - print >> f, line - print >> f - del g[:] - g = self.globalobjects - for name in g: - pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) - del g[:] - - def gen_rpyfunction(self, func): - - f = self.f - print >> f, "##SECTION##" # simple to split, afterwards - print >> f, ("## filename %r\n" - "## function %r\n" - "## firstlineno %d") % ( - func.func_code.co_filename, - func.func_code.co_name, - func.func_code.co_firstlineno) - print >> f, "##SECTION##" - locals = {} - body = list(self.rpyfunction_body(func, locals)) - name_of_defaults = [self.nameof(x, debug=('Default argument of', func)) - for x in (func.func_defaults or ())] - self.gen_global_declarations() - - # print header - cname = self.nameof(func) - assert cname.startswith('gfunc_') - f_name = 'f_' + cname[6:] - - # collect all the local variables - graph = self.translator.getflowgraph(func) - localslst = [] - def visit(node): - if isinstance(node, Block): - localslst.extend(node.getvariables()) - traverse(visit, graph) - localnames = [self.expr(a, locals) for a in uniqueitems(localslst)] - - # collect all the arguments - if func.func_code.co_flags & CO_VARARGS: - vararg = graph.getargs()[-1] - positional_args = graph.getargs()[:-1] - else: - vararg = None - positional_args = graph.getargs() - min_number_of_args = len(positional_args) - len(name_of_defaults) - - fast_args = [self.expr(a, locals) for a in positional_args] - if vararg is not None: - fast_args.append(self.expr(vararg, locals)) - fast_name = 'fast' + f_name - - fast_set = dict(zip(fast_args, fast_args)) - - # create function declaration - name = func.__name__ - argstr = ", ".join(fast_args) - fast_function_header = ('def %s(space, %s):' - % (fast_name, argstr)) - - print >> f, 'def %s(space, *args_w):' % (f_name,) - kwlist = ['"%s"' % name for name in - func.func_code.co_varnames[:func.func_code.co_argcount]] - print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) - - # argument unpacking - if vararg is not None: - varname = self.expr(vararg, locals) - lenargs = len(positional_args) - print >> f, ' %s = space.newtuple(list(args_w[%d:]))' % ( - varname, lenargs) - print >> f, ' _args_w = args_w[:%d]' % (lenargs,) - else: - print >> f, ' _args_w = args_w' - varname = None - - def tupstr(seq): - if len(seq) == 1: - fmt = '%s,' - else: - fmt = '%s' - return fmt % ', '.join(seq) - - print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) - - theargs = [arg for arg in fast_args if arg != varname] - txt = ('from pypy.translator.genrpy import PyArg_ParseMini\n' - 'm.PyArg_ParseMini = PyArg_ParseMini\n' - 'from pypy.interpreter.error import OperationError\n' - 'm.OperationError = OperationError') - self.initcode.append(txt) - print >> f, ' funcname = "%s"' % func.__name__ - if theargs: - txt = ' %s = PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' - print >>f, txt % (tupstr(theargs), - min_number_of_args, len(positional_args)) - else: - txt = ' PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' - print >>f, txt % (min_number_of_args, len(positional_args)) - print >> f, ' return %s(space, %s)' % (fast_name, ', '.join(fast_args)) - print >> f - - print >> f, fast_function_header - - fast_locals = [arg for arg in localnames if arg not in fast_set] - if fast_locals: - print >> f - for line in self.large_initialize(fast_locals): - print >> f, " %s" % line - print >> f - # generate an incref for each input argument - # skipped - - # print the body - for line in body: - print >> f, line - print >> f - - # print the PyMethodDef - # skipped - - if not self.translator.frozen: - # this is only to keep the RAM consumption under control - del self.translator.flowgraphs[func] - Variable.instances.clear() - - def rpyfunction_body(self, func, localvars): - try: - graph = self.translator.getflowgraph(func) - except Exception, e: - print 20*"*", e - print func - raise - # not needed, we use tuple assignment! - # remove_direct_loops(graph) - checkgraph(graph) - - allblocks = [] - - f = self.f - t = self.translator - #t.simplify(func) - graph = t.getflowgraph(func) - - start = graph.startblock - allblocks = ordered_blocks(graph) - nblocks = len(allblocks) - - blocknum = {} - for block in allblocks: - blocknum[block] = len(blocknum)+1 - - yield " goto = %d # startblock" % blocknum[start] - yield " while True:" - - def render_block(block): - catch_exception = block.exitswitch == Constant(last_exception) - regular_op = len(block.operations) - catch_exception - # render all but maybe the last op - for op in block.operations[:regular_op]: - for line in self.oper(op, localvars).split("\n"): - yield "%s" % line - # render the last op if it is exception handled - for op in block.operations[regular_op:]: - yield "try:" - for line in self.oper(op, localvars).split("\n"): - yield " %s" % line - - if len(block.exits) == 0: - if len(block.inputargs) == 2: # exc_cls, exc_value - # exceptional return block - exc_cls = self.expr(block.inputargs[0], localvars) - exc_val = self.expr(block.inputargs[1], localvars) - yield "raise OperationError(%s, %s)" % (exc_cls, exc_val) - else: - # regular return block - retval = self.expr(block.inputargs[0], localvars) - yield "return %s" % retval - return - elif block.exitswitch is None: - # single-exit block - assert len(block.exits) == 1 - for op in self.gen_link(block.exits[0], localvars, blocknum, block): - yield "%s" % op - elif catch_exception: - # block catching the exceptions raised by its last operation - # we handle the non-exceptional case first - link = block.exits[0] - assert link.exitcase is None - for op in self.gen_link(link, localvars, blocknum, block): - yield " %s" % op - # we must catch the exception raised by the last operation, - # which goes to the last err%d_%d label written above. - # Since we only have OperationError, we need to select: - yield "except OperationError, e:" - q = "if" - for link in block.exits[1:]: - assert issubclass(link.exitcase, Exception) - # Exeption classes come unwrapped in link.exitcase - yield " %s space.is_true(space.issubtype(e.w_type, %s)):" % (q, - self.nameof(link.exitcase)) - q = "elif" - for op in self.gen_link(link, localvars, blocknum, block, { - Constant(last_exception): 'e.w_type', - Constant(last_exc_value): 'e.w_value'}): - yield " %s" % op - yield " else:raise # unhandled case, should not happen" - else: - # block ending in a switch on a value - exits = list(block.exits) - if len(exits) == 2 and ( - exits[0].exitcase is False and exits[1].exitcase is True): - # order these guys like Python does - exits.reverse() - q = "if" - for link in exits[:-1]: - yield "%s %s == %s:" % (q, self.expr(block.exitswitch, - localvars), - link.exitcase) - for op in self.gen_link(link, localvars, blocknum, block): - yield " %s" % op - q = "elif" - link = exits[-1] - yield "else:" - yield " assert %s == %s" % (self.expr(block.exitswitch, - localvars), - link.exitcase) - for op in self.gen_link(exits[-1], localvars, blocknum, block): - yield " %s" % op - - for block in allblocks: - blockno = blocknum[block] - yield "" - yield " if goto == %d:" % blockno - for line in render_block(block): - yield " %s" % line - -# ____________________________________________________________ - - RPY_HEADER = '#!/bin/env python\n# -*- coding: LATIN-1 -*-' - - RPY_SEP = "#*************************************************************" - - RPY_INIT_HEADER = RPY_SEP + ''' - -def init%(modname)s(space): - """NOT_RPYTHON""" - class m: pass # fake module - m.__dict__ = globals() -''' - - RPY_INIT_FOOTER = ''' -# entry point: %(entrypointname)s, %(entrypoint)s) -if __name__ == "__main__": - from pypy.objspace.std import StdObjSpace - space = StdObjSpace() - init%(modname)s(space) - print space.unwrap(space.call( - gfunc_%(entrypointname)s, space.newtuple([]))) -''' - -# a translation table suitable for str.translate() to remove -# non-C characters from an identifier -C_IDENTIFIER = ''.join([(('0' <= chr(i) <= '9' or - 'a' <= chr(i) <= 'z' or - 'A' <= chr(i) <= 'Z') and chr(i) or '_') - for i in range(256)]) - -# temporary arg parsing -# what about keywords? Gateway doesn't support it. -def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): - err = None - if len(args_w) < minargs: - txt = "%s() takes at least %d argument%s (%d given)" - plural = ['s', ''][minargs == 1] - err = (name, minargs, plural, len(args_w)) - if len(args_w) > maxargs: - plural = ['s', ''][maxargs == 1] - if minargs == maxargs: - if minargs == 0: - txt = '%s() takes no arguments (%d given)' - err = (name, len(args_w)) - elif minargs == 1: - txt = '%s() takes exactly %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - else: - txt = '%s() takes at most %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - if err: - w_txt = space.wrap(txt) - w_tup = space.wrap(err) - w_txt = space.mod(w_txt, w_tup) - raise OperationError(space.w_TypeError, w_txt) - - # finally, we create the result ;-) - res_w = args_w + defaults_w[len(args_w) - minargs:] - assert len(res_w) == maxargs - return res_w -# _____________________________________________________________________ - -## this should go into some test file - -def somefunc(arg): - pass - -def f(a,b): -## print "start" - a = [] - a.append(3) - for i in range(3): - pass#print i - if a > b: - try: - if b == 123: - raise ValueError - elif b == 321: - raise IndexError - return 123 - except ValueError: - raise TypeError - else: - dummy = somefunc(23) - return 42 - -class TestClass:pass - -def ff(a, b, c=3,*rest): - try: - try: - if rest: - raise SystemError, 42 - return a+b - finally: - a = 7 - if rest: - return len(rest),c - except TypeError: - print "eek" - -glob = 100 -def fff(): - global glob - return 42+glob - -def app_mod__String_ANY(format, values): - import _formatting - if isinstance(values, tuple): - return _formatting.format(format, values, None) - else: - if hasattr(values, 'keys'): - return _formatting.format(format, (values,), values) - else: - return _formatting.format(format, (values,), None) - -def app_str_decode__String_ANY_ANY(str, encoding=None, errors=None): - if encoding is None and errors is None: - return unicode(str) - elif errors is None: - return unicode(str, encoding) - else: - return unicode(str, encoding, errors) - - -def test_md5(): - #import md5 - # how do I avoid the builtin module? - from pypy.appspace import md5 - digest = md5.new("hello").hexdigest() - return digest - -def test_mod(): - return app_mod__String_ANY("-%s-", ["hallo"]) - -def test_join(): - return " ".join(["hi", "there"]) - -# cannot nest local classes, yet -# this appears to be a problem in flow space. -class AnIterClass(object): - def __init__(self): - self.lis = [c for c in "test"] - def next(self): - if self.lis: - return self.lis.pop() - raise StopIteration - def __iter__(self): - return self - -def test_iter(): - res = [] - for i in "hallo": - res.append(i) - for i in AnIterClass(): - res.append(i) - return res - -def test_strutil(): - from pypy.objspace.std import strutil - return (strutil.string_to_int("42"), - strutil.string_to_long("12345678901234567890")) - -def test_struct(): - from pypy.appspace import struct - import struct as stru - res1 = stru.pack('f',1.23), struct.pack('f',1.23) - res2 = struct.unpack('f', struct.pack('f',1.23)) - return res1, res2 - -def all_entries(): - res = [func() for func in entry_points[:-1]] - return res - -entry_points = (lambda: f(2, 3), - lambda: ff(2, 3, 5), - fff, - lambda: app_str_decode__String_ANY_ANY("hugo"), - test_mod, - test_md5, - test_join, - test_iter, - test_strutil, - test_struct, - all_entries) -entry_point = entry_points[-2] - -if __name__ == "__main__": - import os, sys - from pypy.interpreter import autopath - srcdir = os.path.dirname(autopath.pypydir) - appdir = os.path.join(autopath.pypydir, 'appspace') - - if appdir not in sys.path: - sys.path.insert(0, appdir) - - t = Translator(entry_point, verbose=False, simplifying=True) - gen = GenRpy(t) - gen.use_fast_call = True - import pypy.appspace.generated as tmp - pth = os.path.dirname(tmp.__file__) - ftmpname = "d:/tmp/look.py" - fname = os.path.join(pth, gen.modname+".py") - gen.gen_source(fname, ftmpname) - - #t.simplify() - #t.view() - # debugging - graph = t.getflowgraph() - ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab - -def crazy_test(): - """ this thingy is generating the whole interpreter in itself""" - # but doesn't work, my goto's give a problem for flow space - dic = {"__builtins__": __builtins__, "__name__": "__main__"} - execfile("d:/tmp/look.py", dic) - - def test(): - f_ff(space, 2, 3) - test = type(test)(test.func_code, dic) - - t = Translator(test, verbose=False, simplifying=True) - gen = GenRpy(t) - gen.gen_source("d:/tmp/look2.py") From arigo at codespeak.net Wed Jan 12 17:39:41 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 12 Jan 2005 17:39:41 +0100 (MET) Subject: [pypy-svn] r8239 - pypy/trunk/src/pypy/translator/tool Message-ID: <20050112163941.5816A27BDE@code1.codespeak.net> Author: arigo Date: Wed Jan 12 17:39:41 2005 New Revision: 8239 Modified: pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py Log: Updated make_module_from_c() to save/restore os.environ along the lines of py/misc/buildcmodule. These two should be unified at some point, but the PyPy version is a bit messy and uses various strange tricks... Modified: pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py ============================================================================== --- pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py (original) +++ pypy/trunk/src/pypy/translator/tool/buildpyxmodule.py Wed Jan 12 17:39:41 2005 @@ -70,16 +70,22 @@ else: from distutils.core import setup from distutils.extension import Extension - setup( - name = "testmodules", - ext_modules=[ - Extension(modname, [str(cfile)], - include_dirs=include_dirs) - ], - script_name = 'setup.py', - script_args = ['-q', 'build_ext', '--inplace'] - #script_args = ['build_ext', '--inplace'] - ) + saved_environ = os.environ.items() + try: + setup( + name = "testmodules", + ext_modules=[ + Extension(modname, [str(cfile)], + include_dirs=include_dirs) + ], + script_name = 'setup.py', + script_args = ['-q', 'build_ext', '--inplace'] + #script_args = ['build_ext', '--inplace'] + ) + finally: + for key, value in saved_environ: + if os.environ.get(key) != value: + os.environ[key] = value finally: foutput, foutput = c.done() except: From arigo at codespeak.net Wed Jan 12 18:42:40 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 12 Jan 2005 18:42:40 +0100 (MET) Subject: [pypy-svn] r8241 - pypy/trunk/src/pypy/translator Message-ID: <20050112174240.25F6C27BDE@code1.codespeak.net> Author: arigo Date: Wed Jan 12 18:42:39 2005 New Revision: 8241 Modified: pypy/trunk/src/pypy/translator/genc.h Log: PyInt_GetMax() returns a long, not an int... The largest integer is INT_MAX. Modified: pypy/trunk/src/pypy/translator/genc.h ============================================================================== --- pypy/trunk/src/pypy/translator/genc.h (original) +++ pypy/trunk/src/pypy/translator/genc.h Wed Jan 12 18:42:39 2005 @@ -121,7 +121,7 @@ #define OP_GETSLICE(x,y,z,r,err) { \ int __y = (y == Py_None) ? 0 : AS_LONG(y); \ - int __z = (z == Py_None) ? PyInt_GetMax() : AS_LONG(z); \ + int __z = (z == Py_None) ? INT_MAX : AS_LONG(z); \ FAIL_IF_ERR(r,err) \ if (!(r=PySequence_GetSlice(x, __y, __z))) FAIL(err) \ } From arigo at codespeak.net Wed Jan 12 18:53:22 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 12 Jan 2005 18:53:22 +0100 (MET) Subject: [pypy-svn] r8242 - pypy/trunk/src/pypy/translator/test Message-ID: <20050112175322.5BF6E27BDE@code1.codespeak.net> Author: arigo Date: Wed Jan 12 18:53:22 2005 New Revision: 8242 Modified: pypy/trunk/src/pypy/translator/test/test_ctrans.py Log: A test showing another bug on amd64. Modified: pypy/trunk/src/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/trunk/src/pypy/translator/test/test_ctrans.py (original) +++ pypy/trunk/src/pypy/translator/test/test_ctrans.py Wed Jan 12 18:53:22 2005 @@ -273,3 +273,13 @@ 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=int): + 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') From arigo at codespeak.net Wed Jan 12 19:08:17 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 12 Jan 2005 19:08:17 +0100 (MET) Subject: [pypy-svn] r8244 - pypy/trunk/src/pypy/translator Message-ID: <20050112180817.E36DC27BDE@code1.codespeak.net> Author: arigo Date: Wed Jan 12 19:08:17 2005 New Revision: 8244 Modified: pypy/trunk/src/pypy/translator/genc.h Log: Proper handling of slice indices. (Check if _PyEval_SliceIndex exists in Python 2.2?) Modified: pypy/trunk/src/pypy/translator/genc.h ============================================================================== --- pypy/trunk/src/pypy/translator/genc.h (original) +++ pypy/trunk/src/pypy/translator/genc.h Wed Jan 12 19:08:17 2005 @@ -111,24 +111,20 @@ #define OP_NEWSLICE(x,y,z,r,err) if (!(r=PySlice_New(x,y,z))) FAIL(err) -#define AS_LONG(x) PyInt_AsLong(x) - -#define FAIL_IF_ERR(r,err) \ - if (PyErr_Occurred()) { \ - r = NULL; \ - FAIL(err) \ - } - -#define OP_GETSLICE(x,y,z,r,err) { \ - int __y = (y == Py_None) ? 0 : AS_LONG(y); \ - int __z = (z == Py_None) ? INT_MAX : AS_LONG(z); \ - FAIL_IF_ERR(r,err) \ - if (!(r=PySequence_GetSlice(x, __y, __z))) FAIL(err) \ +#define OP_GETSLICE(x,y,z,r,err) { \ + PyObject *__yo = y, *__zo = z; \ + int __y = 0, __z = INT_MAX; \ + if (__yo == Py_None) __yo = NULL; \ + if (__zo == Py_None) __zo = NULL; \ + if (!_PyEval_SliceIndex(__yo, &__y) || \ + !_PyEval_SliceIndex(__zo, &__z) || \ + !(r=PySequence_GetSlice(x, __y, __z))) FAIL(err) \ } #define OP_ALLOC_AND_SET(x,y,r,err) { \ - int __i, __x = AS_LONG(x); \ - FAIL_IF_ERR(r,err) \ + /* XXX check for long/int overflow */ \ + int __i, __x = PyInt_AsLong(x); \ + if (PyErr_Occurred()) FAIL(err) \ if (!(r = PyList_New(__x))) FAIL(err) \ for (__i=0; __i<__x; __i++) { \ Py_INCREF(y); \ From mwh at codespeak.net Thu Jan 13 15:54:06 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Thu, 13 Jan 2005 15:54:06 +0100 (MET) Subject: [pypy-svn] r8256 - pypy/trunk/src/pypy/objspace/std Message-ID: <20050113145406.6A41327B84@code1.codespeak.net> Author: mwh Date: Thu Jan 13 15:54:06 2005 New Revision: 8256 Modified: pypy/trunk/src/pypy/objspace/std/multimethod.py Log: I must have found this useful at some point: a __repr__ method for BoundMultimethods. Modified: pypy/trunk/src/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/multimethod.py (original) +++ pypy/trunk/src/pypy/objspace/std/multimethod.py Thu Jan 13 15:54:06 2005 @@ -499,6 +499,9 @@ def is_empty(self): return self.multimethod.is_empty() + def __repr__(self): + return ''%(self.multimethod,) + class error(Exception): "Thrown to you when you do something wrong with multimethods." From arigo at codespeak.net Thu Jan 13 16:25:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 13 Jan 2005 16:25:13 +0100 (MET) Subject: [pypy-svn] r8257 - pypy/trunk/src/pypy/objspace/test Message-ID: <20050113152513.1109A27B84@code1.codespeak.net> Author: arigo Date: Thu Jan 13 16:25:12 2005 New Revision: 8257 Modified: pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py Log: Minor change to work around Python 2.5's peephole optimizer. Modified: pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py ============================================================================== --- pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py (original) +++ pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py Thu Jan 13 16:25:12 2005 @@ -57,7 +57,8 @@ def test_trace_oneop(self): def app_f(): - 1 + 1 + x = 1 + x + 1 res = self.perform_trace(app_f) disresult = pydis.pydis(app_f) uw = self.space.unwrap From arigo at codespeak.net Thu Jan 13 16:26:19 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 13 Jan 2005 16:26:19 +0100 (MET) Subject: [pypy-svn] r8258 - in pypy/trunk/src/pypy: interpreter objspace Message-ID: <20050113152619.3C9C827B84@code1.codespeak.net> Author: arigo Date: Thu Jan 13 16:26:19 2005 New Revision: 8258 Modified: pypy/trunk/src/pypy/interpreter/gateway.py pypy/trunk/src/pypy/objspace/descroperation.py Log: Got rid of performance_shortcut_call() methods of BuiltinCode. It was found that just special-casing Function at the proper place was enough to get the same performance improvement. Modified: pypy/trunk/src/pypy/interpreter/gateway.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/gateway.py (original) +++ pypy/trunk/src/pypy/interpreter/gateway.py Thu Jan 13 16:26:19 2005 @@ -92,49 +92,6 @@ def getdocstring(self): return self.docstring - def performance_shortcut_call(self, space, args): - # this shortcut is only used for performance reasons - args_w, kwds_w = args.unpack() - if self.generalargs or kwds_w: - return None - if not (self.minargs <= len(args_w) <= self.maxargs): - return None - if self.ismethod: - if not args_w: - return None - args_w = list(args_w) - args_w[0] = space.unwrap(args_w[0]) - if self.spacearg: - w_result = self.func(space, *args_w) - else: - w_result = self.func(*args_w) - if w_result is None: - w_result = space.w_None - return w_result - - def performance_shortcut_call_meth(self, space, w_obj, args): - # this shortcut is only used for performance reasons - if self.generalargs: - if self.ismethod and not self.spacearg and len(self.sig[0]) == 1: - w_result = self.func(space.unwrap(w_obj), args) - else: - return None - else: - args_w, kwds_w = args.unpack() - if kwds_w: - return None - if not (self.minargs <= 1+len(args_w) <= self.maxargs): - return None - if self.ismethod: - w_obj = space.unwrap(w_obj) # abuse name w_obj - if self.spacearg: - w_result = self.func(space, w_obj, *args_w) - else: - w_result = self.func(w_obj, *args_w) - if w_result is None: - w_result = space.w_None - return w_result - class BuiltinFrame(eval.Frame): "Frame emulation for BuiltinCode." Modified: pypy/trunk/src/pypy/objspace/descroperation.py ============================================================================== --- pypy/trunk/src/pypy/objspace/descroperation.py (original) +++ pypy/trunk/src/pypy/objspace/descroperation.py Thu Jan 13 16:26:19 2005 @@ -62,14 +62,8 @@ def get_and_call_args(space, w_descr, w_obj, args): descr = space.unwrap_builtin(w_descr) - # some special cases to avoid infinite recursion + # a special case for performance and to avoid infinite recursion if isinstance(descr, Function): - if isinstance(descr.code, BuiltinCode): - # this sub-special case is ONLY for performance reasons - w_result = descr.code.performance_shortcut_call_meth( - space, w_obj, args) - if w_result is not None: - return w_result return descr.call_args(args.prepend(w_obj)) else: w_impl = space.get(w_descr, w_obj) @@ -83,11 +77,9 @@ return w_obj # hook for hack by TrivialObjSpace def call_args(space, w_obj, args): - if type(w_obj) is Function and isinstance(w_obj.code, BuiltinCode): - # this special case is ONLY for performance reasons - w_result = w_obj.code.performance_shortcut_call(space, args) - if w_result is not None: - return w_result + # a special case for performance + if type(w_obj) is Function: + return w_obj.call_args(args) w_descr = space.lookup(w_obj, '__call__') if w_descr is None: raise OperationError( From pedronis at codespeak.net Thu Jan 13 18:48:07 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 13 Jan 2005 18:48:07 +0100 (MET) Subject: [pypy-svn] r8261 - in pypy/trunk/src/pypy: interpreter interpreter/test objspace/std Message-ID: <20050113174807.028E927B84@code1.codespeak.net> Author: pedronis Date: Thu Jan 13 18:48:07 2005 New Revision: 8261 Modified: pypy/trunk/src/pypy/interpreter/eval.py pypy/trunk/src/pypy/interpreter/gateway.py pypy/trunk/src/pypy/interpreter/pyframe.py pypy/trunk/src/pypy/interpreter/test/test_eval.py pypy/trunk/src/pypy/objspace/std/fake.py pypy/trunk/src/pypy/objspace/std/stdtypedef.py Log: preparatory refactoring for specification bases typed arg-unwrapping for builtin functions. Frame setfastscope getfastscope are abstract. PyFrame reintroduce the usual behavior with fastlocals_w. Constructed subclasses of BuiltinFrame will be able to do the typed unwrapping in their setfastscope. Modified: pypy/trunk/src/pypy/interpreter/eval.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/eval.py (original) +++ pypy/trunk/src/pypy/interpreter/eval.py Thu Jan 13 18:48:07 2005 @@ -65,7 +65,7 @@ self.w_locals = None # wrapped dict of locals if numlocals < 0: # compute the minimal size based on arguments numlocals = len(code.getvarnames()) - self.fastlocals_w = [UNDEFINED]*numlocals # flat list of wrapped locals + self.numlocals = numlocals def resume(self): "Resume the execution of the frame from its current state." @@ -100,22 +100,20 @@ self.locals2fast() def getfastscope(self): - "Get the fast locals as a list." - return self.fastlocals_w + "Abstract. Get the fast locals as a list." + raise TypeError, "abstract" def setfastscope(self, scope_w): - """Initialize the fast locals from a list of values, + """Abstract. Initialize the fast locals from a list of values, where the order is according to self.code.signature().""" - if len(scope_w) > len(self.fastlocals_w): - raise ValueError, "new fastscope is longer than the allocated area" - self.fastlocals_w[:len(scope_w)] = scope_w + raise TypeError, "abstract" def fast2locals(self): # Copy values from self.fastlocals_w to self.w_locals if self.w_locals is None: self.w_locals = self.space.newdict([]) varnames = self.code.getvarnames() - for name, w_value in zip(varnames, self.fastlocals_w): + for name, w_value in zip(varnames, self.getfastscope()): if w_value is not UNDEFINED: w_name = self.space.wrap(name) self.space.setitem(self.w_locals, w_name, w_value) @@ -124,7 +122,10 @@ # Copy values from self.w_locals to self.fastlocals_w assert self.w_locals is not None varnames = self.code.getvarnames() - for name, i in zip(varnames, range(len(self.fastlocals_w))): + + new_fastlocals_w = [UNDEFINED]*self.numlocals + + for name, i in zip(varnames, range(self.numlocals)): w_name = self.space.wrap(varnames[i]) try: w_value = self.space.getitem(self.w_locals, w_name) @@ -132,4 +133,6 @@ if not e.match(self.space, self.space.w_KeyError): raise else: - self.fastlocals_w[i] = w_value + new_fastlocals_w[i] = w_value + + self.setfastscope(new_fastlocals_w) Modified: pypy/trunk/src/pypy/interpreter/gateway.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/gateway.py (original) +++ pypy/trunk/src/pypy/interpreter/gateway.py Thu Jan 13 18:48:07 2005 @@ -99,8 +99,8 @@ # Initialization of locals is already done by the time run() is called, # via the interface defined in eval.Frame. - def run(self): - argarray = list(self.fastlocals_w) + def setfastscope(self, scope_w): + argarray = list(scope_w) if self.code.generalargs: w_kwds = argarray.pop() w_args = argarray.pop() @@ -110,6 +110,14 @@ argarray += self.space.unpacktuple(w_args) if self.code.ismethod: argarray[0] = self.space.unwrap(argarray[0]) + self.argarray = argarray + + def getfastscope(self): + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a BuiltinFrame")) + + def run(self): + argarray = self.argarray if self.code.spacearg: w_result = self.code.func(self.space, *argarray) else: Modified: pypy/trunk/src/pypy/interpreter/pyframe.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/pyframe.py (original) +++ pypy/trunk/src/pypy/interpreter/pyframe.py Thu Jan 13 18:48:07 2005 @@ -34,6 +34,19 @@ if code.dictscope_needed(): self.w_locals = space.newdict([]) # set to None by Frame.__init__ + self.fastlocals_w = [eval.UNDEFINED]*self.numlocals + + def getfastscope(self): + "Get the fast locals as a list." + return self.fastlocals_w + + def setfastscope(self, scope_w): + """Initialize the fast locals from a list of values, + where the order is according to self.code.signature().""" + if len(scope_w) > len(self.fastlocals_w): + raise ValueError, "new fastscope is longer than the allocated area" + self.fastlocals_w[:len(scope_w)] = scope_w + def getclosure(self): return None Modified: pypy/trunk/src/pypy/interpreter/test/test_eval.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/test/test_eval.py (original) +++ pypy/trunk/src/pypy/interpreter/test/test_eval.py Thu Jan 13 18:48:07 2005 @@ -9,7 +9,21 @@ def c(x, y, *args): pass code = PyCode()._from_code(c.func_code) - self.f = Frame(self.space, code, numlocals=5) + + class ConcreteFastscopeFrame(Frame): + + def __init__(self, space, code, numlocals): + Frame.__init__(self, space, code, numlocals=numlocals) + self.fastlocals_w = [UNDEFINED] * self.numlocals + + def setfastscope(self, scope_w): + self.fastlocals_w = scope_w + + def getfastscope(self): + return self.fastlocals_w + + self.f = ConcreteFastscopeFrame(self.space, code, numlocals=5) + def test_fast2locals(self): space = self.space Modified: pypy/trunk/src/pypy/objspace/std/fake.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/fake.py (original) +++ pypy/trunk/src/pypy/objspace/std/fake.py Thu Jan 13 18:48:07 2005 @@ -88,16 +88,22 @@ return [], 'args', 'kwds' class CPythonFakeFrame(eval.Frame): - def run(self): - fn = self.code.cpy_callable - w_args, w_kwds = self.fastlocals_w + + def setfastscope(self, scope_w): + w_args, w_kwds = scope_w try: - unwrappedargs = self.space.unwrap(w_args) - unwrappedkwds = self.space.unwrap(w_kwds) + self.unwrappedargs = self.space.unwrap(w_args) + self.unwrappedkwds = self.space.unwrap(w_kwds) except UnwrapError, e: raise UnwrapError('calling %s: %s' % (fn, e)) + + def getfastscope(self): + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a CPythonFakeFrame")) + def run(self): + fn = self.code.cpy_callable try: - result = apply(fn, unwrappedargs, unwrappedkwds) + result = apply(fn, self.unwrappedargs, self.unwrappedkwds) except: wrap_exception(self.space) return self.space.wrap(result) Modified: pypy/trunk/src/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/stdtypedef.py (original) +++ pypy/trunk/src/pypy/objspace/std/stdtypedef.py Thu Jan 13 18:48:07 2005 @@ -160,23 +160,29 @@ return self.framecls(space, self) class MmFrame(eval.Frame): + + def setfastscope(self, scope_w): + args = list(scope_w) + args.insert(0, args.pop(self.code.bound_position)) + self.args = args + + def getfastscope(self): + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a MmFrame")) + def run(self): "Call the multimethod, raising a TypeError if not implemented." - args = list(self.fastlocals_w) - args.insert(0, args.pop(self.code.bound_position)) - w_result = self.code.mm(*args) + w_result = self.code.mm(*self.args) # we accept a real None from operations with no return value if w_result is None: w_result = self.space.w_None return w_result -class SpecialMmFrame(eval.Frame): +class SpecialMmFrame(MmFrame): def run(self): "Call the multimethods, possibly returning a NotImplemented." - args = list(self.fastlocals_w) - args.insert(0, args.pop(self.code.bound_position)) try: - return self.code.mm.perform_call(*args) + return self.code.mm.perform_call(*self.args) except FailedToImplement, e: if e.args: raise OperationError(e.args[0], e.args[1]) From pedronis at codespeak.net Fri Jan 14 12:32:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 14 Jan 2005 12:32:47 +0100 (MET) Subject: [pypy-svn] r8266 - pypy/branch/src-typedunwrap Message-ID: <20050114113247.DA10B27B90@code1.codespeak.net> Author: pedronis Date: Fri Jan 14 12:32:47 2005 New Revision: 8266 Added: pypy/branch/src-typedunwrap/ - copied from r8265, pypy/trunk/src/ Log: creating new branch to explore typed unwrapping. From pedronis at codespeak.net Fri Jan 14 17:44:21 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 14 Jan 2005 17:44:21 +0100 (MET) Subject: [pypy-svn] r8276 - in pypy/branch/src-typedunwrap/pypy: interpreter objspace objspace/flow objspace/std objspace/std/test Message-ID: <20050114164421.BB90327BB1@code1.codespeak.net> Author: pedronis Date: Fri Jan 14 17:44:21 2005 New Revision: 8276 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/argument.py pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/interpreter/error.py pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py pypy/branch/src-typedunwrap/pypy/interpreter/function.py pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py pypy/branch/src-typedunwrap/pypy/interpreter/main.py pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/default.py pypy/branch/src-typedunwrap/pypy/objspace/std/intobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stdobjspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stringobject.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: introduced int_w, str_w for ints and strings unwrapping in all object spaces interpreter/ code now uses mostly int_w,str_w and unwrap_builtin (which probably needs a better name) for now unwrap impl keep all of their power. Modified: pypy/branch/src-typedunwrap/pypy/interpreter/argument.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/argument.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/argument.py Fri Jan 14 17:44:21 2005 @@ -30,8 +30,9 @@ space.wrap("the keywords must be " "a dictionary")) for w_key in space.unpackiterable(w_starstararg): - key = space.unwrap(w_key) - if not isinstance(key, str): + try: + key = space.str_w(w_key) + except OperationError: raise OperationError(space.w_TypeError, space.wrap("keywords must be strings")) if key in self.kwds_w: Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Fri Jan 14 17:44:21 2005 @@ -123,7 +123,7 @@ def not_(self, w_obj): return self.wrap(not self.is_true(w_obj)) - def unwrapdefault(self, w_value, default): + def unwrapdefault(self, w_value, default): # xxx if w_value is None or w_value == self.w_None: return default else: @@ -162,7 +162,7 @@ def unpacktuple(self, w_tuple, expected_length=None): """Same as unpackiterable(), but only for tuples. Only use for bootstrapping or performance reasons.""" - tuple_length = self.unwrap(self.len(w_tuple)) + tuple_length = self.int_w(self.len(w_tuple)) if expected_length is not None and tuple_length != expected_length: raise ValueError, "got a tuple of length %d instead of %d" % ( tuple_length, expected_length) @@ -361,6 +361,8 @@ ## Irregular part of the interface: # # wrap(x) -> w_x +# str_w(w_str) -> str +# int_w(w_ival) -> ival # unwrap(w_x) -> x # is_true(w_x) -> True or False # newtuple([w_1, w_2,...]) -> w_tuple Modified: pypy/branch/src-typedunwrap/pypy/interpreter/error.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/error.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/error.py Fri Jan 14 17:44:21 2005 @@ -37,9 +37,9 @@ def errorstr(self, space): "NOT_RPYTHON: The exception class and value, as a string." - exc_type = space.unwrap( + exc_type = space.str_w( space.getattr(self.w_type, space.wrap('__name__'))) - exc_value = space.unwrap(space.str(self.w_value)) + exc_value = space.str_w(space.str(self.w_value)) return '%s: %s' % (exc_type, exc_value) def getframe(self): @@ -107,14 +107,14 @@ else: w = space.wrap if space.is_true(space.is_(space.type(self.w_type), space.w_str)): - exc_typename = space.unwrap(self.w_type) + exc_typename = space.str_w(self.w_type) else: - exc_typename = space.unwrap( + exc_typename = space.str_w( space.getattr(self.w_type, w('__name__'))) if self.w_value == space.w_None: exc_value = None else: - exc_value = space.unwrap(space.str(self.w_value)) + exc_value = space.str_w(space.str(self.w_value)) print >> file, '(application-level)', if not exc_value: print >> file, exc_typename Modified: pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py Fri Jan 14 17:44:21 2005 @@ -104,7 +104,7 @@ def interplevelexec(self, w_codestring): "NOT_RPYTHON: 'exec' a string at interp-level." - codestring = self.space.unwrap(w_codestring) + codestring = self.space.str_w(w_codestring) exec codestring in self.__dict__ return self.space.w_None @@ -112,7 +112,7 @@ """NOT_RPYTHON: 'eval' a string at interp-level. The result must be None or a wrapped object, which is returned to the caller.""" space = self.space - codestring = space.unwrap(w_codestring) + codestring = space.str_w(w_codestring) w_result = eval(codestring, self.__dict__) if w_result is None: w_result = space.w_None # else assume that it is already wrapped @@ -121,7 +121,7 @@ def interplevelexecfile(self, w_filename): """NOT_RPYTON: 'exec' a file at interp-level. The file should be in the same directory as the xxxmodule.py source file of the module.""" - filename = self.space.unwrap(w_filename) + filename = self.space.str_w(w_filename) filename = os.path.join(os.path.dirname(self.__file__), filename) execfile(filename, self.__dict__) return self.space.w_None @@ -138,7 +138,7 @@ if w_fromlist == space.w_None: raise ImportError, "must use 'from __interplevel__ import xx'" for w_name in space.unpacktuple(w_fromlist): - name = space.unwrap(w_name) + name = space.str_w(w_name) if not hasattr(self, 'w_' + name): f = getattr(self, name) code = gateway.BuiltinCode(f, ismethod=False, Modified: pypy/branch/src-typedunwrap/pypy/interpreter/function.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/function.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/function.py Fri Jan 14 17:44:21 2005 @@ -60,24 +60,24 @@ return self.call_args(__args__) def fget_func_defaults(space, w_self): - self = space.unwrap(w_self) + self = space.unwrap_builtin(w_self) values_w = self.defs_w if not values_w: return space.w_None return space.newtuple(values_w) def fget_func_doc(space, w_self): - self = space.unwrap(w_self) + self = space.unwrap_builtin(w_self) if self.w_doc is None: self.w_doc = space.wrap(self.code.getdocstring()) return self.w_doc def fset_func_doc(space, w_self, w_doc): - self = space.unwrap(w_self) + self = space.unwrap_builtin(w_self) self.w_doc = w_doc def fdel_func_doc(space, w_self): - self = space.unwrap(w_self) + self = space.unwrap_builtin(w_self) self.w_doc = space.w_None class Method(Wrappable): @@ -131,7 +131,7 @@ def descr_method_getattribute(self, w_attr): space = self.space w_self = space.wrap(self) - w_result = space.lookup(w_self, space.unwrap(w_attr)) + w_result = space.lookup(w_self, space.str_w(w_attr)) if w_result is None: return space.getattr(self.w_function, w_attr) else: Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Fri Jan 14 17:44:21 2005 @@ -109,7 +109,7 @@ w_args = argarray.pop() argarray += self.space.unpacktuple(w_args) if self.code.ismethod: - argarray[0] = self.space.unwrap(argarray[0]) + argarray[0] = self.space.unwrap_builtin(argarray[0]) self.argarray = argarray def getfastscope(self): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py Fri Jan 14 17:44:21 2005 @@ -36,7 +36,7 @@ "*** Entering interpreter-level console ***") local = self.__dict__.copy() for w_name in self.space.unpackiterable(self.w_globals): - local['w_' + self.space.unwrap(w_name)] = ( + local['w_' + self.space.str_w(w_name)] = ( self.space.getitem(self.w_globals, w_name)) code.interact(banner=banner, local=local) # copy back 'w_' names Modified: pypy/branch/src-typedunwrap/pypy/interpreter/main.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/main.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/main.py Fri Jan 14 17:44:21 2005 @@ -25,7 +25,7 @@ mainmodule = module.Module(space, space.wrap("__main__")) w_globals = mainmodule.w_dict - pycode = space.unwrap(w_code) + pycode = space.unwrap_builtin(w_code) retval = pycode.exec_code(space, w_globals, w_globals) if eval: return retval Modified: pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py Fri Jan 14 17:44:21 2005 @@ -165,10 +165,10 @@ def MAKE_CLOSURE(f, numdefaults): w_codeobj = f.valuestack.pop() - codeobj = f.space.unwrap(w_codeobj) + codeobj = f.space.unwrap_builtin(w_codeobj) assert isinstance(codeobj, pycode.PyCode) nfreevars = len(codeobj.co_freevars) - freevars = [f.space.unwrap(f.valuestack.pop()) for i in range(nfreevars)] + freevars = [f.space.unwrap_builtin(f.valuestack.pop()) for i in range(nfreevars)] freevars.reverse() defaultarguments = [f.valuestack.pop() for i in range(numdefaults)] defaultarguments.reverse() Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py Fri Jan 14 17:44:21 2005 @@ -8,6 +8,15 @@ from pypy.interpreter import eval from pypy.tool.cache import Cache +# helper + +def unpack_str_tuple(space,w_str_tuple): + els = [] + for w_el in space.unpackiterable(w_str_tuple): + els.append(space.str_w(w_el)) + return tuple(els) + + # code object contants, for co_flags below CO_OPTIMIZED = 0x0001 CO_NEWLOCALS = 0x0002 @@ -81,7 +90,7 @@ if isinstance(const, types.CodeType): const = PyCode()._from_code(const) newconsts.append(const) - self.co_consts = tuple(newconsts) + self.co_consts = tuple(newconsts) # xxx mixed types return self def create_frame(self, space, w_globals, closure=None): @@ -140,22 +149,22 @@ code = space.allocate_instance(PyCode, w_subtype) code.__init__() # XXX typechecking everywhere! - code.co_argcount = space.unwrap(w_argcount) - code.co_nlocals = space.unwrap(w_nlocals) - code.co_stacksize = space.unwrap(w_stacksize) - code.co_flags = space.unwrap(w_flags) - code.co_code = space.unwrap(w_codestring) - code.co_consts = space.unwrap(w_constants) - code.co_names = space.unwrap(w_names) - code.co_varnames = space.unwrap(w_varnames) - code.co_filename = space.unwrap(w_filename) - code.co_name = space.unwrap(w_name) - code.co_firstlineno= space.unwrap(w_firstlineno) - code.co_lnotab = space.unwrap(w_lnotab) + code.co_argcount = space.int_w(w_argcount) + code.co_nlocals = space.int_w(w_nlocals) + code.co_stacksize = space.int_w(w_stacksize) + code.co_flags = space.int_w(w_flags) + code.co_code = space.str_w(w_codestring) + code.co_consts = space.unwrap(w_constants) # xxx mixed types + code.co_names = unpack_str_tuple(space, w_names) + code.co_varnames = unpack_str_tuple(space, w_varnames) + code.co_filename = space.str_w(w_filename) + code.co_name = space.str_w(w_name) + code.co_firstlineno= space.int_w(w_firstlineno) + code.co_lnotab = space.str_w(w_lnotab) if w_freevars is not None: - code.co_freevars = space.unwrap(w_freevars) + code.co_freevars = unpack_str_tuple(space, w_freevars) if w_cellvars is not None: - code.co_cellvars = space.unwrap(w_cellvars) + code.co_cellvars = unpack_str_tuple(space, w_cellvars) return space.wrap(code) def _really_enhanceclass(key, stuff): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py Fri Jan 14 17:44:21 2005 @@ -341,7 +341,7 @@ jump_to = self.args[0] return [space.wrap(jump_to)] def state_pack_variables(self, space, w_jump_to): - self.args = (space.unwrap(w_jump_to),) + self.args = (space.int_w(w_jump_to),) class SReturnValue(ControlFlowException): """Signals a 'return' statement. Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py Fri Jan 14 17:44:21 2005 @@ -15,6 +15,7 @@ class unaryoperation: def __init__(self, operationname): self.operationname = operationname + def __call__(self, f): operation = getattr(f.space, self.operationname) w_1 = f.valuestack.pop() @@ -319,8 +320,8 @@ w_resulttuple = pyframe.normalize_exception(f.space, w_type, w_value, w_traceback) w_type, w_value, w_traceback = f.space.unpacktuple(w_resulttuple, 3) - tb = f.space.unwrap(w_traceback) - if tb is not None: + if w_traceback is not f.space.w_None: + tb = f.space.unwrap_builtin(w_traceback) if not isinstance(tb,pytraceback.PyTraceback): raise OperationError(f.space.w_TypeError, f.space.wrap("raise: arg 3 must be a traceback or None")) @@ -348,7 +349,7 @@ plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) if plain: w_locals = f.getdictscope() - pycode = f.space.unwrap(w_prog) + pycode = f.space.unwrap_builtin(w_prog) pycode.exec_code(f.space, w_globals, w_locals) if plain: f.setdictscope(w_locals) @@ -407,9 +408,10 @@ # [wrapped stack unroller ] f.valuestack.pop() # ignore the exception type f.valuestack.pop() # ignore the exception value - unroller = f.space.unwrap(f.valuestack.pop()) - if unroller is not None: - raise unroller # re-raise the unroller, if any + w_unroller = f.valuestack.pop() + if w_unroller is not f.space.w_None: + # re-raise the unroller, if any + raise f.space.unwrap_builtin(w_unroller) def BUILD_CLASS(f): w_methodsdict = f.valuestack.pop() @@ -697,7 +699,7 @@ for i in range(n_keywords): w_value = f.valuestack.pop() w_key = f.valuestack.pop() - key = f.space.unwrap(w_key) # XXX type check: str + key = f.space.str_w(w_key) keywords[key] = w_value arguments = [f.valuestack.pop() for i in range(n_arguments)] arguments.reverse() @@ -721,7 +723,7 @@ def MAKE_FUNCTION(f, numdefaults): w_codeobj = f.valuestack.pop() - codeobj = f.space.unwrap(w_codeobj) + codeobj = f.space.unwrap_builtin(w_codeobj) defaultarguments = [f.valuestack.pop() for i in range(numdefaults)] defaultarguments.reverse() fn = function.Function(f.space, codeobj, f.w_globals, defaultarguments) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py Fri Jan 14 17:44:21 2005 @@ -87,17 +87,17 @@ #print w_property, w_obj, w_cls return w_property else: - return space.unwrap(w_property).fget(space, w_obj) + return space.unwrap_builtin(w_property).fget(space, w_obj) def descr_property_set(space, w_property, w_obj, w_value): - fset = space.unwrap(w_property).fset + fset = space.unwrap_builtin(w_property).fset if fset is None: raise OperationError(space.w_AttributeError, space.wrap("read-only attribute")) fset(space, w_obj, w_value) def descr_property_del(space, w_property, w_obj): - fdel = space.unwrap(w_property).fdel + fdel = space.unwrap_builtin(w_property).fdel if fdel is None: raise OperationError(space.w_AttributeError, space.wrap("cannot delete attribute")) Modified: pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py Fri Jan 14 17:44:21 2005 @@ -1,6 +1,6 @@ import operator from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import ObjSpace +from pypy.interpreter.baseobjspace import ObjSpace,W_Root from pypy.interpreter.function import Function from pypy.interpreter.gateway import BuiltinCode from pypy.interpreter.argument import Arguments @@ -73,7 +73,9 @@ args = Arguments(space, list(args_w)) return space.get_and_call_args(w_descr, w_obj, args) - def unwrap_builtin(self, w_obj): + def unwrap_builtin(space, w_obj): + if not isinstance(w_obj, W_Root): + raise TypeError,"cannot unwrap_builtin: " + repr(w_obj) return w_obj # hook for hack by TrivialObjSpace def call_args(space, w_obj, args): Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Fri Jan 14 17:44:21 2005 @@ -99,6 +99,22 @@ raise TypeError("already wrapped: " + repr(obj)) return Constant(obj) + def int_w(self, w_obj): + if isinstance(w_obj, Constant): + val = w_obj.value + if type(val) is not int: + raise TypeError("expected int: " + repr(w_obj)) + return val + return self.unwrap(w_obj) + + def str_w(self, w_obj): + if isinstance(w_obj, Constant): + val = w_obj.value + if type(val) is not str: + raise TypeError("expected string: " + repr(w_obj)) + return val + return self.unwrap(w_obj) + def unwrap(self, w_obj): if isinstance(w_obj, Variable): raise UnwrapException @@ -107,6 +123,8 @@ else: raise TypeError("not wrapped: " + repr(w_obj)) + unwrap_builtin = unwrap + def getexecutioncontext(self): return self.executioncontext Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/default.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/default.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/default.py Fri Jan 14 17:44:21 2005 @@ -219,6 +219,14 @@ class UnwrapError(Exception): pass +def int_w__ANY(space,w_obj): + raise OperationError(space.w_TypeError, + space.wrap("expected int")) + +def str_w__ANY(space,w_obj): + raise OperationError(space.w_TypeError, + space.wrap("expected str")) + def unwrap__ANY(space, w_obj): if isinstance(w_obj, BaseWrappable): return w_obj Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/intobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/intobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/intobject.py Fri Jan 14 17:44:21 2005 @@ -40,6 +40,9 @@ print """ +def int_w__Int(space, w_int1): + return int(w_int1.intval) + def unwrap__Int(space, w_int1): return int(w_int1.intval) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py Fri Jan 14 17:44:21 2005 @@ -338,11 +338,15 @@ #getattribute = MultiMethod('getattr', 2, ['__getattribute__']) # XXX hack # special visible multimethods delegate = DelegateMultiMethod() # delegators + int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int + str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string unwrap = MultiMethod('unwrap', 1, []) # returns an unwrapped object issubtype = MultiMethod('issubtype', 2, []) id = MultiMethod('id', 1, []) init = MultiMethod('__init__', 1, varargs=True, keywords=True) + int_w = MM.int_w + str_w = MM.str_w unwrap = MM.unwrap delegate = MM.delegate #is_true = MM.is_true Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py Fri Jan 14 17:44:21 2005 @@ -13,6 +13,7 @@ def mod__String_ANY(space, w_str, w_item):def mod__String_Tuple(space, w_str, w_tuple):def mod_str_tuple(space, w_format, w_args): def ord__String(space, w_str): def string_richcompare(space, w_str1, w_str2, op): + def str_w__String(space, w_str): def unwrap__String(space, w_str): __add__ def add__String_String(space, w_left, w_right): __class__ @@ -756,6 +757,9 @@ str_translate__String_String_String = gateway.app2interp(app_str_translate__String_String_String) + +def str_w__String(space, w_str): + return w_str._value def unwrap__String(space, w_str): return w_str._value Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py Fri Jan 14 17:44:21 2005 @@ -26,6 +26,9 @@ except FailedToImplement, arg: return arg[0] + def test_int_w(self): + assert self.space.int_w(self.space.wrap(42)) == 42 + def test_repr(self): x = 1 f1 = iobj.W_IntObject(self.space, x) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stdobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stdobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stdobjspace.py Fri Jan 14 17:44:21 2005 @@ -1,4 +1,6 @@ import autopath +from pypy.interpreter.error import OperationError + objspacename = 'std' @@ -9,6 +11,14 @@ self.space.wrap, self.space.wrap(0)) + def test_str_w_non_str(self): + raises(OperationError,self.space.str_w,self.space.wrap(None)) + raises(OperationError,self.space.str_w,self.space.wrap(0)) + + def test_int_w_non_int(self): + raises(OperationError,self.space.int_w,self.space.wrap(None)) + raises(OperationError,self.space.int_w,self.space.wrap("")) + def hopeful_test_exceptions(self): self.apptest("self.failUnless(issubclass(ArithmeticError, Exception))") self.apptest("self.failIf(issubclass(ArithmeticError, KeyError))") Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_stringobject.py Fri Jan 14 17:44:21 2005 @@ -37,6 +37,10 @@ ## w(str2), ## pypyconst)) + + def test_str_w(self): + assert self.space.str_w(self.space.wrap("foo")) == "foo" + def test_equality(self): w = self.space.wrap assert self.space.eq_w(w('abc'), w('abc')) Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Fri Jan 14 17:44:21 2005 @@ -140,6 +140,18 @@ return tuple([self.wrap(y) for y in x]) return x + def int_w(self, w): + if type(w) is not int: + raise OperationError(self.w_TypeError, + sefl.wrap("expected int")) + return w + + def str_w(self, w): + if type(w) is not str: + raise OperationError(self.w_TypeError, + sefl.wrap("expected string")) + return w + def unwrap(self, w): if isinstance(w, CPyWrapper): instancedict = CPyWrapper.__dict__['__dict__'].__get__(w) From mwh at codespeak.net Fri Jan 14 17:53:19 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Fri, 14 Jan 2005 17:53:19 +0100 (MET) Subject: [pypy-svn] r8277 - pypy/trunk/src/pypy/interpreter Message-ID: <20050114165319.E2D9927BB1@code1.codespeak.net> Author: mwh Date: Fri Jan 14 17:53:19 2005 New Revision: 8277 Modified: pypy/trunk/src/pypy/interpreter/function.py Log: I got fairly badly confused by the Function's __repr__. Make it a bit clearer. Modified: pypy/trunk/src/pypy/interpreter/function.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/function.py (original) +++ pypy/trunk/src/pypy/interpreter/function.py Fri Jan 14 17:53:19 2005 @@ -28,7 +28,7 @@ def __repr__(self): # return "function %s.%s" % (self.space, self.name) # maybe we want this shorter: - return "func %s" % self.name + return "" % self.name def call_args(self, args): scope_w = args.parse(self.name, self.code.signature(), self.defs_w) From pedronis at codespeak.net Fri Jan 14 19:11:18 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 14 Jan 2005 19:11:18 +0100 (MET) Subject: [pypy-svn] r8280 - in pypy/branch/src-typedunwrap/pypy: interpreter interpreter/test module objspace/flow objspace/flow/test tool tool/test Message-ID: <20050114181118.B503E27BB1@code1.codespeak.net> Author: pedronis Date: Fri Jan 14 19:11:18 2005 New Revision: 8280 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_eval.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_function.py pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/flow/test/test_framestate.py pypy/branch/src-typedunwrap/pypy/tool/test/test_pytestsupport.py pypy/branch/src-typedunwrap/pypy/tool/traceinteractive.py Log: made PyCode objects space depedent. This also solves the mixed types tuple issue with co_consts. Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Fri Jan 14 19:11:18 2005 @@ -217,7 +217,7 @@ if isinstance(expression, str): expression = compile(expression, '?', 'eval') if isinstance(expression, types.CodeType): - expression = PyCode()._from_code(expression) + expression = PyCode(self)._from_code(expression) if not isinstance(expression, PyCode): raise TypeError, 'space.eval(): expected a string, code or PyCode object' return expression.exec_code(self, w_globals, w_locals) @@ -229,7 +229,7 @@ if isinstance(statement, str): statement = compile(statement, '?', 'exec') if isinstance(statement, types.CodeType): - statement = PyCode()._from_code(statement) + statement = PyCode(self)._from_code(statement) if not isinstance(statement, PyCode): raise TypeError, 'space.exec_(): expected a string, code or PyCode object' return statement.exec_code(self, w_globals, w_locals) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py Fri Jan 14 19:11:18 2005 @@ -49,7 +49,7 @@ f.close() code = compile(modulesource, self.__file__, 'exec', generators.compiler_flag) - pycode = PyCode()._from_code(code) + pycode = PyCode(space)._from_code(code) # Set the hooks that call back from app-level to interp-level w_builtins = space.w_builtins Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Fri Jan 14 19:11:18 2005 @@ -30,9 +30,6 @@ eval.Code.__init__(self, func.__name__) self.func = func self.docstring = func.__doc__ - # extract the signature from the (CPython-level) code object - tmp = pycode.PyCode(None) - tmp._from_code(func.func_code) # signature-based hacks: renaming arguments from w_xyz to xyz. # Currently we enforce the following signature tricks: # * the first arg must be either 'self' or 'space' @@ -40,7 +37,8 @@ # * '_w' suffix for the optional '*' argument # * alternatively a final '__args__' means an Arguments() # Not exactly a clean approach XXX. - argnames, varargname, kwargname = tmp.signature() + # First extract the signature from the (CPython-level) code object + argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) argnames = list(argnames) lookslikemethod = argnames[:1] == ['self'] if ismethod is None: @@ -139,12 +137,18 @@ # after initialization the following attributes should be set # name - # code # _staticglobals - # _staticdefs + # _staticdefs + # + # getcode is called lazily to get the code object to construct + # the space-bound function NOT_RPYTHON_ATTRIBUTES = ['_staticglobals', '_staticdefs'] + def getcode(self, space): + # needs to be implemented by subclasses + raise TypeError, "abstract" + def __spacebind__(self, space): # to wrap a Gateway, we first make a real Function object out of it # and the result is a wrapped version of this Function. @@ -192,7 +196,8 @@ return cache.content[self] except KeyError: defs = self.getdefaults(space) # needs to be implemented by subclass - fn = Function(space, self.code, w_globals, defs, forcename = self.name) + code = self.getcode(space) + fn = Function(space, code, w_globals, defs, forcename = self.name) cache.content[self] = fn return fn @@ -200,10 +205,6 @@ # to get the Gateway as a method out of an instance, we build a # Function and get it. # the object space is implicitely fetched out of the instance - if isinstance(self.code, BuiltinCode): - assert self.code.ismethod, ( - 'global built-in function %r used as method' % - self.code.func) space = obj.space fn = self.get_function(space) w_obj = space.wrap(obj) @@ -213,6 +214,9 @@ class app2interp(Gateway): """Build a Gateway that calls 'app' at app-level.""" + + NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + def __init__(self, app, app_name=None): "NOT_RPYTHON" Gateway.__init__(self) @@ -225,11 +229,16 @@ "%r does not" % app.func_name) app_name = app.func_name[4:] self.name = app_name - self.code = pycode.PyCode(None) - self.code._from_code(app.func_code) + self._staticcode = app.func_code self._staticglobals = app.func_globals self._staticdefs = list(app.func_defaults or ()) + def getcode(self, space): + "NOT_RPYTHON" + code = pycode.PyCode(space) + code._from_code(self._staticcode) + return code + def getdefaults(self, space): "NOT_RPYTHON" return [space.wrap(val) for val in self._staticdefs] @@ -264,15 +273,25 @@ raise ValueError, ("function name %r suspiciously starts " "with 'app_'" % f.func_name) app_name = f.func_name - self.code = BuiltinCode(f) + self._code = BuiltinCode(f) self.name = app_name self._staticdefs = list(f.func_defaults or ()) self._staticglobals = None + def getcode(self, space): + return self._code + def getdefaults(self, space): "NOT_RPYTHON" return self._staticdefs + def get_method(self, obj): + assert self._code.ismethod, ( + 'global built-in function %r used as method' % + self._code.func) + return Gateway.get_method(self, obj) + + def exportall(d, temporary=False): """NOT_RPYTHON: Publish every function from a dict.""" if temporary: Modified: pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/interactive.py Fri Jan 14 19:11:18 2005 @@ -51,7 +51,7 @@ def runcode(self, code): # 'code' is a CPython code object from pypy.interpreter.pycode import PyCode - pycode = PyCode()._from_code(code) + pycode = PyCode(self.space)._from_code(code) try: pycode.exec_code(self.space, self.w_globals, self.w_globals) except baseobjspace.OperationError, operationerr: Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py Fri Jan 14 19:11:18 2005 @@ -25,17 +25,35 @@ CO_NESTED = 0x0010 CO_GENERATOR = 0x0020 +# cpython_code_signature helper +def cpython_code_signature(code): + "([list-of-arg-names], vararg-name-or-None, kwarg-name-or-None)." + argcount = code.co_argcount + argnames = list(code.co_varnames[:argcount]) + if code.co_flags & CO_VARARGS: + varargname = code.co_varnames[argcount] + argcount += 1 + else: + varargname = None + if code.co_flags & CO_VARKEYWORDS: + kwargname = code.co_varnames[argcount] + argcount += 1 + else: + kwargname = None + return argnames, varargname, kwargname + class PyCode(eval.Code): "CPython-style code objects." - def __init__(self, co_name=''): + def __init__(self, space, co_name=''): + self.space = space eval.Code.__init__(self, co_name) self.co_argcount = 0 # #arguments, except *vararg and **kwarg self.co_nlocals = 0 # #local variables self.co_stacksize = 0 # #entries needed for evaluation stack self.co_flags = 0 # CO_..., see above self.co_code = None # string: instruction opcodes - self.co_consts = () # tuple: constants used + self.co_consts_w = () # tuple: constants used (wrapped!) self.co_names = () # tuple of strings: names (for attrs,...) self.co_varnames = () # tuple of strings: local variable names self.co_freevars = () # tuple of strings: free variable names @@ -85,12 +103,13 @@ x = code.co_lnotab; assert isinstance(x, str) self.co_lnotab = x # recursively _from_code()-ify the code objects in code.co_consts - newconsts = [] + space = self.space + newconsts_w = [] for const in code.co_consts: if isinstance(const, types.CodeType): - const = PyCode()._from_code(const) - newconsts.append(const) - self.co_consts = tuple(newconsts) # xxx mixed types + const = PyCode(space)._from_code(const) + newconsts_w.append(space.wrap(const)) + self.co_consts_w = newconsts_w return self def create_frame(self, space, w_globals, closure=None): @@ -105,28 +124,18 @@ Frame = enhanceclass(Frame, F) return Frame(space, self, w_globals, closure) - def signature(self): - "([list-of-arg-names], vararg-name-or-None, kwarg-name-or-None)." - argcount = self.co_argcount - argnames = list(self.co_varnames[:argcount]) - if self.co_flags & CO_VARARGS: - varargname = self.co_varnames[argcount] - argcount += 1 - else: - varargname = None - if self.co_flags & CO_VARKEYWORDS: - kwargname = self.co_varnames[argcount] - argcount += 1 - else: - kwargname = None - return argnames, varargname, kwargname + signature = cpython_code_signature def getvarnames(self): return self.co_varnames def getdocstring(self): - if self.co_consts: # it is probably never empty - return self.co_consts[0] + if self.co_consts_w: # it is probably never empty + const0_w = self.co_consts_w[0] + if const0_w is self.space.w_None: + return None + else: + return self.space.str_w(const0_w) else: return None @@ -141,20 +150,24 @@ # first approximation return dis.findlabels(self.co_code) + def fget_co_consts(space, w_self): + self = space.unwrap_builtin(w_self) + return space.newtuple(self.co_consts_w) + def descr_code__new__(space, w_subtype, w_argcount, w_nlocals, w_stacksize, w_flags, w_codestring, w_constants, w_names, w_varnames, w_filename, w_name, w_firstlineno, w_lnotab, w_freevars=None, w_cellvars=None): code = space.allocate_instance(PyCode, w_subtype) - code.__init__() + code.__init__(space) # XXX typechecking everywhere! code.co_argcount = space.int_w(w_argcount) code.co_nlocals = space.int_w(w_nlocals) code.co_stacksize = space.int_w(w_stacksize) code.co_flags = space.int_w(w_flags) code.co_code = space.str_w(w_codestring) - code.co_consts = space.unwrap(w_constants) # xxx mixed types + code.co_consts_w = space.unpacktuple(w_constants) code.co_names = unpack_str_tuple(space, w_names) code.co_varnames = unpack_str_tuple(space, w_varnames) code.co_filename = space.str_w(w_filename) @@ -179,7 +192,3 @@ else: return cache.getorbuild((newclass, baseclass), _really_enhanceclass, None) - - -def cpython_code_signature(co): - return PyCode()._from_code(co).signature() Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py Fri Jan 14 19:11:18 2005 @@ -68,8 +68,8 @@ def getlocalvarname(self, index): return self.code.co_varnames[index] - def getconstant(self, index): - return self.code.co_consts[index] + def getconstant_w(self, index): + return self.code.co_consts_w[index] def getname(self, index): return self.code.co_names[index] @@ -96,7 +96,7 @@ f.valuestack.push(w_value) def LOAD_CONST(f, constindex): - w_const = f.space.wrap(f.getconstant(constindex)) + w_const = f.getconstant_w(constindex) f.valuestack.push(w_const) def STORE_FAST(f, varindex): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_eval.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_eval.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_eval.py Fri Jan 14 19:11:18 2005 @@ -8,7 +8,7 @@ def setup_method(self, method): def c(x, y, *args): pass - code = PyCode()._from_code(c.func_code) + code = PyCode(self.space)._from_code(c.func_code) class ConcreteFastscopeFrame(Frame): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_function.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_function.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_function.py Fri Jan 14 19:11:18 2005 @@ -175,7 +175,7 @@ def setup_method(self, method): def c(self, bar): return bar - code = PyCode()._from_code(c.func_code) + code = PyCode(self.space)._from_code(c.func_code) self.fn = Function(self.space, code) def test_get(self): @@ -202,7 +202,7 @@ space = self.space # Create some function for this test only def m(self): return self - func = Function(space, PyCode()._from_code(m.func_code)) + func = Function(space, PyCode(self.space)._from_code(m.func_code)) # Some shorthands obj1 = space.wrap(23) obj2 = space.wrap(42) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py Fri Jan 14 19:11:18 2005 @@ -199,7 +199,7 @@ co_stacksize = attrproperty('co_stacksize'), co_flags = attrproperty('co_flags'), co_code = attrproperty('co_code'), - co_consts = attrproperty('co_consts'), + co_consts = GetSetProperty(PyCode.fget_co_consts), co_names = attrproperty('co_names'), co_varnames = attrproperty('co_varnames'), co_freevars = attrproperty('co_freevars'), Modified: pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py (original) +++ pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py Fri Jan 14 19:11:18 2005 @@ -216,7 +216,7 @@ raise OperationError(space.w_ValueError,space.wrap(str(e))) except TypeError,e: raise OperationError(space.w_TypeError,space.wrap(str(e))) - return space.wrap(PyCode()._from_code(c)) + return space.wrap(PyCode(space)._from_code(c)) def eval(w_source, w_globals=None, w_locals=None): w = space.wrap Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Fri Jan 14 19:11:18 2005 @@ -144,7 +144,7 @@ if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'): raise Exception, "%r is tagged as NOT_RPYTHON" % (func,) code = func.func_code - code = PyCode()._from_code(code) + code = PyCode(self)._from_code(code) if func.func_closure is None: closure = None else: Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/test/test_framestate.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/test/test_framestate.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/test/test_framestate.py Fri Jan 14 19:11:18 2005 @@ -15,7 +15,7 @@ except AttributeError: pass code = func.func_code - code = PyCode()._from_code(code) + code = PyCode(self.space)._from_code(code) w_globals = Constant({}) # space.newdict([]) frame = code.create_frame(space, w_globals) Modified: pypy/branch/src-typedunwrap/pypy/tool/test/test_pytestsupport.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/tool/test/test_pytestsupport.py (original) +++ pypy/branch/src-typedunwrap/pypy/tool/test/test_pytestsupport.py Fri Jan 14 19:11:18 2005 @@ -13,7 +13,7 @@ def test_AppFrame(space): import sys - co = PyCode()._from_code(somefunc.func_code) + co = PyCode(space)._from_code(somefunc.func_code) pyframe = PyFrame(space, co, space.newdict([]), None) runner = AppFrame(pyframe) exprinfo.run("f = lambda x: x+1", runner) Modified: pypy/branch/src-typedunwrap/pypy/tool/traceinteractive.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/tool/traceinteractive.py (original) +++ pypy/branch/src-typedunwrap/pypy/tool/traceinteractive.py Fri Jan 14 19:11:18 2005 @@ -168,10 +168,10 @@ def runcode(self, code): # 'code' is a CPython code object from pypy.interpreter.pycode import PyCode - pycode = PyCode()._from_code(code) - s = self.space + pycode = PyCode(s)._from_code(code) + try: if self.tracelevel: s.settrace() From hpk at codespeak.net Fri Jan 14 23:23:45 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 14 Jan 2005 23:23:45 +0100 (MET) Subject: [pypy-svn] r8284 - pypy/trunk/src/pypy/tool Message-ID: <20050114222345.EB85927B8A@code1.codespeak.net> Author: hpk Date: Fri Jan 14 23:23:45 2005 New Revision: 8284 Modified: pypy/trunk/src/pypy/tool/example_pytest.py Log: added a few example for failing tests within pypy Modified: pypy/trunk/src/pypy/tool/example_pytest.py ============================================================================== --- pypy/trunk/src/pypy/tool/example_pytest.py (original) +++ pypy/trunk/src/pypy/tool/example_pytest.py Fri Jan 14 23:23:45 2005 @@ -12,3 +12,15 @@ def test_interp_method(self): assert self.space.is_true(self.space.w_False) +def app_test_raises_something(): + int("hallo") + +def app_test_raises_wrong1(): + raises(SyntaxError, 'int("hello")') + +def app_test_raises_wrong2(): + raises(SyntaxError, int, "hello") + +def app_test_raises_doesnt(): + raises(ValueError, int, 3) + From hpk at codespeak.net Sat Jan 15 11:28:02 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 15 Jan 2005 11:28:02 +0100 (MET) Subject: [pypy-svn] r8288 - pypy/trunk/src/pypy/tool Message-ID: <20050115102802.34AB127B72@code1.codespeak.net> Author: hpk Date: Sat Jan 15 11:28:02 2005 New Revision: 8288 Modified: pypy/trunk/src/pypy/tool/pytestsupport.py Log: adjustments to integrate with just refactored py lib. fix the particular "raises(Exception, STRING)" case. Modified: pypy/trunk/src/pypy/tool/pytestsupport.py ============================================================================== --- pypy/trunk/src/pypy/tool/pytestsupport.py (original) +++ pypy/trunk/src/pypy/tool/pytestsupport.py Sat Jan 15 11:28:02 2005 @@ -35,17 +35,23 @@ def is_true(self, w_value): return self.space.is_true(w_value) - class AppExceptionInfo(py.code.ExceptionInfo): """An ExceptionInfo object representing an app-level exception.""" def __init__(self, space, operr): self.space = space self.operr = operr - self.exprinfo = None + self.traceback = AppTraceback(self.operr.application_traceback) def __str__(self): - return '(app-level) ' + self.operr.errorstr(self.space) + return '[app-level] ' + self.operr.errorstr(self.space) + +class AppTracebackEntry(py.code.Traceback.Entry): + exprinfo = None + + def __init__(self, tb): + self.frame = AppFrame(tb.frame) + self.lineno = tb.lineno - 1 def reinterpret(self): # XXX we need to solve a general problem: how to prevent @@ -57,16 +63,15 @@ # XXX this reinterpret() is only here to prevent reinterpretation. return self.exprinfo - def __iter__(self): - tb = self.operr.application_traceback - while tb is not None: - yield AppTracebackEntry(tb) - tb = tb.next +class AppTraceback(py.code.Traceback): + Entry = AppTracebackEntry -class AppTracebackEntry(py.code.TracebackEntry): - def __init__(self, tb): - self.frame = AppFrame(tb.frame) - self.lineno = tb.lineno - 1 + def __init__(self, apptb): + l = [] + while apptb is not None: + l.append(self.Entry(apptb)) + apptb = apptb.next + list.__init__(self, l) # ____________________________________________________________ @@ -89,7 +94,7 @@ source = str(source).strip() except py.error.ENOENT: source = None - if source: + if source and not py.test.config.option.nomagic: msg = exprinfo.interpret(source, runner, should_fail=True) space.setattr(w_self, space.wrap('args'), space.newtuple([space.wrap(msg)])) @@ -120,7 +125,7 @@ "after a string expression")) expr = space.unwrap(w_expr) source = py.code.Source(expr) - frame = space.executioncontext.framestack.top() + frame = space.getexecutioncontext().framestack.top() w_locals = frame.getdictscope() w_locals = space.call_method(w_locals, 'copy') for key, w_value in kwds_w.items(): From pedronis at codespeak.net Sat Jan 15 12:19:33 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 15 Jan 2005 12:19:33 +0100 (MET) Subject: [pypy-svn] r8290 - in pypy/trunk/src/pypy: interpreter objspace/std Message-ID: <20050115111933.46BE527B82@code1.codespeak.net> Author: pedronis Date: Sat Jan 15 12:19:33 2005 New Revision: 8290 Modified: pypy/trunk/src/pypy/interpreter/gateway.py pypy/trunk/src/pypy/objspace/std/fake.py Log: small fixes (they keep translate_pypy working) Modified: pypy/trunk/src/pypy/interpreter/gateway.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/gateway.py (original) +++ pypy/trunk/src/pypy/interpreter/gateway.py Sat Jan 15 12:19:33 2005 @@ -11,6 +11,7 @@ """ import types, sys +from pypy.interpreter.error import OperationError from pypy.interpreter import eval, pycode from pypy.interpreter.function import Function, Method from pypy.interpreter.baseobjspace import Wrappable Modified: pypy/trunk/src/pypy/objspace/std/fake.py ============================================================================== --- pypy/trunk/src/pypy/objspace/std/fake.py (original) +++ pypy/trunk/src/pypy/objspace/std/fake.py Sat Jan 15 12:19:33 2005 @@ -95,7 +95,7 @@ self.unwrappedargs = self.space.unwrap(w_args) self.unwrappedkwds = self.space.unwrap(w_kwds) except UnwrapError, e: - raise UnwrapError('calling %s: %s' % (fn, e)) + raise UnwrapError('calling %s: %s' % (self.code.cpy_callable, e)) def getfastscope(self): raise OperationError(self.space.w_TypeError, From pedronis at codespeak.net Sat Jan 15 12:31:44 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 15 Jan 2005 12:31:44 +0100 (MET) Subject: [pypy-svn] r8291 - in pypy/branch/src-typedunwrap/pypy: interpreter objspace/std tool Message-ID: <20050115113144.413FF27B82@code1.codespeak.net> Author: pedronis Date: Sat Jan 15 12:31:44 2005 New Revision: 8291 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/function.py pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py pypy/branch/src-typedunwrap/pypy/tool/example_pytest.py pypy/branch/src-typedunwrap/pypy/tool/pytestsupport.py Log: fixes, changes from trunk Modified: pypy/branch/src-typedunwrap/pypy/interpreter/function.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/function.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/function.py Sat Jan 15 12:31:44 2005 @@ -28,7 +28,7 @@ def __repr__(self): # return "function %s.%s" % (self.space, self.name) # maybe we want this shorter: - return "func %s" % self.name + return "" % self.name def call_args(self, args): scope_w = args.parse(self.name, self.code.signature(), self.defs_w) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Sat Jan 15 12:31:44 2005 @@ -11,6 +11,11 @@ """ import types, sys +<<<<<<< .working +from pypy.interpreter.error import OperationError +======= +from pypy.interpreter.error import OperationError +>>>>>>> .merge-right.r8290 from pypy.interpreter import eval, pycode from pypy.interpreter.function import Function, Method from pypy.interpreter.baseobjspace import Wrappable Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py Sat Jan 15 12:31:44 2005 @@ -95,7 +95,7 @@ self.unwrappedargs = self.space.unwrap(w_args) self.unwrappedkwds = self.space.unwrap(w_kwds) except UnwrapError, e: - raise UnwrapError('calling %s: %s' % (fn, e)) + raise UnwrapError('calling %s: %s' % (self.code.cpy_callable, e)) def getfastscope(self): raise OperationError(self.space.w_TypeError, Modified: pypy/branch/src-typedunwrap/pypy/tool/example_pytest.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/tool/example_pytest.py (original) +++ pypy/branch/src-typedunwrap/pypy/tool/example_pytest.py Sat Jan 15 12:31:44 2005 @@ -12,3 +12,15 @@ def test_interp_method(self): assert self.space.is_true(self.space.w_False) +def app_test_raises_something(): + int("hallo") + +def app_test_raises_wrong1(): + raises(SyntaxError, 'int("hello")') + +def app_test_raises_wrong2(): + raises(SyntaxError, int, "hello") + +def app_test_raises_doesnt(): + raises(ValueError, int, 3) + Modified: pypy/branch/src-typedunwrap/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/tool/pytestsupport.py (original) +++ pypy/branch/src-typedunwrap/pypy/tool/pytestsupport.py Sat Jan 15 12:31:44 2005 @@ -35,17 +35,23 @@ def is_true(self, w_value): return self.space.is_true(w_value) - class AppExceptionInfo(py.code.ExceptionInfo): """An ExceptionInfo object representing an app-level exception.""" def __init__(self, space, operr): self.space = space self.operr = operr - self.exprinfo = None + self.traceback = AppTraceback(self.operr.application_traceback) def __str__(self): - return '(app-level) ' + self.operr.errorstr(self.space) + return '[app-level] ' + self.operr.errorstr(self.space) + +class AppTracebackEntry(py.code.Traceback.Entry): + exprinfo = None + + def __init__(self, tb): + self.frame = AppFrame(tb.frame) + self.lineno = tb.lineno - 1 def reinterpret(self): # XXX we need to solve a general problem: how to prevent @@ -57,16 +63,15 @@ # XXX this reinterpret() is only here to prevent reinterpretation. return self.exprinfo - def __iter__(self): - tb = self.operr.application_traceback - while tb is not None: - yield AppTracebackEntry(tb) - tb = tb.next +class AppTraceback(py.code.Traceback): + Entry = AppTracebackEntry -class AppTracebackEntry(py.code.TracebackEntry): - def __init__(self, tb): - self.frame = AppFrame(tb.frame) - self.lineno = tb.lineno - 1 + def __init__(self, apptb): + l = [] + while apptb is not None: + l.append(self.Entry(apptb)) + apptb = apptb.next + list.__init__(self, l) # ____________________________________________________________ @@ -89,7 +94,7 @@ source = str(source).strip() except py.error.ENOENT: source = None - if source: + if source and not py.test.config.option.nomagic: msg = exprinfo.interpret(source, runner, should_fail=True) space.setattr(w_self, space.wrap('args'), space.newtuple([space.wrap(msg)])) @@ -120,7 +125,7 @@ "after a string expression")) expr = space.unwrap(w_expr) source = py.code.Source(expr) - frame = space.executioncontext.framestack.top() + frame = space.getexecutioncontext().framestack.top() w_locals = frame.getdictscope() w_locals = space.call_method(w_locals, 'copy') for key, w_value in kwds_w.items(): From pedronis at codespeak.net Sat Jan 15 12:34:02 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 15 Jan 2005 12:34:02 +0100 (MET) Subject: [pypy-svn] r8292 - pypy/branch/src-typedunwrap/pypy/interpreter Message-ID: <20050115113402.C561327B82@code1.codespeak.net> Author: pedronis Date: Sat Jan 15 12:34:02 2005 New Revision: 8292 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Log: oops Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Sat Jan 15 12:34:02 2005 @@ -11,11 +11,8 @@ """ import types, sys -<<<<<<< .working -from pypy.interpreter.error import OperationError -======= + from pypy.interpreter.error import OperationError ->>>>>>> .merge-right.r8290 from pypy.interpreter import eval, pycode from pypy.interpreter.function import Function, Method from pypy.interpreter.baseobjspace import Wrappable From hpk at codespeak.net Sat Jan 15 12:55:23 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 15 Jan 2005 12:55:23 +0100 (MET) Subject: [pypy-svn] r8293 - pypy/trunk/doc Message-ID: <20050115115523.A4A1927B82@code1.codespeak.net> Author: hpk Date: Sat Jan 15 12:55:23 2005 New Revision: 8293 Added: pypy/trunk/doc/newrepolayout.txt Log: a repo layout proposal Added: pypy/trunk/doc/newrepolayout.txt ============================================================================== --- (empty file) +++ pypy/trunk/doc/newrepolayout.txt Sat Jan 15 12:55:23 2005 @@ -0,0 +1,75 @@ +=========================================== +Proposition: new svn repository layout +=========================================== + +Motivation +---------- + +The `PyPy repository layout`_ has evolved for two +years into something that needs some refactoring +to become more practical. + +For example, the `trunk/doc`_ directory was originally intended +to hold developer documentation but nowadays it contains +funding, negotiations, mails and misc-other-stuff documents. It is +not easy and obvious anymore to know which files are relevant. +Moreover, `trunk/doc`_ is too far away from the source code: +developers currently checkout the 'trunk/src' directory and +don't even get the documentation. This also makes it more +difficult to keep the documentation up-to-date. + +.. _`trunk/doc`: http://codespeak.net/svn/pypy/trunk/doc +.. _`PyPy repository layout`: http://codespeak.net/svn/pypy/ + +New repo layout proposal Nr. 1 +------------------------------ + +Based on experiences in various repositories here is a +new proposition describing a possible new structure +(starting at /svn/pypy):: + + branch # holds branches + tag # holds tagged dist-versions + + dist # holds current development + pypy # current trunk/src/pypy + documentation # developer documentation (inside pypy!) + py # and other 'externals' + setup.py # should be there at some point + README.txt # tell how to run PyPy, the translator, tests + LICENSE.txt # copyright notices for tree parts including pypy + + doc # non-dist documentations (papers etc.pp.) + talk # various pypy-talks + paper # various pypy-related papers (including our own) + sprint # sprint related information (reports etc.pp.) + irclog # IRC logs (snipped appropriately) + + www # website-related stuff (needs its own reconsideration) + + funding # funding related documents + eu-info # official information from the EU + contract # contract material (EU-contract, amendments) + eu-report # eu reports (time/cost/budget) + ... # probably more, we'll see later + +The idea is that developers can use a simple url:: + + svn co https://codespeak.net/svn/pypy/dist dist-pypy + +in order to get everything neccessary for sourcecode, documentation +and test development. Obviously, if you care about the funding +or web site application/contents you can do an appropriate checkout +as well. + +Note, that having documentation inside the source tree will help +with keeping a closer eye on documentation - especially when we +have special ref-integrity tests for the documentation (which itself +should reference real source-code/functions at some point). For +example, the refactoring of unitest.py-style tests to `py.test`_ based ones +"forgot" to modify our test-documentation in the too-far-away doc-folder. +We should move to a scheme where such an omission will raise real +test errors. + +.. _`py.test`: http://codespeak.net/py/current/doc/test.html + From pedronis at codespeak.net Sat Jan 15 13:41:24 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 15 Jan 2005 13:41:24 +0100 (MET) Subject: [pypy-svn] r8294 - pypy/branch/src-typedunwrap/pypy/interpreter Message-ID: <20050115124124.2AE7727B8A@code1.codespeak.net> Author: pedronis Date: Sat Jan 15 13:41:23 2005 New Revision: 8294 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Log: fix to make translate_pypy -no-a on the branch happy again Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Sat Jan 15 13:41:23 2005 @@ -217,7 +217,7 @@ class app2interp(Gateway): """Build a Gateway that calls 'app' at app-level.""" - NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + Gateway.NOT_RPYTHON_ATTRIBUTES def __init__(self, app, app_name=None): "NOT_RPYTHON" From jum at codespeak.net Sun Jan 16 04:23:43 2005 From: jum at codespeak.net (jum at codespeak.net) Date: Sun, 16 Jan 2005 04:23:43 +0100 (MET) Subject: [pypy-svn] r8300 - pypy/trunk/doc/devel Message-ID: <20050116032343.78CE227BAC@code1.codespeak.net> Author: jum Date: Sun Jan 16 04:23:43 2005 New Revision: 8300 Modified: pypy/trunk/doc/devel/howtosvn.txt Log: Updated to latest svn OS X build (with local Berkeley DB support this time). Modified: pypy/trunk/doc/devel/howtosvn.txt ============================================================================== --- pypy/trunk/doc/devel/howtosvn.txt (original) +++ pypy/trunk/doc/devel/howtosvn.txt Sun Jan 16 04:23:43 2005 @@ -140,7 +140,7 @@ .. _website: http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B259403 .. _GUI: http://tortoisesvn.tigris.org/servlets/ProjectDocumentList?folderID=616 -.. _MacOS: http://codespeak.net/~jum/svn-1.1.1-darwin-ppc.tar.gz +.. _MacOS: http://codespeak.net/~jum/svn-1.1.3-darwin-ppc.tar.gz .. _versions: http://subversion.tigris.org/project_packages.html .. _Win: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=4B6140F9-2D36-4977-8FA1-6F8A0F5DCA8F From hpk at codespeak.net Sun Jan 16 22:32:43 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 16 Jan 2005 22:32:43 +0100 (MET) Subject: [pypy-svn] r8320 - pypy/trunk/src/pypy/translator/java/test Message-ID: <20050116213243.5865527B55@code1.codespeak.net> Author: hpk Date: Sun Jan 16 22:32:43 2005 New Revision: 8320 Modified: pypy/trunk/src/pypy/translator/java/test/test_javatrans.py Log: skip java translation if there is no javac Modified: pypy/trunk/src/pypy/translator/java/test/test_javatrans.py ============================================================================== --- pypy/trunk/src/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/trunk/src/pypy/translator/java/test/test_javatrans.py Sun Jan 16 22:32:43 2005 @@ -1,4 +1,5 @@ import autopath, os +import py from py.process import cmdexec from pypy.tool.udir import udir from pypy.translator.java.genjava import GenJava @@ -10,6 +11,12 @@ objspacename = 'flow' + def setup_class(cls): + try: + py.path.local.sysfind('javac') + except py.error.ENOENT: + py.test.skip("javac not found") + def build_jfunc(self, func): try: func = func.im_func except AttributeError: pass From hpk at codespeak.net Mon Jan 17 00:08:01 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 17 Jan 2005 00:08:01 +0100 (MET) Subject: [pypy-svn] r8324 - pypy/trunk/src/pypy/translator/test Message-ID: <20050116230801.8E14527B55@code1.codespeak.net> Author: hpk Date: Mon Jan 17 00:08:01 2005 New Revision: 8324 Modified: pypy/trunk/src/pypy/translator/test/test_ctrans.py pypy/trunk/src/pypy/translator/test/test_pyrextrans.py pypy/trunk/src/pypy/translator/test/test_sourcegen.py Log: skip tests if underlying system features (c-compiler mostly) are not present. Modified: pypy/trunk/src/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/trunk/src/pypy/translator/test/test_ctrans.py (original) +++ pypy/trunk/src/pypy/translator/test/test_ctrans.py Mon Jan 17 00:08:01 2005 @@ -1,4 +1,5 @@ import autopath +import py from pypy.tool.udir import udir from pypy.translator.genc import GenC from pypy.objspace.flow.model import * @@ -11,9 +12,7 @@ from pypy.translator.tool import buildpyxmodule buildpyxmodule.enable_fast_compilation() - class TestNoTypeCGenTestCase: - objspacename = 'flow' def build_cfunc(self, func): @@ -21,7 +20,7 @@ except AttributeError: pass t = Translator(func) t.simplify() - return t.ccompile() + return py.test.skip_on_error(t.ccompile) def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) @@ -197,7 +196,7 @@ argstypelist.append(spec) a = t.annotate(argstypelist) a.simplify() - return t.ccompile() + return py.test.skip_on_error(t.ccompile) def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) Modified: pypy/trunk/src/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/trunk/src/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/trunk/src/pypy/translator/test/test_pyrextrans.py Mon Jan 17 00:08:01 2005 @@ -14,7 +14,6 @@ class TestNoTypePyrexGenTestCase: - objspacename = 'flow' def build_cfunc(self, func): @@ -26,7 +25,7 @@ 'simplify' : 1, 'dot' : dot, } - return build_cfunc(func, **options) + return py.test.skip_on_error(build_cfunc, func, **options) def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) @@ -105,7 +104,7 @@ spec = spec[0] # use the first type only for the tests argstypelist.append(spec) t.annotate(argstypelist) - return t.compile() + return py.test.skip_on_error(t.compile) def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) Modified: pypy/trunk/src/pypy/translator/test/test_sourcegen.py ============================================================================== --- pypy/trunk/src/pypy/translator/test/test_sourcegen.py (original) +++ pypy/trunk/src/pypy/translator/test/test_sourcegen.py Mon Jan 17 00:08:01 2005 @@ -1,5 +1,6 @@ import autopath +import py from pypy.tool.udir import udir from pypy.translator.genpyrex import GenPyrex @@ -28,7 +29,8 @@ block.operations.append(op) block.closeblock(Link([result], fun.returnblock)) result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source1', udir, result) + mod = py.test.skip_on_error( + make_module_from_pyxstring, 'test_source1', udir, result) assert mod.f(1) == 2 def test_if(self): @@ -53,7 +55,8 @@ Link([j], fun.returnblock, True)) result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source2', udir, result) + mod = py.test.skip_on_error( + make_module_from_pyxstring, 'test_source2', udir, result) assert mod.f(-1, 42) == 42 assert mod.f(3, 5) == 3 @@ -89,6 +92,7 @@ whileblock.closeblock(Link([i, sum], headerblock)) result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source4', udir, result) + mod = py.test.skip_on_error( + make_module_from_pyxstring, 'test_source4', udir, result) assert mod.f(3) == 6 assert mod.f(-3) == 0 From lac at codespeak.net Mon Jan 17 10:24:18 2005 From: lac at codespeak.net (lac at codespeak.net) Date: Mon, 17 Jan 2005 10:24:18 +0100 (MET) Subject: [pypy-svn] r8326 - pypy/trunk/src/pypy/appspace/test Message-ID: <20050117092418.7D74327B5D@code1.codespeak.net> Author: lac Date: Mon Jan 17 10:24:18 2005 New Revision: 8326 Modified: pypy/trunk/src/pypy/appspace/test/test_file.py Log: Add fix from A. B. Khalid Modified: pypy/trunk/src/pypy/appspace/test/test_file.py ============================================================================== --- pypy/trunk/src/pypy/appspace/test/test_file.py (original) +++ pypy/trunk/src/pypy/appspace/test/test_file.py Mon Jan 17 10:24:18 2005 @@ -16,8 +16,10 @@ assert self.fd.tell() == 0 def test_case_readonly(self): - f=_file.file_('/tmp/tt', 'w') - assert f.name == '/tmp/tt' + from tempfile import mktemp + fn = mktemp() + f=_file.file_(fn, 'w') + assert f.name == fn assert f.mode == 'w' assert f.closed == False assert f.encoding == None # Fix when we find out what this is From hpk at codespeak.net Mon Jan 17 10:33:34 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 17 Jan 2005 10:33:34 +0100 (MET) Subject: [pypy-svn] r8327 - pypy/trunk/src/pypy/appspace/test Message-ID: <20050117093334.7D39A27B64@code1.codespeak.net> Author: hpk Date: Mon Jan 17 10:33:34 2005 New Revision: 8327 Modified: pypy/trunk/src/pypy/appspace/test/test_file.py Log: use PyPy's test-session "udir" so that temp directories are cleaned up at some point. Modified: pypy/trunk/src/pypy/appspace/test/test_file.py ============================================================================== --- pypy/trunk/src/pypy/appspace/test/test_file.py (original) +++ pypy/trunk/src/pypy/appspace/test/test_file.py Mon Jan 17 10:33:34 2005 @@ -1,7 +1,8 @@ import os import autopath from pypy.appspace import _file -from py.test import raises +from pypy.tool.udir import udir +import py import unittest class TestFile: @@ -16,11 +17,10 @@ assert self.fd.tell() == 0 def test_case_readonly(self): - from tempfile import mktemp - fn = mktemp() + fn = str(udir.join('temptestfile')) f=_file.file_(fn, 'w') assert f.name == fn assert f.mode == 'w' assert f.closed == False assert f.encoding == None # Fix when we find out what this is - raises(TypeError, setattr, f, 'name', 42) + py.test.raises(TypeError, setattr, f, 'name', 42) From pedronis at codespeak.net Mon Jan 17 13:52:57 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 13:52:57 +0100 (MET) Subject: [pypy-svn] r8328 - pypy/branch/src-typedunwrap/pypy/objspace Message-ID: <20050117125257.1DD6A27BF4@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 13:52:56 2005 New Revision: 8328 Modified: pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py Log: descropertation now uses type specific unwrap Modified: pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py Mon Jan 17 13:52:56 2005 @@ -7,7 +7,7 @@ class Object: def descr__getattribute__(space, w_obj, w_name): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_obj, name) if w_descr is not None: if space.is_data_descr(w_descr): @@ -24,7 +24,7 @@ raise OperationError(space.w_AttributeError, w_name) def descr__setattr__(space, w_obj, w_name, w_value): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_obj, name) if w_descr is not None: if space.is_data_descr(w_descr): @@ -35,7 +35,7 @@ raise OperationError(space.w_AttributeError, w_name) def descr__delattr__(space, w_obj, w_name): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_obj, name) if w_descr is not None: if space.is_data_descr(w_descr): @@ -361,7 +361,7 @@ return w_res # fallback: lt(a, b) <= lt(cmp(a, b), 0) ... w_res = _cmp(space, w_first, w_second) - res = space.unwrap(w_res) + res = space.int_w(w_res) return space.wrap(op(res, 0)) return func_with_new_name(comparison_impl, 'comparison_%s_impl'%left.strip('_')) From ale at codespeak.net Mon Jan 17 15:43:22 2005 From: ale at codespeak.net (ale at codespeak.net) Date: Mon, 17 Jan 2005 15:43:22 +0100 (MET) Subject: [pypy-svn] r8329 - pypy/trunk/src/pypy/appspace Message-ID: <20050117144322.B9C8C27B62@code1.codespeak.net> Author: ale Date: Mon Jan 17 15:43:22 2005 New Revision: 8329 Modified: pypy/trunk/src/pypy/appspace/struct.py Log: The struct module passes all Python regression test ( on my machine anyway Win2k, Python 2.4) TODO : implement the sanefloat function (do some test on the floats) do something about INF and NAN and friends Modified: pypy/trunk/src/pypy/appspace/struct.py ============================================================================== --- pypy/trunk/src/pypy/appspace/struct.py (original) +++ pypy/trunk/src/pypy/appspace/struct.py Mon Jan 17 15:43:22 2005 @@ -151,6 +151,9 @@ e += bias mantissa = int(2**prec *(man) +0.5) res=[] + if mantissa >> prec : + mantissa = 0 + e += 1 for i in range(size-2): res += [ mantissa & 0xff] From pedronis at codespeak.net Mon Jan 17 16:18:29 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 16:18:29 +0100 (MET) Subject: [pypy-svn] r8335 - in pypy/branch/src-typedunwrap/pypy: interpreter objspace objspace/flow objspace/std objspace/std/test Message-ID: <20050117151829.2559F27B76@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 16:18:28 2005 New Revision: 8335 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/default.py pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/floatobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/floattype.py pypy/branch/src-typedunwrap/pypy/objspace/std/longobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_dictobject.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: int_w now accepts also long int as long as they are in the int range added float_w, for now like str_w and int_w it does not call space.float directly but only unwraps float started using where possible type specifics unwraps in std objspace Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Mon Jan 17 16:18:28 2005 @@ -362,7 +362,8 @@ # # wrap(x) -> w_x # str_w(w_str) -> str -# int_w(w_ival) -> ival +# int_w(w_ival or w_long_ival) -> ival +# float_w(w_floatval) -> floatval # unwrap(w_x) -> x # is_true(w_x) -> True or False # newtuple([w_1, w_2,...]) -> w_tuple Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Mon Jan 17 16:18:28 2005 @@ -102,8 +102,8 @@ def int_w(self, w_obj): if isinstance(w_obj, Constant): val = w_obj.value - if type(val) is not int: - raise TypeError("expected int: " + repr(w_obj)) + if type(val) not in (int,long): + raise TypeError("expected integer: " + repr(w_obj)) return val return self.unwrap(w_obj) @@ -115,6 +115,14 @@ return val return self.unwrap(w_obj) + def float_w(self, w_obj): + if isinstance(w_obj, Constant): + val = w_obj.value + if type(val) is not float: + raise TypeError("expected float: " + repr(w_obj)) + return val + return self.unwrap(w_obj) + def unwrap(self, w_obj): if isinstance(w_obj, Variable): raise UnwrapException Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/default.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/default.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/default.py Mon Jan 17 16:18:28 2005 @@ -221,12 +221,16 @@ def int_w__ANY(space,w_obj): raise OperationError(space.w_TypeError, - space.wrap("expected int")) + space.wrap("expected integer")) def str_w__ANY(space,w_obj): raise OperationError(space.w_TypeError, space.wrap("expected str")) +def float_w__ANY(space,w_obj): + raise OperationError(space.w_TypeError, + space.wrap("expected float")) + def unwrap__ANY(space, w_obj): if isinstance(w_obj, BaseWrappable): return w_obj Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py Mon Jan 17 16:18:28 2005 @@ -38,7 +38,7 @@ def hash(w_self, w_obj): space = w_self.space - return r_uint(space.unwrap(space.hash(w_obj))) + return r_uint(space.int_w(space.hash(w_obj))) def insert(self, h, w_key, w_value): entry = self.lookdict(h, w_key) @@ -108,7 +108,7 @@ registerimplementation(W_DictObject) -def unwrap__Dict(space, w_dict): +def unwrap__Dict(space, w_dict): # xxx result = {} for entry in w_dict.non_empties(): result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/floatobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/floatobject.py Mon Jan 17 16:18:28 2005 @@ -43,6 +43,9 @@ def int__Float(space, w_value): return space.newint(int(w_value.floatval)) +def float_w__Float(space, w_float): + return w_float.floatval + def unwrap__Float(space, w_float): return w_float.floatval Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/floattype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/floattype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/floattype.py Mon Jan 17 16:18:28 2005 @@ -7,7 +7,7 @@ value = 0.0 elif space.is_true(space.isinstance(w_value, space.w_str)): try: - value = float(space.unwrap(w_value)) + value = float(space.str_w(w_value)) except ValueError, e: raise OperationError(space.w_ValueError, space.wrap(str(e))) @@ -16,12 +16,7 @@ if space.is_true(space.is_(w_floattype, space.w_float)): return w_obj # 'float(x)' should return # whatever x.__float__() returned - value = space.unwrap(w_obj) - if isinstance(value, int): # XXX typechecking in unwrap! - value = float(value) - if not isinstance(value, float): # XXX typechecking in unwrap! - raise OperationError(space.w_ValueError, - space.wrap("value can't be converted to float")) + value = space.float_w(w_obj) w_obj = space.allocate_instance(W_FloatObject, w_floattype) w_obj.__init__(space, value) return w_obj Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/longobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/longobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/longobject.py Mon Jan 17 16:18:28 2005 @@ -44,6 +44,13 @@ def long__Float(space, w_floatobj): return W_LongObject(space, long(w_floatobj.floatval)) +def int_w__Long(space, w_value): + if -sys.maxint-1 <= w_value.longval <= sys.maxint: + return int(w_value.longval) + else: + raise OperationError(space.w_OverflowError, + space.wrap("long int too large to convert to int")) + def unwrap__Long(space, w_long): return w_long.longval Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py Mon Jan 17 16:18:28 2005 @@ -340,14 +340,16 @@ delegate = DelegateMultiMethod() # delegators int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string + float_w = MultiMethod('float_w', 1, []) # returns an unwrapped float unwrap = MultiMethod('unwrap', 1, []) # returns an unwrapped object issubtype = MultiMethod('issubtype', 2, []) id = MultiMethod('id', 1, []) init = MultiMethod('__init__', 1, varargs=True, keywords=True) - int_w = MM.int_w - str_w = MM.str_w - unwrap = MM.unwrap + int_w = MM.int_w + str_w = MM.str_w + float_w = MM.float_w + unwrap = MM.unwrap delegate = MM.delegate #is_true = MM.is_true Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_dictobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_dictobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_dictobject.py Mon Jan 17 16:18:28 2005 @@ -300,6 +300,8 @@ return hash(obj) def unwrap(self, x): return x + def int_w(self, x): + return x def is_true(self, x): return x def is_(self, x, y): Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Mon Jan 17 16:18:28 2005 @@ -141,10 +141,16 @@ return x def int_w(self, w): - if type(w) is not int: - raise OperationError(self.w_TypeError, - sefl.wrap("expected int")) - return w + if type(w) is int: + return w + if type(w) is long: + if -sys.maxint-1 <= w <= sys.maxint: + return w + raise OperationError(self.w_OverflowError, + sefl.wrap("long int too large to convert to int")) + + raise OperationError(self.w_TypeError, + sefl.wrap("expected integer")) def str_w(self, w): if type(w) is not str: @@ -152,6 +158,12 @@ sefl.wrap("expected string")) return w + def float_w(self, w): + if type(w) is not float: + raise OperationError(self.w_TypeError, + sefl.wrap("expected float")) + return w + def unwrap(self, w): if isinstance(w, CPyWrapper): instancedict = CPyWrapper.__dict__['__dict__'].__get__(w) From hpk at codespeak.net Mon Jan 17 16:23:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 17 Jan 2005 16:23:52 +0100 (MET) Subject: [pypy-svn] r8336 - pypy/trunk/src/pypy/translator/test Message-ID: <20050117152352.35D7327B76@code1.codespeak.net> Author: hpk Date: Mon Jan 17 16:23:52 2005 New Revision: 8336 Modified: pypy/trunk/src/pypy/translator/test/test_cltrans.py Log: py.testified test_cltrans.py a bit (and make it work on OSX correctly) Modified: pypy/trunk/src/pypy/translator/test/test_cltrans.py ============================================================================== --- pypy/trunk/src/pypy/translator/test/test_cltrans.py (original) +++ pypy/trunk/src/pypy/translator/test/test_cltrans.py Mon Jan 17 16:23:52 2005 @@ -3,12 +3,10 @@ import py import os -def get_cl(): - cl = os.getenv("PYPY_CL") - if cl: return cl - cl = cl_detect() - if cl: return cl - return None +def setup_module(mod): + mod.global_cl = os.getenv("PYPY_CL") + if not mod.global_cl: + mod.global_cl = cl_detect() def cl_detect(): if is_on_path("clisp"): @@ -23,11 +21,11 @@ def is_on_path(name): try: - return os.system("which %s >/dev/null 2>/dev/null" % name) == 0 - except OSError: - pass - -global_cl = get_cl() + py.path.local.sysfind(name) + except py.error.ENOENT: + return False + else: + return True def make_cl_func(func, argtypes=[]): from pypy.translator.tool.buildcl import _make_cl_func @@ -38,7 +36,6 @@ from pypy.translator.tool.buildcl import Literal class TestGenCLTestCase: - objspacename = 'flow' def setup_method(self,method): From arigo at codespeak.net Mon Jan 17 17:03:32 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 17 Jan 2005 17:03:32 +0100 (MET) Subject: [pypy-svn] r8337 - pypy/trunk/src/pypy/interpreter Message-ID: <20050117160332.6439427B6E@code1.codespeak.net> Author: arigo Date: Mon Jan 17 17:03:32 2005 New Revision: 8337 Modified: pypy/trunk/src/pypy/interpreter/pyframe.py Log: Guido's comment on string exceptions Modified: pypy/trunk/src/pypy/interpreter/pyframe.py ============================================================================== --- pypy/trunk/src/pypy/interpreter/pyframe.py (original) +++ pypy/trunk/src/pypy/interpreter/pyframe.py Mon Jan 17 17:03:32 2005 @@ -218,8 +218,7 @@ etype = value.__class__ elif type(etype) is str: # XXX warn -- deprecated - if value is not None and type(value) is not str: - raise TypeError("string exceptions can only have a string value") + pass else: # raise X: we assume that X is an already-built instance if value is not None: From pedronis at codespeak.net Mon Jan 17 17:04:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 17:04:47 +0100 (MET) Subject: [pypy-svn] r8338 - in pypy/branch/src-typedunwrap/pypy/objspace/std: . test Message-ID: <20050117160447.394D827B6E@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 17:04:47 2005 New Revision: 8338 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/inttype.py pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py Log: using type specific unwraps where possible in long and int __new__ code, given that right now we are cheating with our long implementation we have the problem that both code pieces can have to deal with unwrapped longs Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/inttype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/inttype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/inttype.py Mon Jan 17 17:04:47 2005 @@ -12,7 +12,8 @@ value = w_value.intval elif space.is_true(space.isinstance(w_value, space.w_str)): try: - value = string_to_int(space.unwrap(w_value)) + # XXX can produce unwrapped long + value = string_to_int(space.str_w(w_value)) except ValueError, e: raise OperationError(space.w_ValueError, space.wrap(e.args[0])) @@ -22,28 +23,38 @@ # 'int(x)' should return whatever x.__int__() returned if space.is_true(space.is_(w_inttype, space.w_int)): return w_obj - value = space.unwrap(w_obj) - if not isinstance(value, (int, long)): # XXX typechecking in unwrap! - raise OperationError(space.w_ValueError, - space.wrap("value can't be converted to int")) + # int_w is effectively what we want in this case, + # we cannot construct a subclass of int instance with an + # an overflowing long + try: + value = space.int_w(w_obj) + except OperationError, e: + if e.match(space,space.w_TypeError): + raise OperationError(space.w_ValueError, + space.wrap("value can't be converted to int")) + raise e else: - base = space.unwrap(w_base) - if not isinstance(base, int): # XXX typechecking in unwrap! - raise OperationError(space.w_TypeError, - space.wrap("an integer is required")) - s = space.unwrap(w_value) - if not isinstance(s, str): # XXX typechecking in unwrap! + base = space.int_w(w_base) + + try: + s = space.str_w(w_value) + except OperationError, e: raise OperationError(space.w_TypeError, space.wrap("int() can't convert non-string " "with explicit base")) try: + # XXX can produce unwrapped long, need real long impl to know + # what to do value = string_to_int(s, base) except ValueError, e: raise OperationError(space.w_ValueError, space.wrap(e.args[0])) if isinstance(value, long): - # XXX is this right?? + if not space.is_true(space.is_(w_inttype, space.w_int)): + raise OperationError(space.w_OverflowError, + space.wrap( + "long int too large to convert to int")) from pypy.objspace.std.longobject import W_LongObject w_obj = space.allocate_instance(W_LongObject, space.w_long) w_obj.__init__(space, value) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py Mon Jan 17 17:04:47 2005 @@ -13,7 +13,8 @@ value = w_value.longval elif space.is_true(space.isinstance(w_value, space.w_str)): try: - value = string_to_long(space.unwrap(w_value)) + # XXX value can unwrapped long + value = string_to_long(space.str_w(w_value)) except ValueError, e: raise OperationError(space.w_ValueError, space.wrap(e.args[0])) @@ -23,23 +24,23 @@ # 'long(x)' should return whatever x.__long__() returned if space.is_true(space.is_(w_longtype, space.w_long)): return w_obj - value = space.unwrap(w_obj) + value = space.unwrap(w_obj) # XXX value can unwrapped long if isinstance(value, int): # XXX typechecking in unwrap! value = long(value) if not isinstance(value, long): raise OperationError(space.w_ValueError, space.wrap("value can't be converted to long")) else: - base = space.unwrap(w_base) - if not isinstance(base, int): # XXX typechecking in unwrap! - raise OperationError(space.w_TypeError, - space.wrap("an integer is required")) - s = space.unwrap(w_value) - if not isinstance(s, str): # XXX typechecking in unwrap! + base = space.int_w(w_base) + + try: + s = space.str_w(w_value) + except OperationError, e: raise OperationError(space.w_TypeError, space.wrap("long() can't convert non-string " "with explicit base")) try: + # XXX value can unwrapped long value = string_to_long(s, base) except ValueError, e: raise OperationError(space.w_ValueError, Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/test/test_intobject.py Mon Jan 17 17:04:47 2005 @@ -317,3 +317,19 @@ def test_pow(self): assert pow(2, -10) == 1/1024. + + def test_int_w_long_arg(self): + assert int(10000000000) == 10000000000L + assert int("10000000000") == 10000000000L + + def test_int_subclass_ctr(self): + class j(int): + pass + assert j(100) == 100 + assert isinstance(j(100),j) + assert j(100L) == 100 + assert j("100") == 100 + assert j("100",2) == 4 + assert isinstance(j("100",2),j) + raises(OverflowError,j,10000000000) + raises(OverflowError,j,"10000000000") From pedronis at codespeak.net Mon Jan 17 17:18:18 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 17:18:18 +0100 (MET) Subject: [pypy-svn] r8339 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117161818.EF5DC27B92@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 17:18:18 2005 New Revision: 8339 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py Log: typos in comments Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/longtype.py Mon Jan 17 17:18:18 2005 @@ -13,7 +13,7 @@ value = w_value.longval elif space.is_true(space.isinstance(w_value, space.w_str)): try: - # XXX value can unwrapped long + # XXX value can be unwrapped long value = string_to_long(space.str_w(w_value)) except ValueError, e: raise OperationError(space.w_ValueError, @@ -24,7 +24,7 @@ # 'long(x)' should return whatever x.__long__() returned if space.is_true(space.is_(w_longtype, space.w_long)): return w_obj - value = space.unwrap(w_obj) # XXX value can unwrapped long + value = space.unwrap(w_obj) # XXX value can be unwrapped long if isinstance(value, int): # XXX typechecking in unwrap! value = long(value) if not isinstance(value, long): @@ -40,7 +40,7 @@ space.wrap("long() can't convert non-string " "with explicit base")) try: - # XXX value can unwrapped long + # XXX value can be unwrapped long value = string_to_long(s, base) except ValueError, e: raise OperationError(space.w_ValueError, From pedronis at codespeak.net Mon Jan 17 17:38:21 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 17:38:21 +0100 (MET) Subject: [pypy-svn] r8341 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117163821.4DC7527BB0@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 17:38:21 2005 New Revision: 8341 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/tupleobject.py Log: listobject to use type specific unwraps comments for mixed types unwraps Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictobject.py Mon Jan 17 17:38:21 2005 @@ -108,10 +108,10 @@ registerimplementation(W_DictObject) -def unwrap__Dict(space, w_dict): # xxx +def unwrap__Dict(space, w_dict): result = {} for entry in w_dict.non_empties(): - result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) + result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) # XXX generic mixed types unwrap return result def init__Dict(space, w_dict, w_args, w_kwds): Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py Mon Jan 17 17:38:21 2005 @@ -33,8 +33,8 @@ registerimplementation(W_ListObject) -def unwrap__List(space, w_list): - items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]] +def unwrap__List(space, w_list): + items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]]# XXX generic mixed types unwrap return list(items) def init__List(space, w_list, w_args, w_kwds): @@ -406,11 +406,11 @@ eq = space.eq items = w_list.ob_item size = w_list.ob_size - start = space.unwrap(w_start) # XXX type check: int or clamped long + start = space.int_w(w_start) if start < 0: start += size start = min(max(0,start),size) - stop = space.unwrap(w_stop) # XXX type check: int or clamped long + stop = space.int_w(w_stop) if stop < 0: stop += size stop = min(max(start,stop),size) @@ -514,10 +514,13 @@ def complex_lt(self, a, b): space = self.space w_cmp = self.w_cmp - result = space.unwrap(space.call_function(w_cmp, a, b)) - if not isinstance(result,int): - raise OperationError(space.w_TypeError, - space.wrap("comparison function must return int")) + try: + result = space.int_w(space.call_function(w_cmp, a, b)) + except OperationError, e: + if e.match(space, space.w_TypeError): + raise OperationError(space.w_TypeError, + space.wrap("comparison function must return int")) + raise e return result < 0 def list_sort__List_ANY(space, w_list, w_cmp): Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/tupleobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/tupleobject.py Mon Jan 17 17:38:21 2005 @@ -20,8 +20,8 @@ registerimplementation(W_TupleObject) -def unwrap__Tuple(space, w_tuple): - items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] +def unwrap__Tuple(space, w_tuple): + items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] # XXX generic mixed types unwrap return tuple(items) def len__Tuple(space, w_tuple): From pedronis at codespeak.net Mon Jan 17 19:19:37 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 19:19:37 +0100 (MET) Subject: [pypy-svn] r8346 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117181937.C9D0727BB9@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 19:19:37 2005 New Revision: 8346 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/stringtype.py Log: moved to type specific unwraps or direct concrete impl class attribute access Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/stringobject.py Mon Jan 17 19:19:37 2005 @@ -130,7 +130,7 @@ def _is_generic(w_self, fun): space = w_self.space - v = space.unwrap(w_self) + v = w_self._value if len(v) == 0: return space.w_False if len(v) == 1: @@ -162,7 +162,7 @@ return _is_generic(w_self, _islower) def str_istitle__String(space, w_self): - input = space.unwrap(w_self) + input = w_self._value prev_letter='!' for pos in range(0, len(input)): @@ -176,7 +176,7 @@ return space.w_True def str_upper__String(space, w_self): - self = space.unwrap(w_self) + self = w_self._value res = [' '] * len(self) for i in range(len(self)): ch = self[i] @@ -189,7 +189,7 @@ return space.wrap("".join(res)) def str_lower__String(space, w_self): - self = space.unwrap(w_self) + self = w_self._value res = [' '] * len(self) for i in range(len(self)): ch = self[i] @@ -202,7 +202,7 @@ return space.wrap("".join(res)) def str_swapcase__String(space, w_self): - self = space.unwrap(w_self) + self = w_self._value res = [' '] * len(self) for i in range(len(self)): ch = self[i] @@ -219,7 +219,7 @@ def str_capitalize__String(space, w_self): - input = space.unwrap(w_self) + input = w_self._value buffer = [' '] * len(input) if len(input) > 0: ch = input[0] @@ -240,7 +240,7 @@ return space.wrap("".join(buffer)) def str_title__String(space, w_self): - input = space.unwrap(w_self) + input = w_self._value buffer = [' '] * len(input) prev_letter=' ' @@ -258,9 +258,8 @@ def str_split__String_None_Int(space, w_self, w_none, w_maxsplit=-1): res = [] inword = 0 - u = space.unwrap - value = u(w_self) - maxsplit = u(w_maxsplit) + value = w_self._value + maxsplit = space.int_w(w_maxsplit) pos = 0 for ch in value: @@ -285,13 +284,12 @@ return W_ListObject(space, res) def str_split__String_String_Int(space, w_self, w_by, w_maxsplit=-1): - u = space.unwrap res = [] start = 0 - value = u(w_self) - by = u(w_by) + value = w_self._value + by = w_by._value bylen = len(by) - maxsplit = u(w_maxsplit) + maxsplit = space.int_w(w_maxsplit) #if maxsplit is default, then you have no limit #of the length of the resulting array @@ -323,10 +321,10 @@ return W_ListObject(w_self.space, res) def str_join__String_ANY(space, w_self, w_list): - u = space.unwrap list = space.unpackiterable(w_list) + str_w = space.str_w if list: - self = u(w_self) + self = w_self._value firstelem = 1 listlen = 0 reslen = 0 @@ -340,7 +338,7 @@ space.w_TypeError, space.wrap("sequence item %d: expected string, %s " "found"%(i, space.type(list[i]).name))) - reslen = reslen + len(u(list[i])) + reslen = reslen + len(str_w(list[i])) listlen = listlen + 1 reslen = reslen + (listlen - 1) * len(self) @@ -351,7 +349,7 @@ pos = 0 #fill in the string buffer for w_item in list: - item = u(w_item) + item = str_w(w_item) if firstelem: for i in range(len(item)): res[i+pos] = item[i] @@ -372,10 +370,9 @@ def str_rjust__String_ANY(space, w_self, w_arg): - u = space.unwrap - u_arg = u(w_arg) - u_self = u(w_self) + u_arg = space.int_w(w_arg) + u_self = w_self._value d = u_arg - len(u_self) if d>0: @@ -385,10 +382,9 @@ def str_ljust__String_ANY(space, w_self, w_arg): - u = space.unwrap - u_self = u(w_self) - u_arg = u(w_arg) + u_self = w_self._value + u_arg = space.int_w(w_arg) d = u_arg - len(u_self) if d>0: @@ -397,15 +393,16 @@ return space.wrap(u_self) def _convert_idx_params(space, w_self, w_sub, w_start, w_end): - u = space.unwrap - start = u(w_start) - end = u(w_end) - self = u(w_self) - sub = u(w_sub) - if start is None: + self = w_self._value + sub = w_sub._value + if space.is_true(space.is_(w_start,space.w_None)): start = 0 - if end is None: + else: + start = space.int_w(w_start) + if space.is_true(space.is_(w_end,space.w_None)): end = len(self) + else: + end = space.int_w(w_end) return (self, sub, start, end) @@ -446,12 +443,11 @@ def str_replace__String_String_String_Int(space, w_self, w_sub, w_by, w_maxsplit=-1): - u = space.unwrap - input = u(w_self) - sub = u(w_sub) - by = u(w_by) - maxsplit = u(w_maxsplit) #I don't use it now + input = w_self._value + sub = w_sub._value + by = w_by._value + maxsplit = space.int_w(w_maxsplit) #I don't use it now #print "from replace, input: %s, sub: %s, by: %s" % (input, sub, by) @@ -542,8 +538,9 @@ def _strip(space, w_self, w_chars, left, right): "internal function called by str_xstrip methods" - u_self = space.unwrap(w_self) - u_chars = space.unwrap(w_chars) + u_self = w_self._value + assert isinstance(w_chars,W_StringObject) + u_chars = w_chars._value if u_self == None or u_chars == None: return w_self @@ -576,8 +573,8 @@ def str_center__String_Int(space, w_self, w_arg): - u_self = space.unwrap(w_self) - u_arg = space.unwrap(w_arg) + u_self = w_self._value + u_arg = space.int_w(w_arg) d = u_arg - len(u_self) if d>0: @@ -590,18 +587,20 @@ def str_count__String_String_ANY_ANY(space, w_self, w_arg, w_start, w_end): - u_self = space.unwrap(w_self) - u_arg = space.unwrap(w_arg) - u_start = space.unwrap(w_start) - u_end = space.unwrap(w_end) - - - if u_end == None: + u_self = w_self._value + u_arg = w_arg._value + + if space.is_true(space.is_(w_start,space.w_None)): + u_start = 0 + else: + u_start = space.int_w(w_start) + + if space.is_true(space.is_(w_end,space.w_None)): u_end = len(u_self) - elif u_end < 0: - u_end += len(u_self) - - if u_start == None: u_start = 0 + else: + u_end = space.int_w(w_end) + if u_end < 0: + u_end += len(u_self) area = u_self [u_start:u_end] @@ -620,8 +619,8 @@ #[optional arguments not supported now] def str_endswith__String_String(space, w_self, w_end): - u_self = space.unwrap(w_self) - u_end = space.unwrap(w_end) + u_self = w_self._value + u_end = w_end._value found = 0 if u_end: @@ -636,8 +635,8 @@ #[optional arguments not supported now] def str_startswith__String_String(space, w_self, w_start): - u_self = space.unwrap(w_self) - u_start = space.unwrap(w_start) + u_self = w_self._value + u_start = w_start._value found = 0 if u_start: @@ -677,8 +676,8 @@ def str_expandtabs__String_Int(space, w_self, w_tabsize): - u_self = space.unwrap(w_self) - u_tabsize = space.unwrap(w_tabsize) + u_self = w_self._value + u_tabsize = space.int_w(w_tabsize) u_expanded = "" if u_self: @@ -694,8 +693,8 @@ def str_splitlines__String_Int(space, w_self, w_keepends): - u_self = space.unwrap(w_self) - u_keepends = space.unwrap(w_keepends) + u_self = w_self._value + u_keepends = space.is_true(w_keepends) selflen = len(u_self) L = [] @@ -713,9 +712,8 @@ return W_ListObject(space, L) def str_zfill__String_Int(space, w_self, w_width): - u = space.unwrap - input = u(w_self) - width = u(w_width) + input = w_self._value + width = space.int_w(w_width) if len(input) >= width: return w_self @@ -765,7 +763,7 @@ return w_str._value def hash__String(space, w_str): - return W_IntObject(space, hash(space.unwrap(w_str))) + return W_IntObject(space, hash(w_str._value)) ##EQ = 1 @@ -881,10 +879,9 @@ return space.w_False def getitem__String_Int(space, w_str, w_int): - u = space.unwrap - ival = w_int.intval - str = u(w_str) - slen = len(u(w_str)) + ival = space.int_w(w_int) + str = w_str._value + slen = len(str) if ival < 0: ival += slen if ival < 0 or ival >= slen: @@ -904,9 +901,8 @@ return str_join__String_ANY(space, w_empty, w_r) def mul__String_Int(space, w_str, w_mul): - u = space.unwrap - input = u(w_str) - mul = u(w_mul) + input = w_str._value + mul = space.int_w(w_mul) buffer = [' '] * (mul*len(input)) @@ -922,9 +918,8 @@ return mul__String_Int(space, w_str, w_mul) def add__String_String(space, w_left, w_right): - u = space.unwrap - right = u(w_right) - left = u(w_left) + right = w_right._value + left = w_left._value buf = [' '] * (len(left) + len(right)) for i in range(len(left)): buf[i] = left[i] @@ -933,7 +928,7 @@ return space.wrap("".join(buf)) def len__String(space, w_str): - return space.wrap(len(space.unwrap(w_str))) + return space.wrap(len(w_str._value)) def str__String(space, w_str): return w_str @@ -974,12 +969,13 @@ def ord__String(space, w_str): - if len(w_str._value) != 1: + u_str = w_str._value + if len(u_str) != 1: raise OperationError( space.w_TypeError, space.wrap("ord() expected a character, but string " "of length %d found"%(len(w_str._value),))) - return space.wrap(ord(space.unwrap(w_str))) + return space.wrap(ord(u_str)) def app_mod__String_ANY(format, values): import _formatting Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/stringtype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/stringtype.py Mon Jan 17 19:19:37 2005 @@ -46,8 +46,7 @@ w_obj = space.str(w_obj) if space.is_true(space.is_(w_stringtype, space.w_str)): return w_obj # XXX might be reworked when space.str() typechecks - value = space.unwrap(w_obj) - assert isinstance(value, str) # XXX should be checked by space.str() + value = space.str_w(w_obj) w_obj = space.allocate_instance(W_StringObject, w_stringtype) w_obj.__init__(space, value) return w_obj From pedronis at codespeak.net Mon Jan 17 19:33:01 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 19:33:01 +0100 (MET) Subject: [pypy-svn] r8347 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117183301.85E2827BB9@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 19:33:01 2005 New Revision: 8347 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py Log: more type specific unwraps Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/objspace.py Mon Jan 17 19:33:01 2005 @@ -288,7 +288,7 @@ def newstring(self, chars_w): try: - chars = [chr(self.unwrap(w_c)) for w_c in chars_w] + chars = [chr(self.int_w(w_c)) for w_c in chars_w] except TypeError: # chr(not-an-integer) raise OperationError(self.w_TypeError, self.wrap("an integer is required")) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py Mon Jan 17 19:33:01 2005 @@ -68,13 +68,13 @@ def indices3(space, w_slice, length): w_result = slice_indices3(space, w_slice, space.wrap(length)) w_1, w_2, w_3 = space.unpacktuple(w_result, 3) - return space.unwrap(w_1), space.unwrap(w_2), space.unwrap(w_3) + return space.int_w(w_1), space.int_w(w_2), space.int_w(w_3) def indices4(space, w_slice, length): w_result = slice_indices4(space, w_slice, space.wrap(length)) w_1, w_2, w_3, w_4 = space.unpacktuple(w_result, 4) - return (space.unwrap(w_1), space.unwrap(w_2), - space.unwrap(w_3), space.unwrap(w_4)) + return (space.int_w(w_1), space.int_w(w_2), + space.int_w(w_3), space.int_w(w_4)) register_all(vars(), globals()) From pedronis at codespeak.net Mon Jan 17 19:54:39 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 19:54:39 +0100 (MET) Subject: [pypy-svn] r8348 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117185439.83BC627BB9@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 19:54:39 2005 New Revision: 8348 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/unicodeobject.py Log: here we are also cheating, still changed the one unwrap for which it made sense Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/unicodeobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/unicodeobject.py Mon Jan 17 19:54:39 2005 @@ -6,7 +6,7 @@ # string-to-unicode delegation def delegate__String(space, w_str): - return W_UnicodeObject(space, unicode(space.unwrap(w_str))) + return W_UnicodeObject(space, unicode(space.str_w(w_str))) delegate__String.result_class = W_UnicodeObject delegate__String.priority = PRIORITY_CHANGE_TYPE delegate__String.can_fail = True From pedronis at codespeak.net Mon Jan 17 20:12:40 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 17 Jan 2005 20:12:40 +0100 (MET) Subject: [pypy-svn] r8349 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050117191240.099E527BB9@code1.codespeak.net> Author: pedronis Date: Mon Jan 17 20:12:39 2005 New Revision: 8349 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objecttype.py pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/typetype.py Log: done (for now) with objspace/std next: module and unwrapping signatures for gateways open: do we want to rename the generic unwrap to make it clearer that is not meant to be translated more appropriate name for unwrap_builtin Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/objecttype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/objecttype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/objecttype.py Mon Jan 17 20:12:39 2005 @@ -7,8 +7,8 @@ def descr__repr__(space, w_obj): w = space.wrap - classname = space.unwrap(space.getattr(space.type(w_obj), w("__name__"))) - id = space.unwrap(space.id(w_obj)) + classname = space.str_w(space.getattr(space.type(w_obj), w("__name__"))) + id = space.int_w(space.id(w_obj))# xxx ids could be long return w("<%s object at 0x%x>" % (classname, id)) def descr__str__(space, w_obj): @@ -16,6 +16,7 @@ def descr__hash__(space, w_obj): # XXX detect non-hashable instances (the ones overriding comparison only) + # XXX ids could be long return space.id(w_obj) def descr__class__(space, w_obj): Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py Mon Jan 17 20:12:39 2005 @@ -129,7 +129,7 @@ return space.wrap("" % w_obj.name) # XXX remove 'pypy' def getattr__Type_ANY(space, w_type, w_name): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_type, name) if w_descr is not None: if space.is_data_descr(w_descr): @@ -143,7 +143,7 @@ raise OperationError(space.w_AttributeError,w_name) def setattr__Type_ANY_ANY(space, w_type, w_name, w_value): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_type, name) if w_descr is not None: if space.is_data_descr(w_descr): @@ -151,7 +151,7 @@ w_type.dict_w[name] = w_value def delattr__Type_ANY(space, w_type, w_name): - name = space.unwrap(w_name) + name = space.str_w(w_name) w_descr = space.lookup(w_type, name) if w_descr is not None: if space.is_data_descr(w_descr): Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/typetype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/typetype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/typetype.py Mon Jan 17 20:12:39 2005 @@ -6,14 +6,13 @@ "This is used to create user-defined classes only." from pypy.objspace.std.typeobject import W_TypeObject # XXX check types - name = space.unwrap(w_name) + name = space.str_w(w_name) assert isinstance(name, str) bases_w = space.unpackiterable(w_bases) dict_w = {} dictkeys_w = space.unpackiterable(w_dict) for w_key in dictkeys_w: - key = space.unwrap(w_key) - assert isinstance(key, str) + key = space.str_w(w_key) dict_w[key] = space.getitem(w_dict, w_key) w_type = space.allocate_instance(W_TypeObject, w_typetype) w_type.__init__(space, name, bases_w or [space.w_object], dict_w) From hpk at codespeak.net Tue Jan 18 10:40:04 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 10:40:04 +0100 (MET) Subject: [pypy-svn] r8361 - pypy/dist/pypy/documentation Message-ID: <20050118094004.4C7A927BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 10:40:04 2005 New Revision: 8361 Added: pypy/dist/pypy/documentation/annotation.txt - copied unchanged from r8359, pypy/trunk/doc/translation/annotation.txt pypy/dist/pypy/documentation/architecture.txt - copied unchanged from r8359, pypy/trunk/doc/architecture.txt pypy/dist/pypy/documentation/checking_ReST.txt - copied unchanged from r8359, pypy/trunk/doc/devel/checking_ReST.txt pypy/dist/pypy/documentation/cmodules.txt - copied unchanged from r8359, pypy/trunk/doc/cmodules.txt pypy/dist/pypy/documentation/coding-style.txt - copied unchanged from r8359, pypy/trunk/doc/devel/coding-style.txt pypy/dist/pypy/documentation/controlflow.txt - copied unchanged from r8359, pypy/trunk/doc/translation/controlflow.txt pypy/dist/pypy/documentation/developers.txt - copied unchanged from r8359, pypy/trunk/doc/developers.txt pypy/dist/pypy/documentation/goals.txt - copied unchanged from r8359, pypy/trunk/doc/goals.txt pypy/dist/pypy/documentation/howtopypy.txt - copied unchanged from r8359, pypy/trunk/doc/howtopypy.txt pypy/dist/pypy/documentation/howtosvn.txt - copied unchanged from r8359, pypy/trunk/doc/devel/howtosvn.txt pypy/dist/pypy/documentation/newrepolayout.txt - copied unchanged from r8359, pypy/trunk/doc/newrepolayout.txt pypy/dist/pypy/documentation/optionaltool.txt - copied unchanged from r8359, pypy/trunk/doc/devel/optionaltool.txt pypy/dist/pypy/documentation/readme.txt - copied unchanged from r8359, pypy/trunk/doc/readme.txt pypy/dist/pypy/documentation/testdesign.txt - copied unchanged from r8359, pypy/trunk/doc/devel/testdesign.txt pypy/dist/pypy/documentation/wrapping.txt - copied unchanged from r8359, pypy/trunk/doc/wrapping.txt Log: flatly add various developer documentation files From hpk at codespeak.net Tue Jan 18 10:41:32 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 10:41:32 +0100 (MET) Subject: [pypy-svn] r8362 - in pypy/trunk/doc: . devel funding objspace translation Message-ID: <20050118094132.3B4F327BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 10:41:31 2005 New Revision: 8362 Removed: pypy/trunk/doc/architecture.txt pypy/trunk/doc/cmodules.txt pypy/trunk/doc/devel/ pypy/trunk/doc/developers.txt pypy/trunk/doc/goals.txt pypy/trunk/doc/howtopypy.txt pypy/trunk/doc/newrepolayout.txt pypy/trunk/doc/objspace/ pypy/trunk/doc/readme.txt pypy/trunk/doc/translation/annotation.txt pypy/trunk/doc/translation/controlflow.txt pypy/trunk/doc/wrapping.txt Modified: pypy/trunk/doc/funding/TODO Log: removed moved documentation ... Deleted: /pypy/trunk/doc/architecture.txt ============================================================================== --- /pypy/trunk/doc/architecture.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,312 +0,0 @@ -Overview on PyPy's current architecture (Dec. 2003) -=================================================== - - -Introduction and higher level picture -------------------------------------- - -The various parts of PyPy have always been under more or less heavy -refactoring during our five one-week sprints in 2003. However, the -higher level architecture remains rather simple and unchanged. There -are two independent basic subsystems: - -- the *standard interpreter* which implements the Python language - and is composed out of two components: - - - the *plain interpreter* which is responsible for interpreting - code objects and implementing bytecodes, - - - the *standard object space* which implements creation, access and - modification of application level objects, - - Note that the *standard interpreter* can run fine on top of CPython - (the C Implementation of Python led by Guido van Rossum) but of course - the double-interpretation penalty lets us interpret python programs - rather slowly. - -- the *translation process* which aims at producing a different (low-level) - representation of our standard interpreter. The *translation process* - is done in three steps: - - - producing a *flow graph* representation of the standard interpreter. - A combination of a *plain interpreter* and a *flow object space* - performs "abstract interpretation" to record the flow of objects - and execution throughout a python program into such a *flow graph*. - - - the *annotator* which performs type inference on the flow graph - - - the *translator* which translates the (annotated) flow graph into - another language, currently Pyrex/C and LISP. - -Please note that we are using the term *interpreter* most often in -reference to the *plain interpreter* which just knows enough to read, -dispatch and implement *bytecodes* thus shuffling objects around on the -stack and between namespaces. The (plain) interpreter is completly -ignorant of how to access, modify or construct objects and their -structure and thus delegates such operations to a so called "Object Space". - -XXX mention Parser and compiler (we have one available since the Berlin -sprint but it is not integrated) - -The Interpreter -=============== - -The interpreter handles python code objects. The interpreter can build -code objects from Python sources, when needed, by invoking Python's -builtin compiler (we also have a way of constructing those code objects -from python code only, but we have not integrated it yet). Code objects -are a nicely preprocessed, structured representation of source code, and -their main content is *bytecode*. In addition, code objects also know -how to create a *frame* object which has the responsibility to -*interpret* a code object's bytecode. Each bytecode is implemented by a -python function, which, in turn, delegates operations on -application-level objects to an object space. - -The Object Space -================ - -The object space creates all objects and knows how to perform operations -on the objects. You may think of an object space as being a library -offering a fixed API, a set of *operations*, with implementations that -correspond to the known semantics of Python objects. An example of an -operation is *add*: add's implementations are, for example, responsible -for performing numeric addition when add works on numbers, concatenation -when add works on built-in sequences. - -All object-space operations take and return "application level" objects. -There is only one, very simple, object-space operation which allows the -interpreter to gain some knowledge about the value of an -application-level object: ``is_true()``, which returns a boolean -interpreter-level value. This is necessary to implement, for example, -if-statements (or rather, to be pedantic, to implement the -conditional-branching bytecodes into which if-statements get compiled). - -We currently have four working object spaces which can be plugged into -the interpreter: - -- The Trivial Object Space, which basically delegates almost all - operations to the underlying CPython interpreter. It was, and still - is, used to test our interpreter. Alhough it is not essential, it - remains useful for testing, and thus it is here to stay. - -- The Standard Object Space, which is an almost complete implementation - of the various Python objects. This is the main focus of this - document, since the Standard Object Space, together with the - interpreter, is the foundation of our Python implementation. - -- the Flow Object Space, which transforms a python program into a - flow-graph representation. The Flow Object Space performs this - transformation task through "abstract interpretation", which we will - explain later in this document. - -- the Trace Object Space, which wraps either the trivial or the standard - object space in order to trace the execution of bytecodes, frames and - object space operations. - -The Standard Object Space -========================= - -The Standard Object Space implements python objects and types, and all -operations on them. It is thus an essential component in order to reach -CPython compatibility. - -The implementations of ints, floats, strings, dicts, lists, etc, all -live in separate files, and are bound together by a "multimethod" -mechanism. Multimethods allow a caller - most notably the interpreter - -to stay free from knowing anything about objects' implementations. Thus -multimethods implement a way of delegating to the right implementation -based on the passed in objects (objects previously created by the same -subsystem). We examine how the multimethod mechanism works through an -example. - -We consider the add-operation of ``int`` and ``float`` objects, and -disregard all other object types for the moment. There is one -multimethod ``add``, and both relevant implementations, ``add(intimpl, -intimpl)`` and ``add(floatimpl, floatimpl)``, *register* with that one -``add`` multimethod. - -When we have the expression ``2+3`` in our application program, the -interpreter creates an application-level object containing ("wrapping") -the value ``2`` and another one containing the value ``3``. We talk -about them as ``W_Int(2)`` and ``W_Int(3)`` respectively. The -interpreter then calls the Standard Object Space with ``add(W_Int(2), -W_Int(3))``. - -The Object Space then examines the objects passed in, and delegates -directly to the ``add(intimpl, intimpl)`` function: since this is a -"direct hit", the multimethod immediately dispatches the operation to -the correct implementation, i.e., the one registered as the -implementation for this signature. - -If the multimethod doesn't have any registered functions for the exact -given signature, as would be the case for example for the expression -``2+3.0``, the multimethod tests if it can use coercion to find a -function with a signature that works. In this case we would coerce -``W_Int(2)`` to ``W_Float(2.0)`` in order to find a function in the -multimethod that has a correct signature. Note that the multimethod -mechanism is still considered a major refactoring target, since it is -not easy to get it completly right, fast and accurate. - -Application-level and interpreter-level execution and objects -============================================================= - -Since Python is used for implementing all of our code base, there is a -crucial distinction to be aware of: *interpreter-level* objects versus -*application level* objects. The latter are the ones that you deal with -when you write normal python programs. Interpreter-level code, however, -cannot invoke operations nor access attributes from application-level -objects. You will immediately recognize any interpreter level code in -PyPy, because all variable and object names start with a ``w_``, which -indicates that they are "wrapped" application-level values. - -Let's show the difference with a simple example. To sum the contents of -two variables ``a`` and ``b``, typical application-level code is ``a+b`` --- in sharp contrast, typical interpreter-level code is ``space.add(w_a, -w_b)``, where ``space`` is an instance of an object space, and ``w_a`` -and ``w_b`` are typical names for the *wrapped* versions of the two -variables. - -It helps to remember how CPython deals with the same issue: interpreter -level code, in CPython, is written in C, and thus typical code for the -addition is ``PyNumber_Add(p_a, p_b)`` where ``p_a`` and ``p_b`` are C -variables of type ``PyObject*``. This is very similar to how we write -our interpreter-level code in Python. - -Moreover, in PyPy we have to make a sharp distinction between -interpreter- and application-level *exceptions*: application exceptions -are always contained inside an instance of ``OperationError``. This -makes it easy to distinguish failures in our interpreter-level code from -failures appearing in a python application level program that we are -interpreting. - - -Application level is often preferable -------------------------------------- - -Application-level code is substantially higher-level, and therefore -correspondingly easier to write and debug. For example, suppose we want -to implement the ``update`` method of dict objects. Programming at -application level, we can write an obvious, simple implementation, one -that looks like an **executable definition** of ``update``, for -example:: - - def update(self, other): - for k in other.keys(): - self[k] = other[k] - -If we had to code only at interpreter level, we would have to code -something much lower-level and involved, say something like:: - - def update(space, w_self, w_other): - w_keys = space.call_method(w_other, 'keys') - w_iter = space.iter(w_keys) - while True: - try: w_key = space.next(w_iter) - except NoValue: break - w_value = space.getitem(w_other, w_key) - space.setitem(w_self, w_key, w_value) - -This interpreter-level implementation looks much more similar to the C -source code, although it is probably still more readable. In any case, -it should be obvious that the application-level implementation is -definitely more readable, more elegant and more maintainable than the -interpreter-level one. - -In fact, in almost all parts of PyPy, you find application level code in -the middle of interpreter-level code. Apart from some bootstrapping -problems (application level functions need a certain initialization -level of the object space before they can be executed), application -level code is usually preferable. We have an abstraction (called -'Gateway') which allows the caller of a function to remain ignorant of -whether a particular function is implemented at application or -interpreter level. - -Wrapping -======== - -The ``w_`` prefixes so lavishly used in the previous example indicate, -by PyPy coding convention, that we are dealing with *wrapped* objects, -that is, interpreter-level objects which the object space constructs to -implement corresponding application-level objects. Each object space -supplies ``wrap`` and ``unwrap`` operations that move between the two -levels for objects of simple built-in types; each object space also -implements other Python types with suitable interpreter-level classes -with some amount of internal structure. - -For example, an application-level Python ``list`` is implemented as an -instance of ``W_ListObject``, which has an instance attribute -``ob_item`` (an interpreter-level list which contains the -application-level list's items as wrapped objects) and another attribute -``ob_size`` which records the application-level list's length (we want -to be able to do "over-allocation" in ``ob_item``, for the same reasons -of performance that lead CPython to do it, and therefore the length of -``ob_item`` is allowed to be greater than the length of the -application-level list -- it is for this reason that the length in -question has to be explicitly recorded in ``ob_size``). - -See ``wrapping.txt`` for more details. - - -RPython, the Flow Object Space and translation -============================================== - -One of PyPy's -term objectives is to enable translation of our -interpreter and standard object space into a lower-level language. In -order for our translation and type inference mechanisms to work -effectively, we need to restrict the dynamism of our interpreter-level -Python code at some point. However, in the start-up phase, we are -completly free to use all kind of nice python constructs, including -metaclasses and execution of dynamically constructed strings. However, -when the initialization phase (mainly, the function -``objspace.initialize()``) finishes, all code objects involved need to -adhere to a (non-formally defined) more static subset of Python: -Restricted Python, also known as 'RPython'. - -The Flow Object Space then, with the help of our plain interpreter, -works through those initialized "RPython" code objects. The result of -this *abstract interpretation* is a flow graph: yet another -representation of a python program, but one which is suitable for -applying translation and type inference techniques. The nodes of the -graph are basic blocks consisting of Object Space operations, flowing -of values, and an exitswitch to one, two or multiple links which connect -each basic block to other basic blocks. - -The flow graphs are fed as input into the Annotator. The Annotator, -given entry point types, infers the types of values that flow through -the program variables. Here, one of the informal definitions of RPython -comes into play: RPython code is restricted in such a way that the -translator is able to compile low-level **typed** code. How much -dynamism we allow in RPython depends, and is restricted by, the Flow -Object Space and the Annotator implementation. The more we can improve -this translation phase, the more dynamism we can allow. In some cases, -however, it will probably be more feasible and practical to just get rid -of some of the dynamism we use in our interpreter level code. It is -mainly because of this trade-off situation that we don't currently try -to formally define 'RPython'. - -The actual low-level code (and, in fact, also other high-level code) is -emitted by "visiting" the type-annotated flow graph. Currently, we have -a Pyrex-producing backend, and a Lisp-producing backend. We use (a -slightly hacked version of) Pyrex to generate C libraries. Since Pyrex -also accepts plain non-typed python code, we can test translation even -though type annotation is not complete. - -Trace Object Space -================== - -A recent addition is the Trace Object space, which wraps a standard or -trivial object space in order to trace all object space operations, -frame creation, deletion and bytecode execution. The ease with which -the Trace Object Space was implemented at the Amsterdam Sprint -underlines the power of the Object Space abstraction. (Of course, the -previously-implemented Flow Object Space producing the flow graph -already was proof enough). - -There are certainly many more possibly useful Object Space ideas, such -as a ProxySpace that connects to a remote machine where the actual -operations are performed. At the other end, we wouldn't need to change -object spaces at all in order to extend or modify the interpreter, e.g. -by adding or removing some bytecodes. Thus, the interpreter and -object-space cooperation nicely splits the python runtime into two -reasonably-independent halves, cooperating along a reasonably narrow -interface, and suitable for multiple separate implementations. Deleted: /pypy/trunk/doc/cmodules.txt ============================================================================== --- /pypy/trunk/doc/cmodules.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,208 +0,0 @@ -PyPy shares a common need with other python reimplementations: -reimplementing c-coded modules in Python. The more plain -python code there is the less code needs to be ported either -Python or to the implementation language (e.g. C# for IronPython_). - -In the course of an email discussion_ Anthony Baxter came up with -a annotated list of modules and some rough categorization of -the to-be-or-has-been ported modules. The list doesn't claim -to be exhaustive and should certainly be worked on. - -Probably doable ---------------- - -These ones are probably achievable, although you might think -otherwise. - -_bisectmodule - already exists - -_codecsmodule - -_csv - already exists? - -_heapqmodule - already exists - -_hotshot - -_localemodule - -_randommodule - already exists but with a lesser generator - -_sre - already exists? - -_weakref - -arraymodule - -audioop - -binascii - -cPickle - already exists - -cStringIO - already exists - -cgensupport - -cmathmodule - -collectionsmodule - Raymond Hettinger has an ASPN recipe (which has a 'deque' drop-in replacement): - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 - -cryptmodule - -datetimemodule - already exists - -gcmodule - -imageop - -imgfile - -itertoolsmodule - the docs include pure python equivalents in a form -suitable for cut and pasting - -mathmodule - -md5module - done - -operator - done in PyPy - -parsermodule - already exists? - -rgbimgmodule - -sgimodule - -shamodule - done - -stropmodule - -structmodule - -symtablemodule - -syslogmodule - -timingmodule - -unicodedata - -yuvconvert - -zipimport - -Deprecated ----------- - -These modules are deprecated - -regexmodule - -regexpr - -rotormodule - -mpzmodule - -Links in an external library ----------------------------- - -These are all wrappers around external C libraries. Rewriting them -from scratch is really not practical. - -_bsddb - -_curses_panel - -_cursesmodule - -_ssl - -_tkinter - -almodule - -bsddbmodule - -bz2module - -cdmodule - -clmodule - -dbmmodule - -flmodule - -fmmodule - -gdbmmodule - -glmodule - -nismodule - -puremodule - -pyexpat - -readline (replace with pyrepl?) - -svmodule - -termios - -tkappinit - -zlibmodule - -System specific ---------------- - -These are modules that are wrappers around system calls -and the like. Rewriting them in pure Python will still -need a way to invoke the underlying calls - and will probably -be different for each platform (pypy, pycore, ironpython, &c). -A lot of these are also a mass of #ifdefs for various broken -operating systems. - -dlmodule - -errnomodule - -fcntlmodule - -fpectlmodule - -fpetestmodule - -grpmodule - -linuxaudiodev - -mmapmodule - -ossaudiodev - -posixmodule - -pwdmodule - -resource - -selectmodule - -signalmodule - -socketmodule - -sunaudiodev - -threadmodule - -timemodule - - -.. _IronPython: http://ironpython.com/ -.. _discussion: http://codespeak.net/pipermail/pypy-dev/2004q3/001509.html Deleted: /pypy/trunk/doc/developers.txt ============================================================================== --- /pypy/trunk/doc/developers.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,20 +0,0 @@ - - -pypy project developers and contributors:: - - Armin Rigo Holger Krekel - Samuele Pedroni Christian Tismer - Michael Hudson Laura Creighton - Jacob Hallen Alex Martelli - Richard Emslie Seo Sanghyeon - Anna Ravencroft Guido Van Rossum - Anders Lehmann Tomek Meka - Jiwon Seo Stephan Diehl - Jens-Uwe Mager Jonathan David Riehl - Guenter Jantzen Stefan Schwarzer - Dinu Gherman Patrick Maupin - Rocco Moretti Andreas Friedge - Theo de Ridder Olivier Dormond - Bob Ippolito Marius Gedminas - -PyPy Webpage: http://codespeak.net/pypy Modified: pypy/trunk/doc/funding/TODO ============================================================================== --- pypy/trunk/doc/funding/TODO (original) +++ pypy/trunk/doc/funding/TODO Tue Jan 18 10:41:31 2005 @@ -9,3 +9,63 @@ reaorganize all the B6.7 files (create missing and rename existing) * Laura has to create B7 + +quick Review of all sections (saturday noon) +-------------------------------------------- + +section/file status + +B0.0_preamble.txt has consortium list, nothing else so far +B0.1_summary.txt should contain Alastair's abstract. +B1.0_objectives.txt contains all 1.* sections + this is done, up to proof-reading and checking by Alistair(?), + only point we the new abstract we should say + Python more and VHLL language a bit less or define. +B1._obj_from_badB2.txt not used, we could extract parts. ok? + +B2.0.0_new_relevance.txt needs serious work. Alastair? + (laura is working on it right now) +b2.txt laura's version. see last item. + +B3.0_impact.txt +B3.1_standards.txt +B3.2.3_european_dimension.txt +B3.2.strategic_impact.txt + Bea is working on B3.* - should be merged into a single document. + +B4.0_resources.txt needs to be completed. +B4.1_subcontracting.txt +B4.2_other_countries.txt +B4.3_participants.txt +B4.4_quality_SMEs.txt in good shape, need final retouches + +# break here: jacob wants to present his list of todos in a few minutes. + + + +B4.5_resources.txt # (ar) is something going on here ? i used to have some sprint info there (hpk) but i moved it to other +secs# (ar) i mean, what are we doing right now ?? i am helping bea to install an svn-client :-(, however let's start +B4.6_finance.txt +B4.7_effort_form.txt +B5.0_manage_bea.txt +B6.0_detailed_implementation.txt +B6.1_plan_introduction.txt +B6.2_tech_aspects.txt +B6.3_risks_minimise.txt +B6.4_gantt.txt +B6.5_workpackage_list.txt +B6.6_deliverables_list.txt +B6.7.wp01_management.txt +B6.7.wp02_maintenance.txt +B6.7.wp03_synchronisation.txt +B6.7.wp04_core.txt +B6.7.wp05_translation.txt +B6.7.wp06_dynamic_optimization.txt +B6.7.wp07_translator_optimisations.txt +B6.7.wp08_core_optimisations.txt +B6.7.wp09_language_extensions.txt +B6.7.wp10_app_language_ext.txt +B6.7.wp11_validations.txt +B6.7.wp12_integration_config.txt +B6.7.wp14_documentation.txt +B7.0_other_issues.txt Deleted: /pypy/trunk/doc/goals.txt ============================================================================== --- /pypy/trunk/doc/goals.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,376 +0,0 @@ -**Infrastructure and tools** - -Supporting the PyPy project by producing and enhancing the tools. - -Support the development process with reusing existing or developing -new debugging opensource tools. - -- provide access over http/https and ssh server - -- build extensions for automatic document extraction - -- implement a search facility over all content - -- maintain and enhance website infrastructure - -- setup a mirror repository which is kept up-to-date and which - can be used readonly in case of failure of the main repository. - -- Design a strict backup policy. - -- help with automated testing - - XXX add what more do we want to do? - -- http-server to present runtime/introspection information aiding - debugging and understanding of PyPy internals - -- automated (unit-)testing framework with html/pdf reports - -**Synchronisation with Standard Python** - -- Keeping PyPy in sync with potential changes to Standard Python. - -- Support a subset of the CPython API for compatibility with extension modules. - -- Facilitate porting of extension modules to PyPy. - -- What's new since 2.2? see http://www.python.org/doc/2.3.3/whatsnew -- Thank you amk! - -**PEPS** - -+ PEP 218: A Standard Set Datatype -- set module -- - -+ PEP 263 defining Python Source Code encodings - -+ PEP 273 Importing Modules from Zip Archives -- zipimport module -- - -+ PEP 277: Unicode file name support for Windows NT - -+ PEP 278: Universal Newline Support - -+ PEP 279: enumerate() - -+ PEP 282: The logging Package - -+ PEP 285: A Boolean Type - -+ PEP 293: Codec Error Handling Callbacks - -+ PEP 301: Package Index and Metadata for Distutils - -+ PEP 302: New Import Hooks - -+ PEP 307: Pickle Enhancements - -**Check and see we have implemented these** - -* Extended Slices - -* The yield statement is now always a keyword - -* new built-in function enumerate() - -* Two new constants, True and False - -* The int() type constructor will now return a long integer instead of - raising an OverflowError when a string or floating-point number is too - large to fit into an integer. This can lead to the paradoxical result - that isinstance(int(expression), int) is false. - -* Built-in types now support the extended slicing syntax - -* A new built-in function, sum(iterable, start=0), adds up the numeric - items in the iterable object and returns their sum. sum() only accepts - numbers, meaning that you can't use it to concatenate a bunch of strings. - -does it handle mixed floats and ints? - -* list.insert(pos, value) used to insert value at the front of the list - when pos was negative. The behaviour has now been changed to be consistent - with slice indexing, so when pos is -1 the value will be inserted before - the last element, and so forth. - -so to insert at the front? - -* list.index(value), which searches for value within the list and - returns its index, now takes optional start and stop arguments to limit - the search to only part of the list. - -* Dictionaries have a new method, pop(key[, default]), that returns the - value corresponding to key and removes that key/value pair from the - dictionary. If the requested key isn't present in the dictionary, - default is returned if it's specified and KeyError raised if it isn't. - -* There's also a new class method, dict.fromkeys(iterable, value), that - creates a dictionary with keys taken from the supplied iterator iterable - and all values set to value, defaulting to None. - - Also, the dict() constructor now accepts keyword arguments to simplify - creating small dictionaries: - - >>> dict(red=1, blue=2, green=3, black=4) - {'blue': 2, 'black': 4, 'green': 3, 'red': 1} - - -* The assert statement no longer checks the __debug__ flag, so you can no - longer disable assertions by assigning to __debug__. Running Python with - the -O switch will still generate code that doesn't execute any assertions. - -So what if you want to disable assertions just within one module? - -* Most type objects are now callable, so you can use them to create new - objects such as functions, classes, and modules. (This means that the - new module can be deprecated in a future Python version, because you - can now use the type objects available in the types module.) For example, - you can create a new module object with the following code: - - >>> import types - >>> m = types.ModuleType('abc','docstring') - >>> m - - >>> m.__doc__ - 'docstring' - -* A new warning, PendingDeprecationWarning was added to indicate features - which are in the process of being deprecated. The warning will not be - printed by default. To check for use of features that will be deprecated - in the future, supply -Walways::PendingDeprecationWarning:: on the - command line or use warnings.filterwarnings(). - -* The process of deprecating string-based exceptions, as in - raise "Error occurred", has begun. Raising a string will now trigger - PendingDeprecationWarning. - -* Using None as a variable name will now result in a SyntaxWarning warning. - In a future version of Python, None may finally become a keyword. - -* The xreadlines() method of file objects, introduced in Python 2.1, - is no longer necessary because files now behave as their own - iterator. xreadlines() was originally introduced as a faster way to - loop over all the lines in a file, but now you can simply write - for line in file_obj. File objects also have a new read-only encoding - attribute that gives the encoding used by the file; Unicode strings - written to the file will be automatically converted to bytes using - the given encoding. - -* The method resolution order used by new-style classes has changed, - though you'll only notice the difference if you have a really - complicated inheritance hierarchy. Classic classes are unaffected by - this change. Python 2.2 originally used a topological sort of a - class's ancestors, but 2.3 now uses the C3 algorithm as described in - the paper *A Monotonic Superclass Linearization for Dylan*. To - understand the motivation for this change, read Michele Simionato's - article *Python 2.3 Method Resolution Order*, or read the thread - on python-dev starting with the message at - http://mail.python.org/pipermail/python-dev/2002-October/029035.html. - Samuele Pedroni first pointed out the problem and also implemented the fix - by coding the C3 algorithm. - -* Python runs multithreaded programs by switching between threads - after executing N bytecodes. The default value for N has been - increased from 10 to 100 bytecodes, speeding up single-threaded - applications by reducing the switching overhead. Some multithreaded - applications may suffer slower response time, but that's easily - fixed by setting the limit back to a lower number using - sys.setcheckinterval(N). The limit can be retrieved with the new - sys.getcheckinterval() function. - -* One minor but far-reaching change is that the names of extension - types defined by the modules included with Python now contain the - module and a "." in front of the type name. For example, in Python - 2.2, if you created a socket and printed its __class__, you'd get - this output: - - >>> s = socket.socket() - >>> s.__class__ - - - In 2.3, you get this: - - >>> s.__class__ - - -* One of the noted incompatibilities between old- and new-style - classes has been removed: you can now assign to the __name__ and - __bases__ attributes of new-style classes. There are some - restrictions on what can be assigned to __bases__ along the lines of - those relating to assigning to an instance's __class__ attribute. - -**String Changes** - -* The in operator now works differently for strings. Previously, when - evaluating X in Y where X and Y are strings, X could only be a - single character. That's now changed; X can be a string of any - length, and X in Y will return True if X is a substring of Y. If X - is the empty string, the result is always True. - - >>> 'ab' in 'abcd' - True - >>> 'ad' in 'abcd' - False - >>> '' in 'abcd' - True - -* The strip(), lstrip(), and rstrip() string methods now have an - optional argument for specifying the characters to strip. The - default is still to remove all whitespace characters: - -* The startswith() and endswith() string methods now accept negative - numbers for the start and end parameters. - -* Another new string method is zfill(), originally a function in the - string module. zfill() pads a numeric string with zeros on the left - until it's the specified width. Note that the % operator is still - more flexible and powerful than zfill(). - -* A new type object, basestring, has been added. Both 8-bit strings - and Unicode strings inherit from this type, so isinstance(obj, basestring) - will return True for either kind of string. It's a completely abstract - type, so you can't create basestring instances. - -* Interned strings are no longer immortal and will now be - garbage-collected in the usual way when the only reference to them - is from the internal dictionary of interned strings. - -**Replace PyPy Core** - -Building a complete Python interpreter written in Python, -using a subset of Python that avoids dynamic featureslll -which would impair the objectives of RPython. - -- Design and implement the PyPy bytecode interpreter and - build an object space library in RPython. - The resulting interpreter must cover the complete Python - language specification. -- mostly done, test coverage. - -- Port the built-in Python library to PyPy (functions, types and - modules currently implemented in C) -- types needs refactoring, - the rest is mostly done. Anthony Baxter has given us a very useful - list of the cmodules_ we need to consider porting. - -- Decide on a case-by-case basis which features are to - be implemented using RPython or just general Python. -- moving target. - -- Implement a Python parser and bytecode compiler in Python. - -- we have something, but it is not well integrated. - -- A partial Python implementation that passses 75% of the official - Python test suite that don't depend on extension modules. - -- write this test and then pass it. - -**The PyPy Translation** - -- Analysis and translation of the PyPy core into efficient low-level code - (C, Pyrex, Java, others). - moving target - -- Provide a Runtime Library for the translated versions - of PyPy. - not even started - -- Create a code analysis tool for a subset of the Python - language (RPython). Coordinate the definition of RPython - being the implementation language of the core. - - - we can analyse functions, but not classes, modules, spaces etc. - -- Complete implementation of Python, conforming to the language - definition and passing all relevant tests of the official Python - test suite. -- global goal, which we will think more about when - it is very close to being done. - -**Stackless Integration + More Performance Hacks** - -- Identification and Implementation of Optimisations through modifications - of the Translator. - -- Enable Massive Parallelism in a Single Thread. - -- Provide support for real-time parallelism. - -- Allow Pickling of a Running Program. - -- Enhance the translator to support continuation passing - style by integrating technology from the Stackless project. - -- Implement the necessary runtime system to support massive parallelism. - -- Implement a single-threaded, pre-emptive scheduler with - priorities, complementing the OS threads. - -- Study approaches concerning code size vs. speed trade-offs. - -- Implement and compare different object layout and memory management - strategy or strategies. - -- Enhance multimethod dispatching. - -- Implement schemes of pointer tagging. - -- Create reports and merge the results back into the optimization effort. - -**Psyco Integration** - -- Outperform the state-of-the art (Psyco, Stackless). - -- Enhance PyPy to dynamically adapt to its run-time environment and - to the characteristics of the running program. Dramatically - increase speed by enabling Just-In-Time compilation and - specialization. - -- Address multiple processor architectures. - -- Apply and enhance techniques from the Psyco project. Promote parts - of the static translator to be used for run-time specialization. - -- Design and implement a back-end component for dynamically emitting - machine code for multiple processor architectures. Enable dynamic - foreign function calls. - -- Research optimisation heuristics for the Just-In-Time compiler. - -- A Just-In-Time compiler for PyPy !!! Outperform the - state-of-the art (Psyco, Stackless). - -**Embed in Specialized Hardware** - -if we get funding. - -**Implement Security, Distribution and Persistence** - -- Research and validate the flexibility of PyPy by building key middleware - features into the language itself. - -- Analyze and implement security models at the language level. - -- Implement the "RExec" restricted execution model. (It was removed - from the official Python implementation because it is false security.) - -- Analyze and implement distributed execution models at the language level. - -- Implement network-transparent execution of Python programs. (Typical - libraries require programs to be aware of the remote execution model.) - -- Analyze and implement persistence at the language level. -- talk to - Patrick O'Brien who is really hot for the idea. - -- Implement an orthogonally persistent object space for Python programs. - (Persistence is never fully orthogonal without advanced language support.) - -**PyPy A la Carte** - -- Develop tools that will allow to chose from available features and runtime - restrictions to build a custom PyPy version. - -- Analyse and integrate all results from the results of other workpackages. - This involves identifying and resolving conflicts which could prevent - a combintation of desired optimization goals. - -- Implement user interfaces to select features and runtime restrictions. - Provide a way to automatically build a PyPy custom version for different - memory, performance and extension requirements. - -- Make a build- and configuration tool that allows to build custom PyPy - versions suitable for specialized environments such as small or very large - computing devices. - -.. _cmodules: http://codespeak.net/pypy/index.cgi?doc/cmodules.html \ No newline at end of file Deleted: /pypy/trunk/doc/howtopypy.txt ============================================================================== --- /pypy/trunk/doc/howtopypy.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,205 +0,0 @@ -================================== -Getting started with PyPy -================================== - -PyPy sources can be browsed on the web at: - - ``http://codespeak.net/svn/pypy/trunk/`` - -Once you are ready to download and try PyPy out, -follow these instructions, which assume that you -are working in a DOS box (Windows) or terminal (MacOS/X or Linux). - -1. Download subversion_ if you do not already have it. - - -2. Change to the directory where you wish to install the source tree, - and use subversion to download the source:: - - svn co http://codespeak.net/svn/pypy/trunk/src - - This will create a subdirectory named ``src``, and will create - the PyPy source tree under this directory. - - - If desired, you can also download the documentation:: - - svn co http://codespeak.net/svn/pypy/trunk/doc - - -3. To start interpreting Python with PyPy, use Python 2.3 or greater:: - - cd src/pypy/interpreter - python py.py - - After a few seconds, you should be at the PyPy prompt, which is - the same as the Python prompt, but with an extra ">". - - -4. Now you are ready to start running Python code. Some real Python - modules will not run yet, and others will run too slowly to be - worth waiting for, but a few are fun to run:: - - >>>> import pystone - >>>> pystone.main(10) - - Note that this is a slightly modified version of pystone -- the - original version does not accept the parameter to main(). The - parameter is the number of loops to run through the test, and the - default is 50000, which is far too many to run in a reasonable time - on the current PyPy implementation. - - -5. To list the PyPy interpreter command line options, type:: - - python py.py --help - - As an example of using PyPy from the command line, you could type:: - - python py.py -c "import pystone; pystone.main(10)" - - Alternatively, as with regular Python, you can simply give a - script name on the command line:: - - python py.py ../appspace/pystone.py - - (Note that this will run "forever" -- actually, "just" for many - hours, with the current implementation of PyPy.) - - -6. The PyPy project uses test-driven-development. Right now, there are - a couple of different categories of tests which you can run. - To run all the unit tests:: - - cd src/pypy - python test_all.py - - Alternatively, you may run subtests by going to the correct subdirectory - and running them individually:: - - cd src/pypy/module/test - python test_builtin.py - - Finally, there are some more advanced tests (which are derived from - some of the standard CPython tests). These are not part of the unit - tests, because they take longer than the standard unit tests:: - - cd src/pypy/interpreter - python py.py ../appspace/builtin_types_test.py - - -Trying out the translator -========================= - -The translator is a tool based on the PyPy interpreter which can translate -sufficiently static Python programs into low-level code. - -1. Download and install `Dot Graphviz`_. - -2. Download and install Pygame_ if you do not already have it. - -3. Type:: - - cd src/pypy/translator - python -i translator.py - - Test snippets of translatable code are provided in the file - ``test/snippet.py``. For example:: - - >>> t = Translator(test.is_perfect_number) - >>> t.simplify() - >>> t.view() - -4. We have a type annotator that can completely infer types for functions like - ``is_perfect_number``:: - - >>> t.annotate([int]) - >>> t.view() - - Move the mouse over variable names (in red) to see their inferred types. - -5. The graph can be turned into Pyrex code, with types if ``annotate()`` was - called:: - - >>> print t.pyrex() - >>> f = t.compile() - >>> f(28) - 1 - - Note how the strange-looking Pyrex code is unrelated to the original - Python source code. This is because the Pyrex code is generated from the - graph only, without reference to the original source. - - -Where to start reading the sources -================================== - -PyPy is made from parts that are relatively independent from each other. -You should start looking at the part that attracts you most: - -* `src/pypy/interpreter`_ contains the basic interpreter: bytecode dispatcher - in pyopcode.py_, frame and code objects in eval.py_ and pyframe.py_, - function objects and argument passing in function.py_ and argument.py_, - the object space interface definition in baseobjspace.py_, modules in - module.py_ and extmodule.py_. Core types supporting the interpreter are - defined in typedef.py_. - -* `src/pypy/objspace/std`_ contains the `Standard object space`_. The main file - is objspace.py_. For each type, the files ``xxxtype.py`` and - ``xxxobject.py`` contain respectively the definition of the type and its - (default) implementation. - -* `src/pypy/objspace`_ contains a few other object spaces: the trivial one - (but let's forget about it), the trace_ one, the flow_ one. The latter - is a relatively short piece of code that builds the control flow graphs - when the interpreter runs in it. - -* `src/pypy/translator`_ contains the code analysis and generation stuff. - Start reading from translator.py_, from which it should be easy to follow - the pieces of code involved in the various translation phases. - -* `src/pypy/annotation`_ contains the data model for the type annotation that - can be inferred about a graph. The graph "walker" that uses this is in - `src/pypy/translator/annrpython.py`_. - - -To learn more -============= - -* To learn more about PyPy and its development process, read the documentation_ - and the wiki_, and consider subscribing to the `mailing lists`_ (or simply - read the archives online) or communicating via irc.freenode.net:6667, channel #pypy. - -* To help PyPy become Python-the-next-generation, write some `unit tests`_ and - file some `bug reports`_! - --------------------------------------------------------------------------------- - -.. _subversion: http://codespeak.net/pypy/index.cgi?doc/devel/howtosvn.html -.. _Dot Graphviz: http://www.research.att.com/sw/tools/graphviz/ -.. _Pygame: http://www.pygame.org/ -.. _src/pypy/interpreter: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/ -.. _pyopcode.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/pyopcode.py -.. _eval.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/eval.py -.. _pyframe.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/pyframe.py -.. _function.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/function.py -.. _argument.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/argument.py -.. _baseobjspace.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/baseobjspace.py -.. _module.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/module.py -.. _extmodule.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/extmodule.py -.. _typedef.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/typedef.py -.. _src/pypy/objspace/std: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/std/ -.. _Standard object space: http://codespeak.net/pypy/index.cgi?doc/objspace/stdobjspace.html -.. _objspace.py: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/std/objspace.py -.. _src/pypy/objspace: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/ -.. _trace: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/trace.py -.. _flow: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/flow/ -.. _src/pypy/translator: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/ -.. _translator.py: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/translator.py -.. _src/pypy/annotation: http://codespeak.net/svn/pypy/trunk/src/pypy/annotation/ -.. _src/pypy/translator/annrpython.py: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/annrpython.py -.. _mailing lists: http://codespeak.net/pypy/index.cgi?lists -.. _documentation: http://codespeak.net/pypy/index.cgi?doc -.. _wiki: http://codespeak.net/moin/pypy/moin.cgi/FrontPage?action=show -.. _unit tests: http://codespeak.net/pypy/index.cgi?doc/devel/testdesign.html -.. _bug reports: http://codespeak.net/issues/pypy/ Deleted: /pypy/trunk/doc/newrepolayout.txt ============================================================================== --- /pypy/trunk/doc/newrepolayout.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,75 +0,0 @@ -=========================================== -Proposition: new svn repository layout -=========================================== - -Motivation ----------- - -The `PyPy repository layout`_ has evolved for two -years into something that needs some refactoring -to become more practical. - -For example, the `trunk/doc`_ directory was originally intended -to hold developer documentation but nowadays it contains -funding, negotiations, mails and misc-other-stuff documents. It is -not easy and obvious anymore to know which files are relevant. -Moreover, `trunk/doc`_ is too far away from the source code: -developers currently checkout the 'trunk/src' directory and -don't even get the documentation. This also makes it more -difficult to keep the documentation up-to-date. - -.. _`trunk/doc`: http://codespeak.net/svn/pypy/trunk/doc -.. _`PyPy repository layout`: http://codespeak.net/svn/pypy/ - -New repo layout proposal Nr. 1 ------------------------------- - -Based on experiences in various repositories here is a -new proposition describing a possible new structure -(starting at /svn/pypy):: - - branch # holds branches - tag # holds tagged dist-versions - - dist # holds current development - pypy # current trunk/src/pypy - documentation # developer documentation (inside pypy!) - py # and other 'externals' - setup.py # should be there at some point - README.txt # tell how to run PyPy, the translator, tests - LICENSE.txt # copyright notices for tree parts including pypy - - doc # non-dist documentations (papers etc.pp.) - talk # various pypy-talks - paper # various pypy-related papers (including our own) - sprint # sprint related information (reports etc.pp.) - irclog # IRC logs (snipped appropriately) - - www # website-related stuff (needs its own reconsideration) - - funding # funding related documents - eu-info # official information from the EU - contract # contract material (EU-contract, amendments) - eu-report # eu reports (time/cost/budget) - ... # probably more, we'll see later - -The idea is that developers can use a simple url:: - - svn co https://codespeak.net/svn/pypy/dist dist-pypy - -in order to get everything neccessary for sourcecode, documentation -and test development. Obviously, if you care about the funding -or web site application/contents you can do an appropriate checkout -as well. - -Note, that having documentation inside the source tree will help -with keeping a closer eye on documentation - especially when we -have special ref-integrity tests for the documentation (which itself -should reference real source-code/functions at some point). For -example, the refactoring of unitest.py-style tests to `py.test`_ based ones -"forgot" to modify our test-documentation in the too-far-away doc-folder. -We should move to a scheme where such an omission will raise real -test errors. - -.. _`py.test`: http://codespeak.net/py/current/doc/test.html - Deleted: /pypy/trunk/doc/readme.txt ============================================================================== --- /pypy/trunk/doc/readme.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,94 +0,0 @@ -===================== -PyPy Documentation -===================== - -PyPy documentation is generated from reST textfiles in the /doc directory of -our pypy-subversion repository. On the pypy home page you'll find a "doc" link that -shows you a list of recently modified documents. While in "doc-view" you also have -a navigation area on the left side which maps all documentation. - -Please add new or updated documentation by checking it in to the appropriate -directory in subversion, usually under http://codespeak.net/svn/pypy/trunk/doc/. - -+ Remember to run ``svn up`` **before** doing any commit. -+ All filenames should be lowercase, and documentation should be .txt files. -+ Mark-up the documentation with reST so it can generate a pretty html version. -+ On the server side a commit on the doc-subtree will immediately update the webpage. - -*Note* If you don't markup the textfile, it'll still be checked in, but when docutils -runs the parser, it'll look ugly on the website. So run docutils yourself before you commit it. - -Some reST basics: ------------------- - -There should be a title on your page. Do it like this:: - - Here is my Title - ================== - - Here is a section title - ------------------------- - -Make sure you have a blank line after your = or - lines or it will give you an error. -For marking a block of code so it'll look right, you can:: - - Put a line of text ending with :: - indent your code at least one space - my code - more code - even more code - still more code - -End of the "block" occurs whenever you unindent back to the same level as the -text with the ``::`` at the end. - -Using an underscore after a word like this_ will make reST think you want a hyperlink. -To avoid that (especially with things like ``wrap_``), you can use the `` back quote `` -to mark it as plain text. - -You can get more info on reST markup at http://docutils.sourceforge.net/docs/rst/quickref.html - ------------------------- -Checking your work ------------------------- - -In order to make sure that what you commit looks reasonably pretty (or at least not -entirely broken), you'll need to run the ``docutils`` parser on it. Unless you've -installed it in the past, you probably don't have it installed. Open IDLE (or any -Python interactive environment) and try "import docutils". If it imports, hooray! -Otherwise, you'll need to download it. - -Go to sourceforge and download the ``snapshot`` version. Install it. - -*Note to Debian users:* Be sure you installed ``python2.2-dev``, which includes ``distutils``, -before trying to install ``docutils``. - -Once you have ``docutils`` installed, you can use it go to your shell and use it like this:: - - $ python ~/mypath/docutils/tools/buildhtml.py - /// Processing directory: /home/anna/downloads/arObjSpaceDoc - ::: Processing .txt: howtosvn.txt - ::: Processing .txt: index.txt - -**WARNING** This will process **all** text documents in the directory and any subdirectories. -I prefer to work on text in a separate directory, run the ``docutils`` parser to see what it -looks like, then copy the .txt file over to my local /doc checkouts to commit it. - -Use a browser menu to go to ``File: Open: filename.html`` then you can see what it looks -like. Look at the command shell to see what errors you've got on which lines and fix it -in your textfile. You can then re-run the buildhtml.py script and see what errors you get. -After it's fixed, you can commit the .txt file and it'll automagically be turned into html -viewable on the website. - - -Here are some sample reST textfiles to see what it looks like: - -+ ObjectSpace_ -+ ObjectSpaceInterface_ - ---------------------------------------------------------------------------------- - -.. _this: http://docutils.sourceforge.net/docs/rst/quickref.html -.. _ObjectSpace: objspace/objspace.html -.. _ObjectSpaceInterface: objspace/objspaceinterface.html - Deleted: /pypy/trunk/doc/translation/annotation.txt ============================================================================== --- /pypy/trunk/doc/translation/annotation.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,366 +0,0 @@ -The annotation pass -=================== - -We describe below how a control flow graph can be "annotated" -to discover the types of the objects. This annotation pass is -done after control flow graphs are built by the FlowObjSpace, -but before these graphs are translated into low-level code -(e.g. C/Lisp/Pyrex). - - -An example: the factorial -------------------------- - -Say we want to make the control flow graph and type inference -on the following program:: - - def f(n): - if n >= 2: - return n * f(n-1) - else: - return 1 - -The flow objspace gives us the following graph (after the -simplification that turns ``call`` into ``simple_call``):: - - StartBlock(v1): - v2 = ge(v1, 2) - exitswitch(v2) - link "True" to Block2(v1) - link "False" to Block3 - - Block2(v3): - v4 = sub(v3, 1) - v7 = simple_call(f, v4) - v8 = mul(v3, v7) - jump to ReturnBlock(v8) - - Block3: - v9 = 1 - jump to ReturnBlock(v9) - - ReturnBlock(retval): - (empty, just returns retval) - -Suppose that we know that ``f`` takes an ``int`` argument. -We start type inference on the first block:: - - Analyse(StartBlock): - v1 ----> SV1 type(SV1)=int - v2 ----> SV2 type(SV2)=bool - -The notation is as follows. Everything at the right of the arrows -lives in a "big heap" of objects and annotations; a object is like a -CPython ``PyObject`` object structure in the heap, althought it can -here be unknown (SV1, SV2, SV3...). Annotations give some information -about the unknown heap objects. The arrows represent binding from -variables to objects. ``SV`` means ``SomeValue``. - -After StartBlock, we proceed to the type inference of its exits; -first Block2:: - - Analyse(Block2): - v3 ------------> SV1 # copied from StartBlock - v4 ------------> SV4 type(SV4)=int - v7 ------------> impossiblevalue - -It fails at the simple_call to f, because we don't know yet anything -about the return value of f. We suspend the analysis of Block2 and -resume at some other non-blocked point -- in this case, the other exit -from the StackBlock, which is jumping to Block3:: - - Analyse(Block3): - v9 --------> SV31 # const(SV31)=1, type(SV31)=int - -The object SV31 is the constant object 1. -Then we proceed to ReturnBlock:: - - Analyse(ReturnBlock): - retval --------> SV31 - -And we are done. We can now try to resume the suspended analysis of -Block2 -- in practice it is easier to just restart it:: - - Analyse(Block2): - v3 ------------> SV1 # copied from StartBlock - v4 ------------> SV4 type(SV4)=int - v7 ------------> SV31 # because that's the retval of f - v8 ------------> SV8 type(SV8)=int - -And now is the second branch into ReturnBlock. We must combine the -annotations coming from the two branches:: - - Intersection(ReturnBlock): - previous annotations for retval ----> SV31 type(SV31)=int const(SV31)=1 - new annotations for retval ---------> SV8 type(SV8)=int - intersection of both is retval -----> SV10 type(SV10)=int - -We invalidate the analysis of the blocks that depend on this new result, -namely ReturnBlock, which in turn invalidates the analysis of Block2 -which depended on the return value. Then we can restart it once more:: - - Analyse(Block2): - v3 ------------> SV1 # with type(SV1)=int - v4 ------------> SV4 type(SV4)=int - v7 ------------> SV10 # with type(SV10)=int - v8 ------------> SV11 type(SV11)=int - -Again, we must redo the intersection of the two branches -that enter ReturnBlock:: - - Intersection(ReturnBlock): - previous annotations for retval -------> SV10 type(SV10)=int - new annotations for retval ------------> SV11 type(SV11)=int - intersection doesn't change any more. - -Now the annotations are stable, and we are done. In the final version -summarized below, all the objects that are used in the variables and -in retval are properly annotated:: - - Bindings: - v1 ------> SV1 - v2 ------> SV2 - v3 ------> SV1 - v4 ------> SV4 - v7 ------> SV10 - v8 ------> SV11 - v9 ------> SV31 - retval --> SV10 - - Annotations: - type(SV1)=int - type(SV2)=bool - type(SV4)=int - type(SV10)=int - type(SV11)=int - -The bindings are implemented as a dictionary, and the annotations as -an AnnotationSet instance. More about it below. - - -Whole-program analysis ----------------------- - -A program of more than one function is analysed in exactly the same way, -starting from an entry point and following calls. We have a cache of all -the flowgraphs that the flow objspace produced, and a list of pending blocks -that we have to type-analyse. When the analysis of a block temporarily -fails (as above for the first recursive call to ``f``) we move the block -back into the pending list. There is only one heap of annotations for the -whole program, so that we can track where the objects come from and go -through the whole program. (This makes separate compilation very difficult, -I guess.) - - -Empty lists and mutable objects -------------------------------- - -Nothing special is required for empty lists. Let's try:: - - def g(a, n): - a.append(n) - - def f(): - b = [] - g(b, 5) - g(b, 6) - -As above, after simplification:: - - F_StartBlock(): - v1 = newlist() - v2 = simple_call(g, v1, 5) - v3 = simple_call(g, v1, 6) - - Analyse(F_StartBlock): - v1 -------> SV1 type(SV1)=list len(SV1)=0 listitems(SV1)=impossiblevalue - v2 -------> impossiblevalue - -The annotations about ``SV1`` mean that it is an empty list. When trying -to get any item out of it, the result is ``impossiblevalue``, because if we -try to execute code like ``c=b[0]`` then obviously it is impossible for -``c`` to contain any value. It is important not to confuse the two extreme -values: ``impossiblevalue`` means that no value can ever be found there -during actual execution, and corresponds to a ``SVx`` about which all -annotations are still possible. During the annotation pass, annotations -about a ``SVx`` can only *decrease*: we can later remove annotations that -we find to be incorrect, but we don't add new annotations. Thus an -``impossiblevalue`` is a value with potentially all annotations at first. -The other extreme is a ``SVx`` with no annotation at all; it represents -an object about which we know nothing at all -- and about which nothing -will be known later either: it means that we have inferred that many -different objects could be found at that point during execution. -Typically it shows a problem, e.g. that type inference failed to figure -out what object type can appear at that point. - -Let's come back to the example. The type analysis above fails at ``v2`` -because of the calls to ``g``, but it triggers the analysis of ``g`` with -the input arguments' annotations:: - - G_StartBlock(v4, v5): - v6 = getattr(v4, 'append') - v7 = simple_call(v6, v5) - - Analyse(G_StartBlock): - v4 -------> SV1 # from the call above - v5 -------> SV35 const(SV35)=5 type(SV35)=int - v6 -------> SV6 im_self(SV6)=SV1 im_func(SV6)=list_append - v7 -------> SV30 const(SV30)=None - -And most importantly the call to list_append corrects the annotations about -``SV1``. The annotation ``len(SV1)=0`` is deleted, and ``listitems(SV1)`` -is generalized from ``impossiblevalue`` to ``SV35`` -- this is done by -the same intersection process as above: we already know that -``listitems(SV1)`` can be ``impossiblevalue``, and now we figure out that -it could also be ``SV35``, so we take the intersection of the annotations -that apply to both ``impossiblevalue`` and ``SV35``. The result in this -case is just ``SV35``. - -Note that killing annotations like ``len(SV1)=0`` invalidates the inference -in any block that explicitely depends on it. Such blocks are marked as -"to be redone". (There isn't any such block in the present example.) - -Only after this can the analysis of ``F_StartBlock`` proceed, and -now we know that v1 points to the list ``SV1`` with the correct annotations: -unknown length, all items are ``5``. - -In the above example I also show a second call to ``g(b, 6)``, which -triggers an intersection on the input argument types of ``g`` which was -previously thought to be used with ``5`` only:: - - Intersection(G_StartBlock): - previous annotations for v5 -----> SV35 const(SV35)=5 type(SV35)=int - new annotations for v5 ----------> SV36 const(SV36)=6 type(SV36)=int - intersection of both is v5 ------> SV5 type(SV5)=int - -And so this time the list ``SV1`` is updated with:: - - listitems(SV1)=SV5 - -and now we know that we have a list of integers. - -Note that during this whole process the same list is represented by ``SV1``. -This is important, so that any code anywhere that could modify the list -can kill invalid annotations about it. Intersection must be clever about -mutable objects: we have seen above an example where ``retval`` could map -to ``SV10`` or ``SV11``, and the intersection said it was fine because they -had the same annotations. It would not be fine if ``SV10`` and ``SV11`` -could be of a mutable type. In this case we must force ``SV10==SV11`` for -the whole program. In other words the representation choosen for a list -depends on all the places where this list could go, and these places -themselves use a representation that depends on all the lists that could -come at this point. All these places and lists will use a common, -most general representation. - - -Polymorphism and mixed flowing/inference ----------------------------------------- - -(This paragraph is just an idea, it is not implemented.) - -We might eventually mix type inference and control flow generation a bit -more than described above. The annotations could influence the generation -of the graph. - -The most interesting influence would be to occasionally prevent two -FrameStates from being merged. This would result in a bigger control flow -graph in which several basic blocks can contain the operations about the -same bytecode positions, with different annotations. In particular, a -quite interesting idea is to disallow two states to be merged if the -resulting intersection of annotations is too poor -- say if it would make -genpyrex.py use the fall-back generic object type, which is not available -to other genxxx.py. - -The result is that we will automatically generate several specialized -version of the RPython code when it is meant to be polymorphic. For -example, in a function such as:: - - def push(stack, item): - stack.append(item) - -the different entry points, specifying quite different type annotations -for ``item``, are all unmergeable, as merging them would result in -insufficently many annotations left. By contrast, in the factorial -example above, all merges are fine because they conserve at least the -``type(X)=int`` annotation. - - -SomeValue ---------- - -An abstract Python object in the heap is represented by an -instance of ``pypy.annotation.model.SomeValue``. All these SomeValue() -instances print as SV0, SV1, SV2... for debugging, but we only -use their identity internally. - -A SomeValue() alone represents an object about which nothing -is known. To collect information about such an object we use an -instance of ``pypy.annotation.annset.AnnotationSet``. An -annotation is like an attribute of a SomeValue(); for example, to -say that an object SV5 is known to be an integer, then we set the -annotation ``SV5.type = int``. However, for various good and bad -reasons, the annotation is not actually stored as an attribute, -but managed by the AnnotationSet(). The allowed "attributes", -i.e. the various annotations that exist, are in -``pypy.annotation.model.ANN``. Thus for the above example we -set the annotation ``ANN.type`` of SV5 to ``int``. This is what -we wrote in the above examples ``type(SV5) = int``. - -Note that unlike previous attempts an annotation is now always -a "name" (ANN.type) with just two arguments: the subject (SV5) and -the associated value (int). Just like with attributes, there are -never more than one associated value per subject and attribute name. -But unlike attributes, all annotations have a default value: -``mostgeneralvalue``, which is a SomeValue() about which nothing -is known. The only differences between the ``mostgeneralvalue`` -and a normal SomeValue() with no annotations are that AnnotationSet -will complain if you try to set annotations to ``mostgeneralvalue``; -and for convenience reasons ``mostgeneralvalue`` is false in a -boolean context. - - -AnnotationSet and ANN ---------------------- - -AnnotationSet has two main methods: ``get(name, subject)`` to -read the current annotation ``name`` about ``subject``, and -``set(name, subject, value)`` to set it. - -The meaning of ``value`` depends on the annotation. In some -cases it is a usual Python object (int, 3, True...). In other -cases it is specifically a SomeValue() instance, on which we -can recursively have partial information only. Here are -a few common annotations: - -* ``ANN.type``: the ``value`` is the type (int, list, ...). - -* ``ANN.len``: the ``value`` is the length of the object - (if known and constant, of course). - -* ``ANN.const``: we know that the ``subject`` is a constant - object; the ``value`` of ``ANN.const`` is precisely this - constant. - -* ``ANN.listitems``: the ``value`` is another SomeValue() - which stands for any item of the list. Thus the - annotations about this sub-SomeValue() tell what is known - in general about all the items in the list. - -* ``ANN.tupleitem[index]``: this is a family of annotations. - This is one of the reasons why we don't just use attributes - to store annotations: the whole expression ``ANN.tupleitem[0]`` - would be the attribute name. The expression ``ANN.tupleitem[1]`` - would be a different attribute name, and so on. Annotation-wise, - ``ANN.tupleitem[i]`` has a ``value`` which is a SomeValue() - describing what is known about the item ``i`` of a tuple. - -* ``ANN.immutable``: the ``value`` is always ``True``, unless - the annotation is not set, in which case it automatically - defaults to ``mostgeneralvalue`` (which is considered as false - in a boolean context for convenient checking). When - ``ANN.immutable`` is set, it means that the subject is known to - be of an immutable type (int, float, tuple...). This influences - the intersection algorithm. - -The interection algorithm is implemented in the ``merge()`` method -of AnnotationSet. Deleted: /pypy/trunk/doc/translation/controlflow.txt ============================================================================== --- /pypy/trunk/doc/translation/controlflow.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,162 +0,0 @@ -FlowObjSpace -============ - -Introduction ------------- - -The FlowObjSpace generates a control-flow graph from a function. This graph also contains a trace of the individual operations, so that it is actually just an alternate representation for the function. - -The FlowObjSpace is an object space, which means that it exports the standard object space interface and it is driven by the interpreter. - -The basic idea is that if the interpreter is given a function, e.g.:: - - def f(n): - return 3*n+2 - -it will do whatever bytecode dispatching and stack-shuffling needed, during which it issues a sequence of calls to the object space. The FlowObjSpace merely records these calls (corresponding to "operations") in a structure called a basic block. To track which value goes where, the FlowObjSpace invents placeholder "wrapped objects" and give them to the interpreter, so that they appear in some next operation. - -For example, if the placeholder ``v1`` is given as the argument to the above function, the interpreter will call ``v2 = space.mul(space.wrap(3), v1)`` and then ``v3 = space.add(v2, space.wrap(2))`` and return ``v3`` as the result. During these calls the FlowObjSpace will record a basic block:: - - Block(v1): # input argument - v2 = mul(constant(3), v1) - v3 = add(v2, constant(2)) - - -Joining basic blocks --------------------- - -A basic block ends in one of two cases: when the interpreters calls ``is_true()``, or when a joinpoint is reached. - -* A joinpoint is a specially marked position in the bytecode. This is the only bytecode dependency in FlowObjSpace. Intuitively, there should be one joinpoint at each bytecode position where two different paths can "join" together, e.g. the entry point of a loop. A joinpoint forces a basic block to end and the next one to begin. A snapshot of the current frame is taken (a FrameState) and recorded on the joinpoint. If the control flow later reaches this point again, we put a "backwards" jump to the old basic block that starts at this point. (The control flow is actually just a graph, with basic blocks pointing to each other, so there is not really a notion of "backwards".) - -* If the interpreter calls ``is_true()``, the FlowObjSpace doesn't generally know if the answer should be True or False, so it puts a conditional jump and generates two successor blocks for the current basic block. There is some trickery involved so that the interpreter is fooled into thinking that ``is_true()`` first returns False (and the subsequent operations are recorded in the first successor block), and later the *same* call to ``is_true()`` also returns True (and the subsequent operations go this time to the other successor block). - - -Passing variables between basic blocks --------------------------------------- - -XXX - - -FlowExecutionContext --------------------- - -The FlowExecutionContext is a modified ExecutionContext that drives the interpreter in a fashion that is quite different from the one needed for normal interpretation. XXX - - -Interface ---------- - -We make one instance of FlowExecutionContext per function to analyse. The instance has a cache of FrameStates to detect when the control is looping (``self.joinpoints``). XXX - - -Old stuff to remove -------------------- - -:: - - Hello again - - def f(i): - return g(i)+2 - def g(i): - return i+1 - - f(3) - tspace: - pyxcode.putln('def f(%s):' % sig) - res = frame.eval(executioncontext) - pyxcode.putln('return %s' % res) - - - Pyrex: def f(v1): - dis.dis(f) --> - 2 0 LOAD_GLOBAL 0 (g) - w_result = space.getitem(f.w_globals, w_varname) - - 3 LOAD_FAST 0 (i) - 6 CALL_FUNCTION 1 - space.call(w_function, w_arguments, w_kwds) - space.call(w_g, ("v1",), {}) - Pyrex: v2 = g(v1) - 9 LOAD_CONST 1 (2) - space.wrap(2) - 12 BINARY_ADD - space.add("v2", "constant 2") - Pyrex: v3 = v2 + 2 - 13 RETURN_VALUE - 14 LOAD_CONST 0 (None) - 17 RETURN_VALUE - Pyrex: return v3 - - - Result: - def f(v1): - v2 = g(v1) - v3 = v2 + 2 - return v3 - - - def h(i, j): - if i < 0: - i = j - return i+1 - - Pyrex: def h(v1, v2): - --> interpreter - 3 0 LOAD_FAST 0 (i) - 3 LOAD_CONST 1 (0) - 6 COMPARE_OP 0 (<) - "v3" = space.lt("v1", "constant 0") - Pyrex: v3 = v1 < 0 - 9 JUMP_IF_FALSE 10 (to 22) - space.is_true("v3") - Pyrex: if v3: cinline "goto Label1;" - 12 POP_TOP - - 4 13 LOAD_FAST 1 (j) - 16 STORE_FAST 0 (i) - 19 JUMP_FORWARD 1 (to 23) - >> 22 POP_TOP - - Pyrex: cinline "LabelBytecode23:" # just in case for later - 5 >> 23 LOAD_FAST 0 (i) - 26 LOAD_CONST 2 (1) - 29 BINARY_ADD - space.add("v1", "constant 2") - Pyrex: v4 = v1 + 2 - 30 RETURN_VALUE - 31 LOAD_CONST 0 (None) - 34 RETURN_VALUE - Pyrex: return v4 - - pyrex: cinline "Label1:" - 12 POP_TOP - - 4 13 LOAD_FAST 1 (j) - 16 STORE_FAST 0 (i) - (in the interpreter fastlocals now: i="v2" j="v2") - 19 JUMP_FORWARD 1 (to 23) - >> 22 POP_TOP - - (bytecode 23 already seen!) - Pyrex: v1 = v2 - Pyrex: cinline "goto LabelBytecode23;" - 5 >> 23 LOAD_FAST 0 (i) - - def h(i, j): - if i < 0: - i = j - return i+1 - - def h(v1, v2): - v3 = v1 < 0 - if v3: cinline "goto label1;" - - cinline "labelBytecode23:" - v4=v1+1 - return v4 - cinline "label1:" - v1=v2 - cinline "goto labelBytecode23;" - Deleted: /pypy/trunk/doc/wrapping.txt ============================================================================== --- /pypy/trunk/doc/wrapping.txt Tue Jan 18 10:41:31 2005 +++ (empty file) @@ -1,95 +0,0 @@ -========================= - Wrapping rules -========================= - -Introduction ------------- - -PyPy is made of Python source code at two levels: there is on the one hand *application-level code* that looks like normal Python code, and that implements some functionalities as one would expect from Python code (e.g. one can give a pure Python implementation of some built-in functions like ``zip()``). There is also *interpreter-level code* for the functionalities that must more directly manipulate interpreter data and objects (e.g. the main loop of the interpreter, and the various object spaces). - -Application-level code doesn't see object spaces explicitely: it runs using an object space to support the objects it manipulates, but this is implicit. There is no need for particular conventions for application-level code. The sequel is only about interpreter-level code. (Ideally, no application-level variable should be called ``space`` or ``w_xxx`` to avoid confusion.) - - -Naming conventions ------------------- - -* ``space``: the object space is only visible at interpreter-level, where it is by convention in a variable called ``space``. - -* ``w_xxx``: any object seen by application-level code is an object explicitely managed by the object space. From the interpreter-level point of view, this is called a *wrapped* object. The ``w_`` prefix is used for any type of application-level object. - -* ``xxx_w``: an interpreter-level container for wrapped objects, for example a list or a dict containing wrapped objects. Not to be confused with a wrapped object that would be a list or a dict: these are normal wrapped objects, so they use the ``w_`` prefix. - - -Operations on ``w_xxx`` ------------------------ - -The core interpreter considers wrapped objects as black boxes. It is not allowed to inspect them directly. The allowed operations are all dependent on the object space: they are called ``space.xxx()``, where ``xxx`` is a standard operation name (``add``, ``getattr``, ``call``, ``eq``...). The list of standard operations is found in the large table near the end of ``pypy.interpreter.baseobjspace``. These operations take wrapped arguments and return a wrapped result (or sometimes just None). - -Also note some helpers: - -* ``space.call_function(w_callable, ...)``: collects the given (already-wrapped) arguments, builds a wrapped tuple for them, and uses ``space.call()`` to perform the call. - -* ``space.call_method(w_object, 'method', ...)``: uses ``space.getattr()`` to get the method object, and then ``space.call_function()`` to invoke it. - - -Building ``w_xxx`` objects --------------------------- - -From the core interpreter, wrapped objects are usually built as the result of an object space operation. The ways to directly create a wrapped object are: - -* ``space.wrap(x)``: returns a wrapped object containing the value ``x``. Only works if ``x`` is either a simple value (integer, float, string) or an instance of an internal interpreter class (Function, Code, Frame...). - -* ``space.newlist([w_x, w_y, w_z...])``: returns a wrapped list from a list of already-wrapped objects. - -* ``space.newtuple([w_x, w_y, w_z...])``: returns a wrapped tuple from a list of already-wrapped objects. - -* ``space.newdict([])``: returns a new, empty wrapped dictionary. (The argument list can contain tuples ``(w_key, w_value)`` but it seems that such a use is not common.) - -* ``space.newbool(x)``: returns ``space.w_False`` or ``space.w_True`` depending on the truth value of ``x``. - -There are a few less common constructors, described in the comments at the end of ``pypy.interpreter.baseobjspace``. - - -Constant ``w_xxx`` objects --------------------------- - -The object space holds a number of predefined wrapped objects. The most common ones are ``space.w_None`` and ``space.w_XxxError`` for each exception class ``XxxError`` (e.g. ``space.w_KeyError``, ``space.w_IndexError``, etc.). - - -Inspecting ``w_xxx`` objects ----------------------------- - -The most delicate operation is for the interpreter to inspect a wrapped object, which must be done via the object space. - -* ``space.is_true(w_x)``: checks if the given wrapped object is considered to be ``True`` or ``False``. You must never use the truth-value of ``w_x`` directly; doing so (e.g. writing ``if w_x:``) will give you an error reminding you of the problem. - -* ``w_x == w_y`` or ``w_x is w_y``: DON'T DO THAT. The only half-official exception is to check if ``w_x`` contains a wrapped ``None``: you can write ``w_x == space.w_None``. Follow this rule; the case of ``None`` is easy to fix globally later if we find out that we need to. The rationale for this rule is that there is no reason that two wrappers are related in any way even if they contain what looks like the same object at application-level. To check for equality, use ``space.is_true(space.eq(w_x, w_y))``. To check for identity, use ``space.is_true(space.is_(w_x, w_y))``. - -* ``space.unpackiterable(w_x)``: this helper iterates ``w_x`` (using ``space.iter()`` and ``space.next()``) and collects the resulting wrapped objects in a list. Of course, in cases where iterating directly is better than collecting the elements in a list first, you should use ``space.iter()`` and ``space.next()`` directly. - -* ``space.unwrap(w_x)``: inverse of ``space.wrap()``. Attention! Using ``space.unwrap()`` must be avoided whenever possible. Actually, it should only be used when you are sure that ``w_x`` contains a simple object or an internal interpreter object that was wrapped with ``space.wrap()``. This function is a bit buggy anyway, and it should probably be fixed at some point: we should specify what kind of unwrapped result is expected (and raise a TypeError appropriately). - -Remember that you can usually obtain the information you want by invoking operations or methods on the wrapped objects; e.g. ``space.call_method(w_dict, 'iterkeys')`` returns a wrapped iterable that you can decode with ``space.unpackiterable()``. - - -Application-level exceptions ----------------------------- - -Interpreter-level code can use exceptions freely. However, all application-level exceptions are represented as an ``OperationError`` at interpreter-level. In other words, all exceptions that are potentially visible at application-level are internally an ``OperationError``. This is the case of all errors reported by the object space operations (``space.add()`` etc.). - -To raise an application-level exception:: - - raise OperationError(space.w_XxxError, space.wrap("message")) - -To catch a specific application-level exception:: - - try: - ... - except OperationError, e: - if not e.match(space, space.w_XxxError): - raise - ... - -This construct catches all application-level exceptions, so we have to match it against the particular ``w_XxxError`` we are interested in and re-raise other exceptions. The exception instance ``e`` holds two attributes that you can inspect: ``e.w_type`` and ``e.w_value``. Do not use ``e.w_type`` to match an exception, as this will miss exceptions that are instances of subclasses. - -We are thinking about replacing ``OperationError`` with a family of common exception classes (e.g. ``AppKeyError``, ``AppIndexError``...) so that we can more easily catch them. The generic ``AppError`` would stand for all other application-level classes. From hpk at codespeak.net Tue Jan 18 10:42:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 10:42:08 +0100 (MET) Subject: [pypy-svn] r8363 - in pypy: funding trunk/doc/funding Message-ID: <20050118094208.A626A27BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 10:42:08 2005 New Revision: 8363 Added: pypy/funding/ - copied from r8362, pypy/trunk/doc/funding/ Removed: pypy/trunk/doc/funding/ Log: moved funding to new layout ... From hpk at codespeak.net Tue Jan 18 10:52:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 10:52:27 +0100 (MET) Subject: [pypy-svn] r8367 - in pypy/extradoc: . paper papers talk translation Message-ID: <20050118095227.C62EE27BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 10:52:27 2005 New Revision: 8367 Added: pypy/extradoc/paper/ pypy/extradoc/paper/grove.pdf - copied unchanged from r8366, pypy/extradoc/papers/grove.pdf pypy/extradoc/paper/psycoguide.ps.gz - copied unchanged from r8366, pypy/extradoc/psycoguide.ps.gz pypy/extradoc/talk/ pypy/extradoc/talk/amsterdam.sxi - copied unchanged from r8366, pypy/extradoc/amsterdam.sxi pypy/extradoc/talk/oscon2003-paper.txt - copied unchanged from r8366, pypy/extradoc/oscon2003-paper.txt pypy/extradoc/talk/pypy-talk-ep2004-hpk.txt - copied unchanged from r8366, pypy/extradoc/pypy-talk-ep2004.txt Removed: pypy/extradoc/amsterdam.sxi pypy/extradoc/index.txt pypy/extradoc/oscon2003-paper.txt pypy/extradoc/papers/ pypy/extradoc/psycoguide.ps.gz pypy/extradoc/pypy-talk-ep2004.txt pypy/extradoc/translation/ Log: moved stuff around in extradoc according to the proposal Deleted: /pypy/extradoc/amsterdam.sxi ============================================================================== Binary file. No diff available. Deleted: /pypy/extradoc/index.txt ============================================================================== --- /pypy/extradoc/index.txt Tue Jan 18 10:52:27 2005 +++ (empty file) @@ -1,110 +0,0 @@ -Pypy Documentation -================== - -We have a fair amount of documentation for the Pypy project. The files -are available from the website as html (view them along the left side of -the pypy-doc webpage). They are also available from the repository, -under the *doc/* directory or under the *doc/devel* sub-directory. Or, -to catch up on what we've been up to lately, just peek at the -recently-modified_ documents page. - -Overview --------- - -If you just want an overview of the project, take a look at these items in *doc/*. - - * architecture_: - a more technical overview of the current architecture - - * oscon2003-paper_: - presentation to OSCON on what pypy is about and why you should care - - -Getting Started ---------------- - -If you want to get involved, take a look at the following documentation to get a better taste: - -These file are in the *doc/* directory: - - * howtopypy_: - provides some hands-on instructions for getting started - - - * readme_: - this file is on using ReST for pypy documentation - - - * wrapping_: - a description of application-level and interpreter-level wrapped objects - -This file is in the *doc/devel/* sub-directory: - - * howtosvn_: - for new users of subversion - -Before you code ---------------- - -Before doing pypy work, you should also take a look at these developer-specific instructions, found in the *doc/devel/* sub-directory of the repository: - - * coding-style_: - covers pypy coding conventions - - - - * optionaltool_: - there are some optional tools we use for pypy. - - * testdesign_: - pypy is a test-driven development project.read here to find out more about how we're doing testing. - -Further reading ---------------- - -* An interesting thread on an HP tech report that may be proof the pypy is feasible_ . (We already knew that...) - -* An interesting thread on why VHLL rock_ . (We already knew that too.) - -* A thread on Python in Scheme_ . - -* An intriguting project, FlashMob_ - creating an adhoc supercomputer. - -* A discussion on Python and lisp_ support - -* An interesting repository_ of papers by Xerox Parc members, with quite a few issues more or less relevant to PyPy. - -* A thread on the gnu lightning_ project."GNU lightning is a library that generates assembly language code at run-time; it is very fast, making it ideal for Just-In-Time compilers, and it abstracts over the target CPU, as it exposes to the clients a standardized RISC instruction set inspired by the MIPS and SPARC chips." - -* A project to create a Low Level Virtual Machine (LLVM_) and a PyPy-LLVM_ discussion, and conversation_ between PyPy and LLVM. - -* A thread discussing the xhelix_ python C extension implementing Helix encryption and authentication, which may be interesting to use as a pypy performance test at some point. - -* A paper for PyCon 2004: "IronPython_ is a new implementation of the Python language targeting the Common Language Runtime (CLR). It compiles python programs into bytecode (IL) that will run on either Microsoft's .NET or the Open Source Mono platform. IronPython includes an interactive interpreter and transparent on-the-fly compilation of source files just like standard Python. In addition, IronPython supports static compilation of Python code to produce static executables (.exe's) that can be run directly or static libraries (.dll's) that can be called from other CLR languages." - -* A comparison of Python and Pliant_ , an OS written in a python-like language. - - -.. _architecture: http://codespeak.net/pypy/index.cgi?doc/architecture.html -.. _oscon2003-paper: http://codespeak.net/pypy/index.cgi?doc/oscon2003-paper.html -.. _howtopypy: http://codespeak.net/pypy/index.cgi?doc/howtopypy.html -.. _readme: http://codespeak.net/pypy/index.cgi?doc/readme.html -.. _wrapping: http://codespeak.net/pypy/index.cgi?doc/wrapping.html -.. _coding-style: http://codespeak.net/pypy/index.cgi?doc/devel/coding-style.html -.. _howtosvn: http://codespeak.net/pypy/index.cgi?doc/devel/howtosvn.html -.. _optionaltool: http://codespeak.net/pypy/index.cgi?doc/devel/optionaltool.html -.. _testdesign: http://codespeak.net/pypy/index.cgi?doc/devel/testdesign.html -.. _feasible: http://codespeak.net/pipermail/pypy-dev/2004q2/001289.html -.. _rock: http://codespeak.net/pipermail/pypy-dev/2004q1/001255.html -.. _Scheme: http://codespeak.net/pipermail/pypy-dev/2004q1/001256.html -.. _FlashMob: http://www.flashmobcomputing.org/ -.. _lisp: http://codespeak.net/pipermail/pypy-dev/2003q4/001048.html -.. _repository: http://www2.parc.com/csl/groups/sda/publications.shtml -.. _lightning: http://codespeak.net/pipermail/pypy-dev/2003q4/001051.html -.. _LLVM: http://llvm.cs.uiuc.edu/ -.. _PyPy-LLVM: http://codespeak.net/pipermail/pypy-dev/2003q4/001115.html -.. _conversation: http://codespeak.net/pipermail/pypy-dev/2003q4/001119.html -.. _xhelix: http://codespeak.net/pipermail/pypy-dev/2003q4/001129.html -.. _IronPython: http://www.python.org/pycon/dc2004/papers/9/ -.. _pliant: http://pliant.cx -.. _recently-modified: http://codespeak.net/pypy/index.cgi?doc/recent Deleted: /pypy/extradoc/oscon2003-paper.txt ============================================================================== --- /pypy/extradoc/oscon2003-paper.txt Tue Jan 18 10:52:27 2005 +++ (empty file) @@ -1,694 +0,0 @@ -Implementing Python in Python -============================== - -A report from the PyPy project -****************************** -The PyPy_ [#]_ project aims at producing a simple runtime-system for -the Python_ language, written in Python itself. **C** and **Lisp** -are elder examples of languages which are self-hosting. More -recently, we have seen implementations of **Scheme** in Scheme_, [#]_ -and **Squeak**, [#]_ [#]_ a Smalltalk_ implementation of Smalltalk_. -The desire to implement your favourite language *in* your -favourite language is quite understandable. Every significant -computer language has a certain expressiveness and power, and it is -frustrating to not be able to use that expressiveness and power when -writing the language itself. - -.. _PyPy: http://www.codespeak.net/pypy/ -.. _Python: http://www.python.org/ -.. _Scheme: http://www.swiss.ai.mit.edu/projects/scheme/ -.. _Squeak: http://www.squeak.org -.. _Smalltalk: http://www.smalltalk.org/ - -Thus we aim to produce a minimal core which is *simple* and -*flexible*, and no longer dependent on CPython [#]_. This should make -PyPy_ easier than CPython to analyze, change and debug. We will take -care that PyPy will integrate easily with Psyco_ [#]_ and Stackless_, [#]_ -while trying to avoid unwitting C dependencies in our thinking. - -.. _Psyco: http://psyco.sourceforge.net/ -.. _Stackless: http://www.stackless.com/ - -We should be able to produce different versions of PyPy which run -on different architectures, for instance one that runs on the -Java Virtual Machine, much as Jython_ [#]_ does today. - -.. _Jython: http://www.jython.org/ - -By keeping things *simple* and *flexible* we can produce code that has -attractions for both industry and academia. Academics will find that -this Python is even easier to teach concepts of language design with. -Industry will be pleased to know that ending the dependence on CPython -means that we can produce a Python with a smaller footprint. -Eventually, we would like to produce a faster Python , which should -please all. We are very far from that now, because speed is a distant -goal. So far we have only worked on making PyPy *simple* and -*flexible*. - -Most of you know what happens if you type:: - - import this - -at your favourite Python prompt. You get *The Zen of Python*, [#]_ -written by Tim Peters. It starts:: - - Beautiful is better than ugly. - Explicit is better than implicit. - -and ends with:: - - Namespaces are one honking great idea -- let's do more of those! - -This raises an interesting question. What would *doing more of those* -mean? The PyPy project takes one approach. - - -Terminology (a short digression) -******************************** - -In PyPy there is a distinction between **application level code**, which -is the world that PyPy is interpreting, and which can use the full features -of the language, and the **interpreter level code** which is the world -that CPython is interpreting. The interpreter level code -needs to be written in a restricted subset of Python. -(Currently you are mainly restricted to immutable objects; no dicts, you can -use globals but you cannot modify them. *What defines Restricted Python?* -is a matter of current debate.) - -In a Python-like language, a running interpreter has three main parts: - - * the main loop, which shuffles data around and calls the operations defined in the object library according to the bytecode. - * the compiler, which represents the static optimization of the source code into an intermediate format, the bytecode; and - * the object library, implementing the various types of objects and their semantics; - -In PyPy, the three parts are clearly separated and can be replaced -independently. The main loop generally assumes little about the semantics -of the objects: they are essentially black boxes (PyObject pointers). The -interpreter stack and the variables only contain such black boxes. -Every operation is done via calls to the object library, such as -PyNumber_Add(). We haven't done much to make the compiler and the main -loop into explicit concepts (yet), because we have been concentrating -on making separable object libraries. - -We call the separable object library, an *Object Space*. -We call the black boxes of an Object Space *Wrapped Objects*. - -One exciting thing is that while existing languages implement _one_ -Object Space, by separating things we have produced an architecture -which will enable us to run more than one Object Space in the same -interpreter at the same time. This idea has some interesting implications. - -But first let us dream for a bit. (Aside from having fun, why should -we spend our time writing PyPy?) - -Goals: -++++++ -or Dreams, if you prefer - - -A Slimmer Python -++++++++++++++++ -People who write code for handhelds and other embedded devices often -wish that they could have a much smaller footprint. With PyPy it -would be possible to load a Tiny Object Space which only implements -the behaviour which they need, and skips the parts that they do not. - -A Native Reference Language -+++++++++++++++++++++++++++ -Currently, we have two widely-used implementations of Python, CPython, -and Jython. Whenever they differ, the question always comes up: Is -Jython *wrong*? By this, people mean, is this behaviour which exists -in CPython, a matter of the language definition, which Jython ought to -support, or is it instead an irrelevant detail, the historical -accident of how things happened to be implemented in CPython, which -Jython is free to ignore? It would be useful to have an independent -Reference Language, written in Python itself to stand as the model of -what is compliant Python. A PyPy Object Space will provide this. -Moreover, people who would like to experiment with a proposed Python -language change will have an easier task. Proposed new language -features, could profit from first being written in PyPy so that more -people could use, comment, and modify them before final approval or -rejection. - -Getting better use of machines with multiple CPUs -++++++++++++++++++++++++++++++++++++++++++++++++++ -(Also known as *Killing the Global Interpreter Lock*). We believe -that we have barely scratched the surface of what can be done with -the new hardware architectures we have created. The old idea of -*one machine, one CPU* persists, so it is difficult to partition the -work in such a way to keep all the CPUs occupied. We hope to be able -to design our interpreter so that each CPU could be busy with its own -Object Space. - -Running different Object Spaces on different machines -+++++++++++++++++++++++++++++++++++++++++++++++++++++ -Well, why not? Whenever the time needed to do the calculating exceeds -the time needed to communicate between the various calculators, you -will benefit by adding more CPUS. Thus PyPy will provide you with an -alternative way to write a Cluster. (`The Beowulf Cluster`_ is -probably the most famous of Cluster architectures). Right now 'network -computing' is in its infancy. We don't know how to take advantage of -the resources we have. Ideally, one could begin a computation on a -small device, say a mobile phone, and have the interpreter notice that -the device is underpowered for such a computation and transparently -forward the computation to a machine with more computational power. -You could have *peak computing machines* in the same way that -electrical utilities have plants which are expensive to -run and only come on-line when demand is extremely high. As computers -become ubiquitous, we will *need* such demand based load sharing. - -.. _The Beowulf Cluster: http://www.beowulf-underground.org/index.html - -Multiple, Dynamically Changing Implementations of a Single Type -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -Consider the question: *What is the best way to implement a dict*? - -How one answers depends on how much data one intends to store. -If the dict is never expected to have more than a half dozen items, a -really fast list may be best. Larger dicts might best be implemented -as hashes. For storing enormous amounts of data, a binary tree -might be just what you desire. In principle, there is -nothing to stop your interpreter from keeping statistics on how it is -being used, and to move from strategy to strategy at runtime. You -could implement this in CPython, but we intend to make it a lot -*easier* to do this in PyPy to encourage such experimentation. - -A better teaching vehicle -+++++++++++++++++++++++++ -Python has proven to be an excellent first programming language. -However, once the student develops a desire to see the nuts and bolts -of how one implements a language, when they look under the hood, they -find C, sometimes the sort of C one writes when speed optimisation is -of paramont importance. For pedagological purposes, one would prefer -a language implementation whose chief virtue is *clarity* so that the -concepts are illustrated cleanly. - -However, academic computer science is littered with tiny teaching -languages. Every time we get a few new ideas in language design or -pedagogical theory we itch to create a language to express these -ideas. While understandable, this is wasteful. Many languages are -implemented which are more novel than useful, and too many are begun -with insufficient new ideas. At one extreme, we end up force-feeding -our poor students with too many computer languages, too quickly -- -each language designed to teach a particular point. Alas, many of our -languages are particularly weak on everything *except* the point we -wish to make. - -At the other extreme, many students go to university and end up only -learning how to program in commercially successful languages. This -reduces university to a Giant Trade School, where it is possible to -avoid learning Computer Science altogether. What we need is a the -middle way, a Pythonic way between purity and practicality, theory and -practice. - -PyPy may be able to help. The separation should make learning concepts -easier, and the ability to create one's own Object Spaces provides a -useful way to compare and contrast different techniques. Finally, we -could reasonably ask our students to **implement** interesting -theories in Python, producing slightly different Object Spaces which -could leave the bulk of the language implementation unchanged. - -There is no better way to learn about compiler writing, than writing -compilers, but much of today's education in compiler writing leaves a -huge gap between 'the theory that is in the book which the student is -expected to learn' and 'what is reasonable for a student to implement -as coursework'. Students can spend all semester overcoming -difficulties in *actually getting the IO to work*, and *interfacing -with the runtime libraries*, while only spending a fraction of the -time on the concepts which you are trying to teach. - -Object Spaces could provide a better fit between the the abstract -concepts we wish to teach and the code written to implement just that. - -Runtime Adaptation of C-Libraries and System-Calls -++++++++++++++++++++++++++++++++++++++++++++++++++ -Python is already widely used for integrating and driving C-libraries -(for numerical computation, 3D-modeling etc.). We dream -of introducing runtime mechanisms that allow PyPy to directly setup and -execute "native" calls on a machine. For this to work we need -"trampolin" (assembler-) functions that build a C-like stackframe -and trigger a call directly into e.g. the linux kernel or -any C-library without having to use a C-compiler. This technique -would clearly be of great value to embedded devices but also -to regular python applications that could more easily use C-libraries -once they obtain a pythonic description of the library (possibly -generated from ``.h`` files). - -A Smarter, more Dynamic Interpreter -+++++++++++++++++++++++++++++++++++ -A Virtual Machine written in Python, should be easier to maintain and -optimise. By recording statistics and analysing the bytecodes that are -running through the machine, it is possible to find a shorter, and -faster way to run a script - the essence of optimisation. Native code -compilers do it all the time, but obviously only once at compilation -time. Interpreters can optimise in exactly same way, but at *run -time*. `The Hotspot Java Virtual Machine`_ already does this. - -.. _The Hotspot Java Virtual Machine: http://java.sun.com/products/hotspot/docs/whitepaper/Java_Hotspot_v1.4.1/Java_HSpot_WP_v1.4.1_1002_1.html - -Faster Python -+++++++++++++ -(Okay, you've caught us ...) -While we are writing an adaptive, smarter compiler, we ought to be able -to make it faster. We think we can produce a Just-In-Time compiler which -is faster than C Python without destroying the clarity in our architecture. -Indeed, the ability to run different object spaces at the same time, in the -same interpreter will be most useful in this application. Psyco already -uses similar techniques to great effect. - -Speaking of Running different Object Spaces at the Same Time -++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -This dream is a bit far-fetched, but it is worth investigating. Code -migration currently involves going through one's entire codebase -looking for conflicts. This makes converting to newer versions of the -language both expensive and difficult. There is a trade-off between -getting the new features which contribute to increased productivity in -program design, and having to fix piles of old code that wasn't broken -until the language changed. With multiple Object Spaces approach it -may be possible to have your cake and eat it too. - -You could load your existing modules with the Object Space they were -developed for while immediately using new features in new code that -you develop. It would be up to the PyPy interpreter to see that these -Object Spaces communicate with each other transparently. Only modules -that would particularly benefit from having the new features, would -be modified. The rest could sleep peacefully, unchanged. - -This leads to: - -World Domination -++++++++++++++++ -And if we don't pull this off, we will have at least learned a lot. This -in itself makes the project worth doing. Plus it's fun... - -But away from the dreams and back to what do we currently have? - -We now have a pretty good working interpreter which implements -advanced language features such as nested scopes, generators and -metaclasses. Most **types** and **builtins** are either completely -implemented or nearly there. We have extensive unit tests, since we -believe in test driven design, even though we don't always practice -it. - -We currently have three object spaces at least partially implemented. - - -The Trivial Object Space -++++++++++++++++++++++++ -A PyPy interpreter using the Trivial Object Space is an -interpreter with its own main loop (written in Python), and nothing -else. This main loop manipulates real Python objects and all -operations are done directly on the Python objects. For example, "1" -really means "1" and when the interpreter encounters the BINARY_ADD -bytecode instructions the Trivial Object Space will just add two real -Python objects together using Python's "+". The same for lists, -dictionaries, classes ... we just use Python's own. Delegate Object -Space might have been a better name for this Object Space. - -This Object Space is only useful for testing the concept of Object Spaces, -and our interpreter, or even interpreting different kinds of bytecodes. -This is already implemented; it is funny to watch *dis.dis* disassembling -itself painfully slowly. - -Getting this to work was a goal of the Hildesheim Sprint February 16-23. -It demonstrated that our Object Space Concept was viable, and that our -interpreter worked. - -The Standard Object Space -++++++++++++++++++++++++++ -The Standard Object Space is the object space that works just like -Python's, that is, the object space whose black boxes are real Python -objects that work as expected. Getting the Standard Object Space to -work was a goal of the Gothenburg Sprint May 24 - 31. - -The Standard Object Space defines an abstract parent class, W_Object, -and a bunch of subclasses like W_IntObject, W_ListObject, and so on. A -wrapped object (a *black box* for the interpreter main loop) is thus -an instance of one of these classes. When the main loop invokes an -operation, say the addition, between two wrapped objects w1 and w2, -the StandardObjectSpace does some internal dispatching (similar to -"Object/ abstract.c" in CPython) and invokes a method of the proper -W_XyzObject class that can do the operation. The operation itself is -done with the primitives allowed by Restricted Python. The result is -constructed as a wrapped object again. - -The following was our first trivial program:: - - ### our first trivial program ### - - aStr = 'hello world' - print len(aStr) - -to run. We needed types and builtins to work. This ran, slowly. - -We began testing and adding types and builtins. - -Getting this code to work was the second goal.:: - - ### a trivial program to test strings, lists, functions and methods ### - - def addstr(s1,s2): - return s1 + s2 - - str = "an interesting string" - str2 = 'another::string::xxx::y:aa' - str3 = addstr(str,str2) - arr = [] - for word in str.split(): - if word in str2.split('::'): - arr.append(word) - print ''.join(arr) - print "str + str2 = ", str3 - -This we accomplished by mid-week. - -By the end of the Sprint we produced our first Python program [#]_ that -ran under PyPy which simply 'did something we wanted to do' and wasn't -an artificial goal. It calculated the week long foodbill, and divided -the result by the 9 Sprint participants.:: - - ### the first real PyPy Program ### - - slips=[(1, 'Kals MatMarkn', 6150, 'Chutney for Curry', 'dinner Saturday'), - (2, 'Kals MatMarkn', 32000, 'Spaghetti, Beer', 'dinner Monday'), - (2, 'Kals MatMarkn', -810, 'Deposit on Beer Bottles', 'various'), - (3, 'Fram', 7700, 'Rice and Curry Spice', 'dinner Saturday'), - ( ... ) - (23, 'Fram', 2975, 'Potatoes', '3.5 kg @ 8.50SEK'), - (23, 'Fram', 1421, 'Peas', 'Thursday dinner'),] - - print (reduce(lambda x, y: x+y, [t[2] for t in slips], 0))/900 - -Pypy said: 603 SEK, or approximately 75 USD. Don't believe people who -tell you that Sprints are too expensive to hold. - -The Annotation Object Space -+++++++++++++++++++++++++++ -Our third Sprint was held at Louvain-la-Neuve, Belgium (near -Brussels), June 21 - 24. Great progress was made with the The -Annotation Object Space, and began abstract, symbolic interpretation. -(We also spent a lot of time firming up the Standard Object Space, and -improving our documentation, and our documentation tools). - -In the two object spaces so far, application-level objects are -represented in the interpreter as objects that represent a value. -This is so obvious as to not need pointing out, except for the fact -that the Annotation space does something completely different. - -Here the interpreter-level object corresponding to a application-level -variable does not describe the value of the variable, but rather the -state of knowledge about the contents of the variable. -For example, after the code:: - - x = 1 - y = 2 - z = x + y - -we know exactly what *x*, *y* and *z* contain: the integers *1*, *2* and *3* -respectively, and this is how the annotation object space represents -them: there is a class W_Constant that represents totally known values. - -However in:: - - def f(x, y): - z = x + y - - f(1, 2) - f(2, 3) - -we know less. We know that x and y only contain integers, but their -values are no longer entirely fixed. In this case, the annotation -object space could chose to represent the variable in the body of f -as *either* the constant *1* or the constant *2*, but at present it punts -and simply represents it as an instance of W_Integer. - -The eventual hope is to run all of the code that implements PyPy's -interpreter and the standard object space with the annotation object -space and gain sufficient knowledge of the values involved to generate -efficient code (in C, Pyrex_, O'Caml, Java or whatever) to do the same -job. - -If you're wondering how we expect to get a speed up of 20000 times by -this translation when a speed up of 100 or so times is all that -usually obtained by rewriting in C, you have to understand that the -main reason for the standard object space's current slowness is the -computation of which code to execute each time a multimethod is -called. The knowledge gathered by the Annontation Object Space should -be sufficient to remove or at least substantially reduce this computation -for most of the call sites. - -Current plans are to use the information gathered from the Annotation Object -Space to emit Pyrex_ code which itself will generate a CPython extension. - -.. _Pyrex: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ - -Types -+++++ -Types are implemented by the class W_TypeObject. This is where -inheritance and the Method Resolution Order are defined, and where -attribute look-ups are done. - -Instances of user-defined types are implemented as W_UserObjects. A -user-defined type can inherit from built-in types (maybe more than -one, although this is incompatible with CPython). The W_UserObject -delegator converts the object into any of these "parent objects" if -needed. This is how user-defined types appear to inherit all built-in -operator implementations. - -Delegators should be able to invoke user code; this would let us -implement special methods like __int__() by calling them within a -W_UserObject -> int delegator. - -Multimethods -++++++++++++ -Interpreter-level classes correspond to implementations of -application-level types. The hierarchy among the classes used for the -implementations is convenient for implementation purposes. It is not -related to any application-level type hierarchy. Multimethods -dispatch by looking in a set of registered functions. Each registered -function has a signature, which defines which object implementation -classes are accepted at the corresponding argument position. - -Specifics of multimethods -+++++++++++++++++++++++++ -Multimethods dispatch more-specific-first, left-to-right (i.e. if -there is an exact match for the first argument it will always be tried -first). - -Delegators are automatically chained (i.e. A -> B and B -> C would be -combined to allow for A -> C delegation). - -Delegators do not publish the class of the converted object in -advance, so that the W_UserObject delegator can potentially produce -any other built-in implementation. This means chaining and chain loop -detection cannot be done statically (at least without help from an -analysis tool like the translator-to-C). To break loops, we can assume -(unless a particular need arises) that delegators are looping when -they return an object of an already-seen class. - -Registration -++++++++++++ -The register() method of multimethods adds a function to its database -of functions, with the given signature. A function that raises -FailedToImplement causes the next match to be tried. - -'delegate' is the special unary multimethod that should try to convert -its argument to something else. For greater control, it can also -return a list of 2-tuples (class, object), or an empty list for -failure to convert the argument to anything. All delegators will -potentially be tried, and recursively on each other's results to do -chaining. - -Multimethod slicing -+++++++++++++++++++ -Multimethods are visible to user code as (bound or unbound) methods -defined for the corresponding types. (At some point built-in functions -like *len()* and the *operator.xxx()* should really directly map to the -multimethods themselves, too.) - -To build a method from a multimethod (e.g. as in *l.append* or -*int.__add__*), the result is actually a "slice" of the whole -multimethod, i.e. a sub-multimethod in which the registration table -has been trimmed down. (Delegation mechanisms are not restricted for -sliced multimethods.) - -Say that C is the class the new method is attached to (in the above -examples, respectively, C=type(l) and C=int). The restriction is based -on the registered class of the first argument ('self' for the new -method) in the signature. If this class corresponds to a fixed type -(as advertized by 'statictype'), and this fixed type is C or a -superclass of C, then we keep it. - -Some multimethods can also be sliced along their second argument, -e.g. for __radd__(). - -A Word of History -+++++++++++++++++ - -The PyPy project was started in January of 2003 by Armin Rigo, -Christian Tismer and Holger Krekel. The latter organized the initial -Coding-Sprint in Hildesheim, Germany where the interpreter and the -Trivial Object Space were implemented and people first got together. -The second sprint in G?teborg, Sweden was organized by Jacob Hall?n and -Laura Creighton and it resulted in much of today's Standard Object Space -implementation. Benjamin Henrion and Godefroid Chapelle organized the -third sprint in Louvain-La-Neuve, Belgium which led to a pretty complete -Standard ObjectSpace and interpreter and the beginnings of Abstract -Interpretation (Annotation Object Space). These three coding -sprints in the course of half a year brought PyPy to existence, though -there was some off-sprint development and discussions going on. - -Participants -++++++++++++ - -.. line-block:: - - Laura Creighton - Stephan Diehl - Dinu Gherman - Jacob Hall?n - Michael Hudson - G?nter Jantzen - Holger Krekel - Anders Lehmann - Jens-Uwe Mager - Alex Martelli - Tomek Meka - Rocco Morretti - Samuele Pedroni - Anna Ravencroft - Armin Rigo - Guido van Rossum - Christian Tismer - -Conclusions -+++++++++++ -It is a little early for conclusions, but our architecture seems to be -working so far. Sprints are a lot of fun, and a great way to write -code, and meet interesting people. We're productively lazy, and so -have created a few tools that could possibly be useful to other -projects ... parts of our test rig, for example, and automatic ReST -processing on checkins. An Infastructure mini-Sprint, again at -Hildesheim, is planned which may produce tools good enough to package -and release separately. - -Thank you -+++++++++ -As was to be expected we are using Python web applications (mailman_, -roundup_, moinmoin_) to host our project. - -.. _mailman: http://www.list.org/ -.. _roundup: http://roundup.sourceforge.net/ -.. _moinmoin: http://moin.sourceforge.net/ - -The members of the PyPy team are especially grateful to RyanAir_, without -which holding Sprints would be prohibitively expensive, freenode.net_ -which lets us communicate with each other on the #pypy channel, and the -Subversion_ development team, without whom restructuring the entire universe -whenever we feel like it would have been close to impossible. - -.. _freenode.net: http://www.freenode.net/ -.. _RyanAir: http://www.ryanair.com/ -.. _Subversion: http://subversion.tigris.org/ - - -.. [#] The PyPy homepage: http://www.codespeak.net/pypy/ -.. [#] See for instance, Scheme48's PreScheme -.. [#] The Squeak homepage: http://www.squeak.org/ -.. [#] See *Back to the Future The Story of Squeak, A Practical - Smalltalk Written in Itself* ftp://st.cs.uiuc.edu/Smalltalk/Squeak/docs/OOPSLA.Squeak.html -.. [#] CPython is what we call the commonly available Python_ which you - can download from http://www.python.org . This is to distinguish it - from other implementations of the Python_ language, such as - Jython_, which is written for the Java virtual machine. -.. [#] The Psyco homespage: http://psyco.sourceforge.net/ -.. [#] The Stackless homespage: http://www.stackless.com/ -.. [#] The Jython homespage: http://www.jython.org/ -.. [#] The complete text is as follows: - -.. line-block:: - - *The Zen of Python* - - by Tim Peters - -.. line-block:: - - *Beautiful is better than ugly. - Explicit is better than implicit. - Simple is better than complex. - Complex is better than complicated. - Flat is better than nested. - Sparse is better than dense. - Readability counts. - Special cases aren't special enough to break the rules. - Although practicality beats purity. - Errors should never pass silently. - Unless explicitly silenced. - In the face of ambiguity, refuse the temptation to guess. - There should be one-- and preferably only one --obvious way to do it. - Although that way may not be obvious at first unless you're Dutch. - Now is better than never. - Although never is often better than _right_ now. - If the implementation is hard to explain, it's a bad idea. - If the implementation is easy to explain, it may be a good idea. - Namespaces are one honking great idea -- let's do more of those!* - -.. [#] The full text for historians and other curious people is: - -.. line-block:: - - slips=[ - (1, 'Kals MatMarkn', 6150, 'Chutney for Curry', 'dinner Saturday'), - (2, 'Kals MatMarkn', 32000, 'Spaghetti, Beer', 'dinner Monday'), - (2, 'Kals MatMarkn', -810, 'Deposit on Beer Bottles', 'various'), - (3, 'Fram', 7700, 'Rice and Curry Spice', 'dinner Saturday'), - (4, 'Kals MatMarkn', 25000, 'Alcohol-Free Beer, sundries', 'various'), - (4, 'Kals MatMarkn', -1570, "Michael's toothpaste", 'none'), - (4, 'Kals MatMarkn', -1690, "Laura's toothpaste", 'none'), - (4, 'Kals MatMarkn', -720, 'Deposit on Beer Bottles', 'various'), - (4, 'Kals MatMarkn', -60, 'Deposit on another Beer Bottle', 'various'), - (5, 'Kals MatMarkn', 26750, 'lunch bread meat cheese', 'lunch Monday'), - (6, 'Kals MatMarkn', 15950, 'various', 'dinner Tuesday and Thursday'), - (7, 'Kals MatMarkn', 3650, 'Drottningsylt, etc.', 'dinner Thursday'), - (8, 'Kals MatMarkn', 26150, 'Chicken and Mushroom Sauce', 'dinner Wed'), - (8, 'Kals MatMarkn', -2490, 'Jacob and Laura -- juice', 'dinner Wed'), - (8, 'Kals MatMarkn', -2990, "Chicken we didn't cook", 'dinner Wednesday'), - (9, 'Kals MatMarkn', 1380, 'fruit for Curry', 'dinner Saturday'), - (9, 'Kals MatMarkn', 1380, 'fruit for Curry', 'dinner Saturday'), - (10, 'Kals MatMarkn', 26900, 'Jansons Frestelse', 'dinner Sunday'), - (10, 'Kals MatMarkn', -540, 'Deposit on Beer Bottles', 'dinner Sunday'), - (11, 'Kals MatMarkn', 22650, 'lunch bread meat cheese', 'lunch Thursday'), - (11, 'Kals MatMarkn', -2190, 'Jacob and Laura -- juice', 'lunch Thursday'), - (11, 'Kals MatMarkn', -2790, 'Jacob and Laura -- cereal', 'lunch Thurs'), - (11, 'Kals MatMarkn', -760, 'Jacob and Laura -- milk', 'lunch Thursday'), - (12, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'lunch Friday'), - (13, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'guestimate Sun'), - (14, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'guestimate Tues'), - (15, 'Kals MatMarkn', 20000, 'lunch bread meat cheese', 'guestimate Wed'), - (16, 'Kals MatMarkn', 42050, 'grillfest', 'dinner Friday'), - (16, 'Kals MatMarkn', -1350, 'Deposit on Beer Bottles', 'dinner Friday'), - (17, 'System Bolaget', 15500, 'Cederlunds Caloric', 'dinner Thursday'), - (17, 'System Bolaget', 22400, '4 x Farnese Sangiovese 56SEK', 'various'), - (17, 'System Bolaget', 22400, '4 x Farnese Sangiovese 56SEK', 'various'), - (17, 'System Bolaget', 13800, '2 x Jacobs Creek 69SEK', 'various'), - (18, 'J and Ls winecabinet', 10800, '2 x Parrotes 54SEK', 'various'), - (18, 'J and Ls winecabinet', 14700, '3 x Saint Paulin 49SEK', 'various'), - (18, 'J and Ls winecabinet', 10400, '2 x Farnese Sangioves 52SEK','cheaper when we bought it'), - (18, 'J and Ls winecabinet', 17800, '2 x Le Poiane 89SEK', 'various'), - (18, 'J and Ls winecabinet', 9800, '2 x Something Else 49SEK', 'various'), - (19, 'Konsum', 26000, 'Saturday Bread and Fruit', 'Slip MISSING'), - (20, 'Konsum', 15245, 'Mooseburgers', 'found slip'), - (21, 'Kals MatMarkn', 20650, 'Grilling', 'Friday dinner'), - (22, 'J and Ls freezer', 21000, 'Meat for Curry, grilling', ''), - (22, 'J and Ls cupboard', 3000, 'Rice', ''), - (22, 'J and Ls cupboard', 4000, 'Charcoal', ''), - (23, 'Fram', 2975, 'Potatoes', '3.5 kg @ 8.50SEK'), - (23, 'Fram', 1421, 'Peas', 'Thursday dinner'), - (24, 'Kals MatMarkn', 20650, 'Grilling', 'Friday dinner'), - (24, 'Kals MatMarkn', -2990, 'TP', 'None'), - (24, 'Kals MatMarkn', -2320, 'T-Gul', 'None') - ] - - print [t[2] for t in slips] - print (reduce(lambda x, y: x+y, [t[2] for t in slips], 0))/900 Deleted: /pypy/extradoc/psycoguide.ps.gz ============================================================================== Binary file. No diff available. Deleted: /pypy/extradoc/pypy-talk-ep2004.txt ============================================================================== --- /pypy/extradoc/pypy-talk-ep2004.txt Tue Jan 18 10:52:27 2005 +++ (empty file) @@ -1,14 +0,0 @@ - -EuroPython 2004 PyPy talk - -1. Motivation / small summary of our EU efforts (Laura?) - -2. architecture / pygame view (Michael, Armin) - -3. source explanation + lower level architecture + examples (Holger) - -4. translation / flowgraphs / (Samuele) - -5. future directions / how to get involved / questions - (al together) - From hpk at codespeak.net Tue Jan 18 10:54:02 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 10:54:02 +0100 (MET) Subject: [pypy-svn] r8368 - pypy/dist/pypy/documentation Message-ID: <20050118095402.6793C27BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 10:54:02 2005 New Revision: 8368 Added: pypy/dist/pypy/documentation/index.txt - copied unchanged from r8366, pypy/extradoc/index.txt Log: forgot the index From hpk at codespeak.net Tue Jan 18 11:58:13 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 11:58:13 +0100 (MET) Subject: [pypy-svn] r8371 - pypy/dist/pypy/documentation Message-ID: <20050118105813.0CFCE27BB9@code1.codespeak.net> Author: hpk Date: Tue Jan 18 11:58:12 2005 New Revision: 8371 Modified: pypy/dist/pypy/documentation/newrepolayout.txt Log: slight fix to the plan to match reality :-) Modified: pypy/dist/pypy/documentation/newrepolayout.txt ============================================================================== --- pypy/dist/pypy/documentation/newrepolayout.txt (original) +++ pypy/dist/pypy/documentation/newrepolayout.txt Tue Jan 18 11:58:12 2005 @@ -39,7 +39,7 @@ README.txt # tell how to run PyPy, the translator, tests LICENSE.txt # copyright notices for tree parts including pypy - doc # non-dist documentations (papers etc.pp.) + extradoc # non-dist documentations (papers etc.pp.) talk # various pypy-talks paper # various pypy-related papers (including our own) sprint # sprint related information (reports etc.pp.) From hpk at codespeak.net Tue Jan 18 12:11:10 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 12:11:10 +0100 (MET) Subject: [pypy-svn] r8374 - pypy/branch/src-new-utest Message-ID: <20050118111110.545B827BC1@code1.codespeak.net> Author: hpk Date: Tue Jan 18 12:11:10 2005 New Revision: 8374 Removed: pypy/branch/src-new-utest/ Log: this branch is long unused and Laura's utestconvert has long since been moved to the pypy's dist "trunk". From hpk at codespeak.net Tue Jan 18 16:11:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 16:11:27 +0100 (MET) Subject: [pypy-svn] r8385 - pypy/dist/pypy/documentation Message-ID: <20050118151127.DB27927B5E@code1.codespeak.net> Author: hpk Date: Tue Jan 18 16:11:27 2005 New Revision: 8385 Modified: pypy/dist/pypy/documentation/readme.txt Log: added information about source code to readme (what is currently the "source" menu entry Modified: pypy/dist/pypy/documentation/readme.txt ============================================================================== --- pypy/dist/pypy/documentation/readme.txt (original) +++ pypy/dist/pypy/documentation/readme.txt Tue Jan 18 16:11:27 2005 @@ -1,14 +1,84 @@ -===================== +PyPy Source Code +================ + +.. contents:: +.. sectnum:: + +Checking out & running PyPy as a two-liner +------------------------------------------ + +There is no public release yet, but you can easily + + + svn co http://codespeak.net/svn/pypy/dist dist-pypy + +After checkout you should be able to get a PyPy interpreter via:: + + python dist-pypy/pypy/interpreter/py.py + +have fun :-) + + +Browsing via HTTP and getting an svn client +------------------------------------------- + +You can `browse the pypy source code`_ directly via http. +(sorry, viewcvs is still not stable enough with subversion). +And here is some information to `install a subversion client`_. + +.. _`install a subversion client`: howtosvn.html +.. _`browse the pypy source code`: http://codespeak.net/svn/pypy/dist + + +coding style and testing +------------------------ + +We keep a strong focus on testing because we want to be able +to refactor things all the time (without proper automated +testing this would become very hard and fragile). + +For an overview of how we organize our codebase please look at our +`coding-style document`_. + +For running all PyPy tests you can issue:: + + cd dist-pypy/pypy/ + python test_all.py + +test_all.py really is another name for `py.test`_ which is a testing +tool working from the current directory unless you specify +filename/directory arguments. + +If you want to have write access to the codespeak respository +please send a mail to jum at anubis han de or hpk at merlinux de +in order to ask for a username and password. Please mention what you want to do +within the pypy project. Even better, come to our next sprint so that we can get +to know you. + +.. _`documentation start page`: http://codespeak.net/pypy/index.cgi?doc/index.html +.. _`coding-style document`: http://codespeak.net/pypy/index.cgi?doc/devel/coding-style.html +.. _`py.test`: /py/current/doc/test.html + + PyPy Documentation -===================== +================== + -PyPy documentation is generated from reST textfiles in the /doc directory of -our pypy-subversion repository. On the pypy home page you'll find a "doc" link that -shows you a list of recently modified documents. While in "doc-view" you also have -a navigation area on the left side which maps all documentation. +Viewing documentation +--------------------- + +PyPy documentation is generated from reST textfiles in the pypy/documentation directory of +our pypy-subversion repository. Go to the `documentation start page`_ and hit +"recently modified" to get a list of recently modified documents. While in +"doc-view" you also have a navigation area on the left side which maps all +documentation files. + +Adding documentation +-------------------- Please add new or updated documentation by checking it in to the appropriate -directory in subversion, usually under http://codespeak.net/svn/pypy/trunk/doc/. +directory in subversion, usually under +http://codespeak.net/svn/pypy/dist/pypy/documentation + Remember to run ``svn up`` **before** doing any commit. + All filenames should be lowercase, and documentation should be .txt files. @@ -19,7 +89,7 @@ runs the parser, it'll look ugly on the website. So run docutils yourself before you commit it. Some reST basics: ------------------- +----------------- There should be a title on your page. Do it like this:: @@ -48,7 +118,6 @@ You can get more info on reST markup at http://docutils.sourceforge.net/docs/rst/quickref.html ------------------------- Checking your work ------------------------ From hpk at codespeak.net Tue Jan 18 16:13:57 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 16:13:57 +0100 (MET) Subject: [pypy-svn] r8386 - pypy/dist/pypy/documentation Message-ID: <20050118151357.A8C5E27B5E@code1.codespeak.net> Author: hpk Date: Tue Jan 18 16:13:57 2005 New Revision: 8386 Modified: pypy/dist/pypy/documentation/readme.txt Log: improved the readme markup Modified: pypy/dist/pypy/documentation/readme.txt ============================================================================== --- pypy/dist/pypy/documentation/readme.txt (original) +++ pypy/dist/pypy/documentation/readme.txt Tue Jan 18 16:13:57 2005 @@ -7,12 +7,11 @@ Checking out & running PyPy as a two-liner ------------------------------------------ -There is no public release yet, but you can easily - +There is no public release yet, but you can easily do:: svn co http://codespeak.net/svn/pypy/dist dist-pypy -After checkout you should be able to get a PyPy interpreter via:: +and after checkout you can get a PyPy interpreter via:: python dist-pypy/pypy/interpreter/py.py From hpk at codespeak.net Tue Jan 18 16:21:56 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 16:21:56 +0100 (MET) Subject: [pypy-svn] r8387 - pypy/dist/pypy/documentation Message-ID: <20050118152156.87D1227B5E@code1.codespeak.net> Author: hpk Date: Tue Jan 18 16:21:56 2005 New Revision: 8387 Modified: pypy/dist/pypy/documentation/readme.txt Log: fixed url Modified: pypy/dist/pypy/documentation/readme.txt ============================================================================== --- pypy/dist/pypy/documentation/readme.txt (original) +++ pypy/dist/pypy/documentation/readme.txt Tue Jan 18 16:21:56 2005 @@ -55,7 +55,7 @@ to know you. .. _`documentation start page`: http://codespeak.net/pypy/index.cgi?doc/index.html -.. _`coding-style document`: http://codespeak.net/pypy/index.cgi?doc/devel/coding-style.html +.. _`coding-style document`: http://codespeak.net/pypy/index.cgi?doc/coding-style.html .. _`py.test`: /py/current/doc/test.html From hpk at codespeak.net Tue Jan 18 16:24:26 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 16:24:26 +0100 (MET) Subject: [pypy-svn] r8388 - pypy/dist/pypy/documentation Message-ID: <20050118152426.D3D1A27B5B@code1.codespeak.net> Author: hpk Date: Tue Jan 18 16:24:26 2005 New Revision: 8388 Modified: pypy/dist/pypy/documentation/howtopypy.txt pypy/dist/pypy/documentation/howtosvn.txt pypy/dist/pypy/documentation/index.txt pypy/dist/pypy/documentation/newrepolayout.txt Log: fixming more URLs Modified: pypy/dist/pypy/documentation/howtopypy.txt ============================================================================== --- pypy/dist/pypy/documentation/howtopypy.txt (original) +++ pypy/dist/pypy/documentation/howtopypy.txt Tue Jan 18 16:24:26 2005 @@ -16,7 +16,7 @@ 2. Change to the directory where you wish to install the source tree, and use subversion to download the source:: - svn co http://codespeak.net/svn/pypy/trunk/src + svn co http://codespeak.net/svn/pypy/dist This will create a subdirectory named ``src``, and will create the PyPy source tree under this directory. @@ -24,7 +24,7 @@ If desired, you can also download the documentation:: - svn co http://codespeak.net/svn/pypy/trunk/doc + svn co http://codespeak.net/svn/pypy/extradoc 3. To start interpreting Python with PyPy, use Python 2.3 or greater:: @@ -175,31 +175,31 @@ -------------------------------------------------------------------------------- -.. _subversion: http://codespeak.net/pypy/index.cgi?doc/devel/howtosvn.html +.. _subversion: http://codespeak.net/pypy/index.cgi?doc/howtosvn.html .. _Dot Graphviz: http://www.research.att.com/sw/tools/graphviz/ .. _Pygame: http://www.pygame.org/ -.. _src/pypy/interpreter: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/ -.. _pyopcode.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/pyopcode.py -.. _eval.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/eval.py -.. _pyframe.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/pyframe.py -.. _function.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/function.py -.. _argument.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/argument.py -.. _baseobjspace.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/baseobjspace.py -.. _module.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/module.py -.. _extmodule.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/extmodule.py -.. _typedef.py: http://codespeak.net/svn/pypy/trunk/src/pypy/interpreter/typedef.py -.. _src/pypy/objspace/std: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/std/ -.. _Standard object space: http://codespeak.net/pypy/index.cgi?doc/objspace/stdobjspace.html -.. _objspace.py: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/std/objspace.py -.. _src/pypy/objspace: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/ -.. _trace: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/trace.py -.. _flow: http://codespeak.net/svn/pypy/trunk/src/pypy/objspace/flow/ -.. _src/pypy/translator: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/ -.. _translator.py: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/translator.py -.. _src/pypy/annotation: http://codespeak.net/svn/pypy/trunk/src/pypy/annotation/ -.. _src/pypy/translator/annrpython.py: http://codespeak.net/svn/pypy/trunk/src/pypy/translator/annrpython.py +.. _src/pypy/interpreter: http://codespeak.net/svn/pypy/dist/pypy/interpreter/ +.. _pyopcode.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/pyopcode.py +.. _eval.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/eval.py +.. _pyframe.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/pyframe.py +.. _function.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/function.py +.. _argument.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/argument.py +.. _baseobjspace.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/baseobjspace.py +.. _module.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/module.py +.. _extmodule.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/extmodule.py +.. _typedef.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/typedef.py +.. _src/pypy/objspace/std: http://codespeak.net/svn/pypy/dist/pypy/objspace/std/ +.. _Standard object space: http://codespeak.net/pypy/index.cgi?doc/stdobjspace.html +.. _objspace.py: http://codespeak.net/svn/pypy/dist/pypy/objspace/std/objspace.py +.. _src/pypy/objspace: http://codespeak.net/svn/pypy/dist/pypy/objspace/ +.. _trace: http://codespeak.net/svn/pypy/dist/pypy/objspace/trace.py +.. _flow: http://codespeak.net/svn/pypy/dist/pypy/objspace/flow/ +.. _src/pypy/translator: http://codespeak.net/svn/pypy/dist/pypy/translator/ +.. _translator.py: http://codespeak.net/svn/pypy/dist/pypy/translator/translator.py +.. _src/pypy/annotation: http://codespeak.net/svn/pypy/dist/pypy/annotation/ +.. _src/pypy/translator/annrpython.py: http://codespeak.net/svn/pypy/dist/pypy/translator/annrpython.py .. _mailing lists: http://codespeak.net/pypy/index.cgi?lists .. _documentation: http://codespeak.net/pypy/index.cgi?doc .. _wiki: http://codespeak.net/moin/pypy/moin.cgi/FrontPage?action=show -.. _unit tests: http://codespeak.net/pypy/index.cgi?doc/devel/testdesign.html +.. _unit tests: http://codespeak.net/pypy/index.cgi?doc/testdesign.html .. _bug reports: http://codespeak.net/issues/pypy/ Modified: pypy/dist/pypy/documentation/howtosvn.txt ============================================================================== --- pypy/dist/pypy/documentation/howtosvn.txt (original) +++ pypy/dist/pypy/documentation/howtosvn.txt Tue Jan 18 16:24:26 2005 @@ -58,8 +58,8 @@ There are currently two directories you'll want to check out: /src and /doc In order to get the sourcecode and docs downloaded onto your drive, open a shell or commandline and type:: - $ svn co http://codespeak.net/svn/pypy/trunk/src - $ svn co http://codespeak.net/svn/pypy/trunk/doc + $ svn co http://codespeak.net/svn/pypy/dist + $ svn co http://codespeak.net/svn/pypy/extradoc If you are behind a dump proxy this may or may not work; see below. @@ -147,7 +147,7 @@ .. _guide: http://svnbook.red-bean.com/book.html#svn-ch-1 .. _archives: http://codespeak.net/pipermail/pypy-svn/ .. _online: http://codespeak.net/svn/pypy/trunk/ -.. _coding-style: http://codespeak.net/pypy/doc/devel/coding-style.html +.. _coding-style: http://codespeak.net/pypy/doc/coding-style.html .. _readme: http://codespeak.net/pypy/doc/readme.html .. _HowToInstallServer: http://codespeak.net/moin/pypy/moin.cgi/HowToInstallServer .. _backports: http://www.backports.org Modified: pypy/dist/pypy/documentation/index.txt ============================================================================== --- pypy/dist/pypy/documentation/index.txt (original) +++ pypy/dist/pypy/documentation/index.txt Tue Jan 18 16:24:26 2005 @@ -38,7 +38,7 @@ * wrapping_: a description of application-level and interpreter-level wrapped objects -This file is in the *doc/devel/* sub-directory: +This file is in the *doc/* sub-directory: * howtosvn_: for new users of subversion @@ -46,7 +46,7 @@ Before you code --------------- -Before doing pypy work, you should also take a look at these developer-specific instructions, found in the *doc/devel/* sub-directory of the repository: +Before doing pypy work, you should also take a look at these developer-specific instructions, found in the *doc/* sub-directory of the repository: * coding-style_: covers pypy coding conventions @@ -90,10 +90,10 @@ .. _howtopypy: http://codespeak.net/pypy/index.cgi?doc/howtopypy.html .. _readme: http://codespeak.net/pypy/index.cgi?doc/readme.html .. _wrapping: http://codespeak.net/pypy/index.cgi?doc/wrapping.html -.. _coding-style: http://codespeak.net/pypy/index.cgi?doc/devel/coding-style.html -.. _howtosvn: http://codespeak.net/pypy/index.cgi?doc/devel/howtosvn.html -.. _optionaltool: http://codespeak.net/pypy/index.cgi?doc/devel/optionaltool.html -.. _testdesign: http://codespeak.net/pypy/index.cgi?doc/devel/testdesign.html +.. _coding-style: http://codespeak.net/pypy/index.cgi?doc/coding-style.html +.. _howtosvn: http://codespeak.net/pypy/index.cgi?doc/howtosvn.html +.. _optionaltool: http://codespeak.net/pypy/index.cgi?doc/optionaltool.html +.. _testdesign: http://codespeak.net/pypy/index.cgi?doc/testdesign.html .. _feasible: http://codespeak.net/pipermail/pypy-dev/2004q2/001289.html .. _rock: http://codespeak.net/pipermail/pypy-dev/2004q1/001255.html .. _Scheme: http://codespeak.net/pipermail/pypy-dev/2004q1/001256.html Modified: pypy/dist/pypy/documentation/newrepolayout.txt ============================================================================== --- pypy/dist/pypy/documentation/newrepolayout.txt (original) +++ pypy/dist/pypy/documentation/newrepolayout.txt Tue Jan 18 16:24:26 2005 @@ -9,16 +9,16 @@ years into something that needs some refactoring to become more practical. -For example, the `trunk/doc`_ directory was originally intended +For example, the `extradoc`_ directory was originally intended to hold developer documentation but nowadays it contains funding, negotiations, mails and misc-other-stuff documents. It is not easy and obvious anymore to know which files are relevant. -Moreover, `trunk/doc`_ is too far away from the source code: -developers currently checkout the 'trunk/src' directory and +Moreover, `extradoc`_ is too far away from the source code: +developers currently checkout the 'dist' directory and don't even get the documentation. This also makes it more difficult to keep the documentation up-to-date. -.. _`trunk/doc`: http://codespeak.net/svn/pypy/trunk/doc +.. _`extradoc`: http://codespeak.net/svn/pypy/extradoc .. _`PyPy repository layout`: http://codespeak.net/svn/pypy/ New repo layout proposal Nr. 1 @@ -32,7 +32,7 @@ tag # holds tagged dist-versions dist # holds current development - pypy # current trunk/src/pypy + pypy # current dist/pypy documentation # developer documentation (inside pypy!) py # and other 'externals' setup.py # should be there at some point From hpk at codespeak.net Tue Jan 18 16:34:11 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 16:34:11 +0100 (MET) Subject: [pypy-svn] r8389 - pypy/dist/pypy/documentation Message-ID: <20050118153411.15ABB27B5B@code1.codespeak.net> Author: hpk Date: Tue Jan 18 16:34:10 2005 New Revision: 8389 Modified: pypy/dist/pypy/documentation/howtopypy.txt Log: fixing urls and what not (i'd like to merge this document with the readme-one at some point) Modified: pypy/dist/pypy/documentation/howtopypy.txt ============================================================================== --- pypy/dist/pypy/documentation/howtopypy.txt (original) +++ pypy/dist/pypy/documentation/howtopypy.txt Tue Jan 18 16:34:10 2005 @@ -16,26 +16,20 @@ 2. Change to the directory where you wish to install the source tree, and use subversion to download the source:: - svn co http://codespeak.net/svn/pypy/dist - - This will create a subdirectory named ``src``, and will create - the PyPy source tree under this directory. - - - If desired, you can also download the documentation:: - - svn co http://codespeak.net/svn/pypy/extradoc + svn co http://codespeak.net/svn/pypy/dist dist-pypy + This will create a directory named ``dist-pypy``, and will get + you the PyPy source in ``dist-pypy/pypy`` and documentation + files in ``dist-pypy/pypy/documentation``. 3. To start interpreting Python with PyPy, use Python 2.3 or greater:: - cd src/pypy/interpreter + cd dist-pypy/pypy/interpreter python py.py After a few seconds, you should be at the PyPy prompt, which is the same as the Python prompt, but with an extra ">". - 4. Now you are ready to start running Python code. Some real Python modules will not run yet, and others will run too slowly to be worth waiting for, but a few are fun to run:: @@ -71,22 +65,28 @@ a couple of different categories of tests which you can run. To run all the unit tests:: - cd src/pypy + cd dist-pypy/pypy python test_all.py Alternatively, you may run subtests by going to the correct subdirectory and running them individually:: - cd src/pypy/module/test - python test_builtin.py + cd dist-pypy/pypy + python test_all.py module/test/test_builtin.py + + ``test_all.py`` is actually just a synonym for `py.test`_ which is + our external testing tool. If you have installed that then you + can as well just issue ``py.test DIRECTORY_OR_FILE`` in order + to perform test runs. Finally, there are some more advanced tests (which are derived from some of the standard CPython tests). These are not part of the unit tests, because they take longer than the standard unit tests:: - cd src/pypy/interpreter + cd dist-pypy/pypy/interpreter python py.py ../appspace/builtin_types_test.py +.. _`py.test`: http://codespeak.net/py/current/doc/test.html Trying out the translator ========================= @@ -100,7 +100,7 @@ 3. Type:: - cd src/pypy/translator + cd dist-pypy/pypy/translator python -i translator.py Test snippets of translatable code are provided in the file @@ -137,30 +137,30 @@ PyPy is made from parts that are relatively independent from each other. You should start looking at the part that attracts you most: -* `src/pypy/interpreter`_ contains the basic interpreter: bytecode dispatcher +* `dist-pypy/pypy/interpreter`_ contains the basic interpreter: bytecode dispatcher in pyopcode.py_, frame and code objects in eval.py_ and pyframe.py_, function objects and argument passing in function.py_ and argument.py_, the object space interface definition in baseobjspace.py_, modules in module.py_ and extmodule.py_. Core types supporting the interpreter are defined in typedef.py_. -* `src/pypy/objspace/std`_ contains the `Standard object space`_. The main file +* `dist-pypy/pypy/objspace/std`_ contains the `Standard object space`_. The main file is objspace.py_. For each type, the files ``xxxtype.py`` and ``xxxobject.py`` contain respectively the definition of the type and its (default) implementation. -* `src/pypy/objspace`_ contains a few other object spaces: the trivial one +* `dist-pypy/pypy/objspace`_ contains a few other object spaces: the trivial one (but let's forget about it), the trace_ one, the flow_ one. The latter is a relatively short piece of code that builds the control flow graphs when the interpreter runs in it. -* `src/pypy/translator`_ contains the code analysis and generation stuff. +* `dist-pypy/pypy/translator`_ contains the code analysis and generation stuff. Start reading from translator.py_, from which it should be easy to follow the pieces of code involved in the various translation phases. -* `src/pypy/annotation`_ contains the data model for the type annotation that +* `dist-pypy/pypy/annotation`_ contains the data model for the type annotation that can be inferred about a graph. The graph "walker" that uses this is in - `src/pypy/translator/annrpython.py`_. + `dist-pypy/pypy/translator/annrpython.py`_. To learn more @@ -178,7 +178,7 @@ .. _subversion: http://codespeak.net/pypy/index.cgi?doc/howtosvn.html .. _Dot Graphviz: http://www.research.att.com/sw/tools/graphviz/ .. _Pygame: http://www.pygame.org/ -.. _src/pypy/interpreter: http://codespeak.net/svn/pypy/dist/pypy/interpreter/ +.. _dist-pypy/pypy/interpreter: http://codespeak.net/svn/pypy/dist/pypy/interpreter/ .. _pyopcode.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/pyopcode.py .. _eval.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/eval.py .. _pyframe.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/pyframe.py @@ -188,16 +188,16 @@ .. _module.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/module.py .. _extmodule.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/extmodule.py .. _typedef.py: http://codespeak.net/svn/pypy/dist/pypy/interpreter/typedef.py -.. _src/pypy/objspace/std: http://codespeak.net/svn/pypy/dist/pypy/objspace/std/ +.. _dist-pypy/pypy/objspace/std: http://codespeak.net/svn/pypy/dist/pypy/objspace/std/ .. _Standard object space: http://codespeak.net/pypy/index.cgi?doc/stdobjspace.html .. _objspace.py: http://codespeak.net/svn/pypy/dist/pypy/objspace/std/objspace.py -.. _src/pypy/objspace: http://codespeak.net/svn/pypy/dist/pypy/objspace/ +.. _dist-pypy/pypy/objspace: http://codespeak.net/svn/pypy/dist/pypy/objspace/ .. _trace: http://codespeak.net/svn/pypy/dist/pypy/objspace/trace.py .. _flow: http://codespeak.net/svn/pypy/dist/pypy/objspace/flow/ -.. _src/pypy/translator: http://codespeak.net/svn/pypy/dist/pypy/translator/ +.. _dist-pypy/pypy/translator: http://codespeak.net/svn/pypy/dist/pypy/translator/ .. _translator.py: http://codespeak.net/svn/pypy/dist/pypy/translator/translator.py -.. _src/pypy/annotation: http://codespeak.net/svn/pypy/dist/pypy/annotation/ -.. _src/pypy/translator/annrpython.py: http://codespeak.net/svn/pypy/dist/pypy/translator/annrpython.py +.. _dist-pypy/pypy/annotation: http://codespeak.net/svn/pypy/dist/pypy/annotation/ +.. _dist-pypy/pypy/translator/annrpython.py: http://codespeak.net/svn/pypy/dist/pypy/translator/annrpython.py .. _mailing lists: http://codespeak.net/pypy/index.cgi?lists .. _documentation: http://codespeak.net/pypy/index.cgi?doc .. _wiki: http://codespeak.net/moin/pypy/moin.cgi/FrontPage?action=show From hpk at codespeak.net Tue Jan 18 17:03:16 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 18 Jan 2005 17:03:16 +0100 (MET) Subject: [pypy-svn] r8390 - pypy/dist/pypy/documentation Message-ID: <20050118160316.2755327B5C@code1.codespeak.net> Author: hpk Date: Tue Jan 18 17:03:15 2005 New Revision: 8390 Removed: pypy/dist/pypy/documentation/readme.txt Modified: pypy/dist/pypy/documentation/howtopypy.txt pypy/dist/pypy/documentation/index.txt Log: merged readme.txt into howtopypy updated and simplified index.txt fixes various stuff Modified: pypy/dist/pypy/documentation/howtopypy.txt ============================================================================== --- pypy/dist/pypy/documentation/howtopypy.txt (original) +++ pypy/dist/pypy/documentation/howtopypy.txt Tue Jan 18 17:03:15 2005 @@ -2,9 +2,176 @@ Getting started with PyPy ================================== +.. contents:: +.. sectnum:: + +Just the facts +============== + + +Checking out & running PyPy as a two-liner +------------------------------------------ + +There is no public release yet, but you can easily do:: + + svn co http://codespeak.net/svn/pypy/dist dist-pypy + +and after checkout you can get a PyPy interpreter via:: + + python dist-pypy/pypy/interpreter/py.py + +have fun :-) + +You can also go the more `detailed version`_ of this +two-liner. + +Browsing via HTTP and getting an svn client +------------------------------------------- + +You can `browse the pypy source code`_ directly via http. +(sorry, viewcvs is still not stable enough with subversion). +And here is some information to `install a subversion client`_. + +.. _`install a subversion client`: howtosvn.html +.. _`browse the pypy source code`: http://codespeak.net/svn/pypy/dist + +coding style and testing +------------------------ + +We keep a strong focus on testing because we want to be able +to refactor things all the time (without proper automated +testing this would become very hard and fragile). + +For an overview of how we organize our codebase please look at our +`coding-style document`_. + +For running all PyPy tests you can issue:: + + cd dist-pypy/pypy/ + python test_all.py + +test_all.py really is another name for `py.test`_ which is a testing +tool working from the current directory unless you specify +filename/directory arguments. + +If you want to have write access to the codespeak respository +please send a mail to jum at anubis han de or hpk at merlinux de +in order to ask for a username and password. Please mention what you want to do +within the pypy project. Even better, come to our next sprint so that we can get +to know you. + +.. _`documentation start page`: http://codespeak.net/pypy/index.cgi?doc/index.html +.. _`coding-style document`: http://codespeak.net/pypy/index.cgi?doc/coding-style.html +.. _`py.test`: /py/current/doc/test.html + + +PyPy Documentation +================== + +Viewing documentation +--------------------- + +PyPy documentation is generated from reST textfiles in the pypy/documentation directory of +our pypy-subversion repository. Go to the `documentation start page`_ and hit +"recently modified" to get a list of recently modified documents. While in +"doc-view" you also have a navigation area on the left side which maps all +documentation files. + +Adding documentation +-------------------- + +Please add new or updated documentation by checking it in to the appropriate +directory in subversion, usually under +http://codespeak.net/svn/pypy/dist/pypy/documentation + ++ Remember to run ``svn up`` **before** doing any commit. ++ All filenames should be lowercase, and documentation should be .txt files. ++ Mark-up the documentation with reST so it can generate a pretty html version. ++ On the server side a commit on the doc-subtree will immediately update the webpage. + +*Note* If you don't markup the textfile, it'll still be checked in, but when docutils +runs the parser, it'll look ugly on the website. So run docutils yourself before you commit it. + +Some reST basics: +----------------- + +There should be a title on your page. Do it like this:: + + Here is my Title + ================== + + Here is a section title + ------------------------- + +Make sure you have a blank line after your = or - lines or it will give you an error. +For marking a block of code so it'll look right, you can:: + + Put a line of text ending with :: + indent your code at least one space + my code + more code + even more code + still more code + +End of the "block" occurs whenever you unindent back to the same level as the +text with the ``::`` at the end. + +Using an underscore after a word like this_ will make reST think you want a hyperlink. +To avoid that (especially with things like ``wrap_``), you can use the `` back quote `` +to mark it as plain text. + +You can get more info on reST markup at http://docutils.sourceforge.net/docs/rst/quickref.html + +Checking your work +------------------------ + +In order to make sure that what you commit looks reasonably pretty (or at least not +entirely broken), you'll need to run the ``docutils`` parser on it. Unless you've +installed it in the past, you probably don't have it installed. Open IDLE (or any +Python interactive environment) and try "import docutils". If it imports, hooray! +Otherwise, you'll need to download it. + +Go to sourceforge and download the ``snapshot`` version. Install it. + +*Note to Debian users:* Be sure you installed ``python2.2-dev``, which includes ``distutils``, +before trying to install ``docutils``. + +Once you have ``docutils`` installed, you can use it go to your shell and use it like this:: + + $ python ~/mypath/docutils/tools/buildhtml.py + /// Processing directory: /home/anna/downloads/arObjSpaceDoc + ::: Processing .txt: howtosvn.txt + ::: Processing .txt: index.txt + +**WARNING** This will process **all** text documents in the directory and any subdirectories. +I prefer to work on text in a separate directory, run the ``docutils`` parser to see what it +looks like, then copy the .txt file over to my local /doc checkouts to commit it. + +Use a browser menu to go to ``File: Open: filename.html`` then you can see what it looks +like. Look at the command shell to see what errors you've got on which lines and fix it +in your textfile. You can then re-run the buildhtml.py script and see what errors you get. +After it's fixed, you can commit the .txt file and it'll automagically be turned into html +viewable on the website. + + +Here are some sample reST textfiles to see what it looks like: + ++ ObjectSpace_ ++ ObjectSpaceInterface_ + +.. _this: http://docutils.sourceforge.net/docs/rst/quickref.html +.. _ObjectSpace: objspace/objspace.html +.. _ObjectSpaceInterface: objspace/objspaceinterface.html + + +.. _`detailed version`: + +The long'n detailed version +=========================== + PyPy sources can be browsed on the web at: - ``http://codespeak.net/svn/pypy/trunk/`` + http://codespeak.net/svn/pypy/dist Once you are ready to download and try PyPy out, follow these instructions, which assume that you @@ -12,7 +179,6 @@ 1. Download subversion_ if you do not already have it. - 2. Change to the directory where you wish to install the source tree, and use subversion to download the source:: @@ -86,8 +252,6 @@ cd dist-pypy/pypy/interpreter python py.py ../appspace/builtin_types_test.py -.. _`py.test`: http://codespeak.net/py/current/doc/test.html - Trying out the translator ========================= @@ -166,12 +330,14 @@ To learn more ============= -* To learn more about PyPy and its development process, read the documentation_ - and the wiki_, and consider subscribing to the `mailing lists`_ (or simply - read the archives online) or communicating via irc.freenode.net:6667, channel #pypy. - -* To help PyPy become Python-the-next-generation, write some `unit tests`_ and - file some `bug reports`_! +* To learn more about PyPy and its development process, head + read around in the documentation_ and the wiki_, and consider + subscribing to the `mailing lists`_ (or simply + read the archives online) or show up irc.freenode.net:6667, channel #pypy. + +* To help PyPy become Python-the-next-generation, you may write some + `unit tests`_ and file some `bug reports`_ (although we are not really + actively using the issue tracker yet, watch out :-) -------------------------------------------------------------------------------- Modified: pypy/dist/pypy/documentation/index.txt ============================================================================== --- pypy/dist/pypy/documentation/index.txt (original) +++ pypy/dist/pypy/documentation/index.txt Tue Jan 18 17:03:15 2005 @@ -1,66 +1,44 @@ -Pypy Documentation -================== +================================================= +PyPy - a Python_ implementation written in Python +================================================= -We have a fair amount of documentation for the Pypy project. The files -are available from the website as html (view them along the left side of -the pypy-doc webpage). They are also available from the repository, -under the *doc/* directory or under the *doc/devel* sub-directory. Or, -to catch up on what we've been up to lately, just peek at the -recently-modified_ documents page. +recently-modified_ -Overview --------- +.. _Python: http://www.python.org/dev/doc/maint24/ref/ref.html -If you just want an overview of the project, take a look at these items in *doc/*. +Here are some good entry points into PyPy's world: * architecture_: - a more technical overview of the current architecture - - * oscon2003-paper_: - presentation to OSCON on what pypy is about and why you should care - - -Getting Started ---------------- - -If you want to get involved, take a look at the following documentation to get a better taste: - -These file are in the *doc/* directory: + a technical overview of PyPy's current architecture * howtopypy_: - provides some hands-on instructions for getting started - - - * readme_: - this file is on using ReST for pypy documentation + provides some hands-on instructions for getting started, + including a two-liner to run PyPy on your computer. - * wrapping_: - a description of application-level and interpreter-level wrapped objects - -This file is in the *doc/* sub-directory: - - * howtosvn_: - for new users of subversion - -Before you code ---------------- - -Before doing pypy work, you should also take a look at these developer-specific instructions, found in the *doc/* sub-directory of the repository: +Before doing pypy coding, you might also take a look at these +developer-specific instructions: * coding-style_: covers pypy coding conventions - - * optionaltool_: there are some optional tools we use for pypy. + * wrapping_: + a description of the crucial distinction between application-level and + interpreter-level objects (without understanding this you might + have difficulties understanding PyPy's source code). + + * oscon2003-paper_: + presentation to OSCON on what pypy is about and why you should care + * testdesign_: - pypy is a test-driven development project.read here to find out more about how we're doing testing. + pypy is a test-driven development project. Read here to find out + more about how we're doing testing. -Further reading ---------------- +Further reading / related projects +---------------------------------- * An interesting thread on an HP tech report that may be proof the pypy is feasible_ . (We already knew that...) Deleted: /pypy/dist/pypy/documentation/readme.txt ============================================================================== --- /pypy/dist/pypy/documentation/readme.txt Tue Jan 18 17:03:15 2005 +++ (empty file) @@ -1,162 +0,0 @@ -PyPy Source Code -================ - -.. contents:: -.. sectnum:: - -Checking out & running PyPy as a two-liner ------------------------------------------- - -There is no public release yet, but you can easily do:: - - svn co http://codespeak.net/svn/pypy/dist dist-pypy - -and after checkout you can get a PyPy interpreter via:: - - python dist-pypy/pypy/interpreter/py.py - -have fun :-) - - -Browsing via HTTP and getting an svn client -------------------------------------------- - -You can `browse the pypy source code`_ directly via http. -(sorry, viewcvs is still not stable enough with subversion). -And here is some information to `install a subversion client`_. - -.. _`install a subversion client`: howtosvn.html -.. _`browse the pypy source code`: http://codespeak.net/svn/pypy/dist - - -coding style and testing ------------------------- - -We keep a strong focus on testing because we want to be able -to refactor things all the time (without proper automated -testing this would become very hard and fragile). - -For an overview of how we organize our codebase please look at our -`coding-style document`_. - -For running all PyPy tests you can issue:: - - cd dist-pypy/pypy/ - python test_all.py - -test_all.py really is another name for `py.test`_ which is a testing -tool working from the current directory unless you specify -filename/directory arguments. - -If you want to have write access to the codespeak respository -please send a mail to jum at anubis han de or hpk at merlinux de -in order to ask for a username and password. Please mention what you want to do -within the pypy project. Even better, come to our next sprint so that we can get -to know you. - -.. _`documentation start page`: http://codespeak.net/pypy/index.cgi?doc/index.html -.. _`coding-style document`: http://codespeak.net/pypy/index.cgi?doc/coding-style.html -.. _`py.test`: /py/current/doc/test.html - - -PyPy Documentation -================== - - -Viewing documentation ---------------------- - -PyPy documentation is generated from reST textfiles in the pypy/documentation directory of -our pypy-subversion repository. Go to the `documentation start page`_ and hit -"recently modified" to get a list of recently modified documents. While in -"doc-view" you also have a navigation area on the left side which maps all -documentation files. - -Adding documentation --------------------- - -Please add new or updated documentation by checking it in to the appropriate -directory in subversion, usually under -http://codespeak.net/svn/pypy/dist/pypy/documentation - -+ Remember to run ``svn up`` **before** doing any commit. -+ All filenames should be lowercase, and documentation should be .txt files. -+ Mark-up the documentation with reST so it can generate a pretty html version. -+ On the server side a commit on the doc-subtree will immediately update the webpage. - -*Note* If you don't markup the textfile, it'll still be checked in, but when docutils -runs the parser, it'll look ugly on the website. So run docutils yourself before you commit it. - -Some reST basics: ------------------ - -There should be a title on your page. Do it like this:: - - Here is my Title - ================== - - Here is a section title - ------------------------- - -Make sure you have a blank line after your = or - lines or it will give you an error. -For marking a block of code so it'll look right, you can:: - - Put a line of text ending with :: - indent your code at least one space - my code - more code - even more code - still more code - -End of the "block" occurs whenever you unindent back to the same level as the -text with the ``::`` at the end. - -Using an underscore after a word like this_ will make reST think you want a hyperlink. -To avoid that (especially with things like ``wrap_``), you can use the `` back quote `` -to mark it as plain text. - -You can get more info on reST markup at http://docutils.sourceforge.net/docs/rst/quickref.html - -Checking your work ------------------------- - -In order to make sure that what you commit looks reasonably pretty (or at least not -entirely broken), you'll need to run the ``docutils`` parser on it. Unless you've -installed it in the past, you probably don't have it installed. Open IDLE (or any -Python interactive environment) and try "import docutils". If it imports, hooray! -Otherwise, you'll need to download it. - -Go to sourceforge and download the ``snapshot`` version. Install it. - -*Note to Debian users:* Be sure you installed ``python2.2-dev``, which includes ``distutils``, -before trying to install ``docutils``. - -Once you have ``docutils`` installed, you can use it go to your shell and use it like this:: - - $ python ~/mypath/docutils/tools/buildhtml.py - /// Processing directory: /home/anna/downloads/arObjSpaceDoc - ::: Processing .txt: howtosvn.txt - ::: Processing .txt: index.txt - -**WARNING** This will process **all** text documents in the directory and any subdirectories. -I prefer to work on text in a separate directory, run the ``docutils`` parser to see what it -looks like, then copy the .txt file over to my local /doc checkouts to commit it. - -Use a browser menu to go to ``File: Open: filename.html`` then you can see what it looks -like. Look at the command shell to see what errors you've got on which lines and fix it -in your textfile. You can then re-run the buildhtml.py script and see what errors you get. -After it's fixed, you can commit the .txt file and it'll automagically be turned into html -viewable on the website. - - -Here are some sample reST textfiles to see what it looks like: - -+ ObjectSpace_ -+ ObjectSpaceInterface_ - ---------------------------------------------------------------------------------- - -.. _this: http://docutils.sourceforge.net/docs/rst/quickref.html -.. _ObjectSpace: objspace/objspace.html -.. _ObjectSpaceInterface: objspace/objspaceinterface.html - From pedronis at codespeak.net Tue Jan 18 19:47:37 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 18 Jan 2005 19:47:37 +0100 (MET) Subject: [pypy-svn] r8400 - pypy/branch/src-typedunwrap/pypy/interpreter Message-ID: <20050118184737.9765227B5E@code1.codespeak.net> Author: pedronis Date: Tue Jan 18 19:47:37 2005 New Revision: 8400 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Log: start of spec based unwrapping for interp2app gateways. Needs refactoring to: - get nicer - use just one BuiltinFrame subclass for unwrap signature not per gateways need to add handlers that effectivily do unwrapping. Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Tue Jan 18 19:47:37 2005 @@ -15,17 +15,149 @@ from pypy.interpreter.error import OperationError from pypy.interpreter import eval, pycode from pypy.interpreter.function import Function, Method -from pypy.interpreter.baseobjspace import Wrappable +from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +class Signature: + def __init__(self, func=None, argnames=None, varargname=None, kwargname=None): + self.func = func + if argnames is None: + argnames = [] + self.argnames = argnames + self.varargname = varargname + self.kwargname = kwargname + self.rewind() + + def rewind(self): + self._iter = iter(self.argnames) + + def __iter__(self): + return self + + def next(self): + return self._iter.next() + + def append(self, argname): + self.argnames.append(argname) + + def signature(self): + return self.argnames, self.varargname, self.kwargname + +def parse_unwrap_spec(unwrap_spec, func, argnames, varargname, kwargname, + new_sig): + orig_sig = Signature(func, argnames, varargname, kwargname) + + for el in unwrap_spec: + to_unwrap_spec_element[el](orig_sig, new_sig) + + return new_sig + + +class BuiltinCodeSignature(Signature): + + def __init__(self,*args,**kwds): + Signature.__init__(self,*args,**kwds) + self.setfastscope = [] + self.run_args = [] + self.through_scope_w = 0 + + + def make_frame_class(self): + setfastscope = self.setfastscope + if not setfastscope: + setfastscope = ["pass"] + setfastscope = ["def setfastscope(self, scope_w):"] + setfastscope + setfastscope = '\n '.join(setfastscope) + d = {} + exec setfastscope in globals(),d + exec """ +def run(self): + w_result = self.code.func(%s) + if w_result is None: + w_result = self.space.w_None + return w_result +""" % ','.join(self.run_args) in globals(),d + return type("BuiltinFrame_for_%s" % self.func.__name__, + (BuiltinFrame,),d) + + +def unwrap_spec_space(orig_sig, new_sig): + orig_sig.next() + # + new_sig.run_args.append('self.space') + +def unwrap_spec_self(orig_sig, new_sig): + argname = orig_sig.next() + new_sig.append(argname) + # + new_sig.setfastscope.append( + "self.arg_%s = self.space.unwrap_builtin(scope_w[%d])" % + (argname, new_sig.through_scope_w)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.arg_%s" % argname) + + +def unwrap_spec_wrapped(orig_sig, new_sig): + argname = orig_sig.next() + assert argname.startswith('w_'), ( + "argument %s of built-in function %r should " + "start with 'w_'" % (argname, orig_sig.func)) + new_sig.append(argname[2:]) + # + new_sig.setfastscope.append( + "self.arg_%s = scope_w[%d]" % (argname, new_sig.through_scope_w)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.arg_%s" % argname) + +def unwrap_spec_arguments(orig_sig, new_sig): + argname = orig_sig.next() + assert new_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + new_sig.varargname = 'args' + new_sig.kwargname = 'keywords' + # + cur = new_sig.through_scope_w + next = cur+1 + new_sig.through_scope_w += 2 + new_sig.setfastscope.append( + "self.arg_%s = " + "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" + % (argname, cur, next)) + new_sig.run_args.append("self.arg_%s" % argname) + +def unwrap_spec_starargs(orig_sig, new_sig): + varargname = orig_sig.varargname + assert varargname.endswith('_w'), ( + "argument *%s of built-in function %r should end in '_w'" % + (varargname, orig_sig.func)) + assert new_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + new_sig.varargname = varargname[:-2] + # + new_sig.setfastscope.append( + "self.arg_%s = self.space.unpacktuple(scope_w[%d])" % + (varargname, new_sig.through_scope_w)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("*self.arg_%s" % varargname) + + +to_unwrap_spec_element = { + ObjSpace: unwrap_spec_space, + 'self': unwrap_spec_self, + W_Root: unwrap_spec_wrapped, + Arguments: unwrap_spec_arguments, + '*': unwrap_spec_starargs, +} + + class BuiltinCode(eval.Code): "The code object implementing a built-in (interpreter-level) hook." # When a BuiltinCode is stored in a Function object, # you get the functionality of CPython's built-in function type. - def __init__(self, func, ismethod=None, spacearg=None): + def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None): "NOT_RPYTHON" # 'implfunc' is the interpreter-level function. # Note that this uses a lot of (construction-time) introspection. @@ -41,50 +173,63 @@ # Not exactly a clean approach XXX. # First extract the signature from the (CPython-level) code object argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) - argnames = list(argnames) - lookslikemethod = argnames[:1] == ['self'] - if ismethod is None: - ismethod = lookslikemethod - if spacearg is None: - spacearg = not lookslikemethod - self.ismethod = ismethod - self.spacearg = spacearg - if spacearg: - del argnames[0] - - assert kwargname is None, ( - "built-in function %r should not take a ** argument" % func) - - self.generalargs = argnames[-1:] == ['__args__'] - self.starargs = varargname is not None - assert not (self.generalargs and self.starargs), ( - "built-in function %r has both __args__ and a * argument" % func) - if self.generalargs: - del argnames[-1] - varargname = "args" - kwargname = "keywords" - elif self.starargs: - assert varargname.endswith('_w'), ( - "argument *%s of built-in function %r should end in '_w'" % - (varargname, func)) - varargname = varargname[:-2] - - for i in range(ismethod, len(argnames)): - a = argnames[i] - assert a.startswith('w_'), ( - "argument %s of built-in function %r should " - "start with 'w_'" % (a, func)) - argnames[i] = a[2:] + if unwrap_spec is None: + + unwrap_spec = [] + + argnames = list(argnames) + lookslikemethod = argnames[:1] == ['self'] + if ismethod is None: + ismethod = lookslikemethod + if spacearg is None: + spacearg = not lookslikemethod + self.ismethod = ismethod + self.spacearg = spacearg + assert kwargname is None, ( + "built-in function %r should not take a ** argument" % func) + + n = len(argnames) + + if self.ismethod: + unwrap_spec.append('self') + n -= 1 + if self.spacearg: + unwrap_spec.append(ObjSpace) + n -= 1 + + self.generalargs = argnames[-1:] == ['__args__'] + self.starargs = varargname is not None + + if self.generalargs: + unwrap_spec.extend([W_Root] * (n-1)) + unwrap_spec.append(Arguments) + else: + unwrap_spec.extend([W_Root] * n) + + if self.starargs: + unwrap_spec.append('*') + else: + assert ismethod is None,("if unwrap_spec is specified," + "ismethod is not expected") + assert spacearg is None,("if unwrap_spec is specified," + "spacearg is not expected") + + new_sig = parse_unwrap_spec(unwrap_spec, func, argnames, + varargname, kwargname, + BuiltinCodeSignature(func)) + + self.sig = argnames, varargname, kwargname = new_sig.signature() - self.sig = argnames, varargname, kwargname self.minargs = len(argnames) if self.starargs: self.maxargs = sys.maxint else: self.maxargs = self.minargs + self.framecls = new_sig.make_frame_class() + def create_frame(self, space, w_globals, closure=None): - return BuiltinFrame(space, self, w_globals) + return self.framecls(space, self, w_globals) def signature(self): return self.sig @@ -100,21 +245,23 @@ # via the interface defined in eval.Frame. def setfastscope(self, scope_w): - argarray = list(scope_w) - if self.code.generalargs: - w_kwds = argarray.pop() - w_args = argarray.pop() - argarray.append(Arguments.frompacked(self.space, w_args, w_kwds)) - elif self.code.starargs: - w_args = argarray.pop() - argarray += self.space.unpacktuple(w_args) - if self.code.ismethod: - argarray[0] = self.space.unwrap_builtin(argarray[0]) - self.argarray = argarray + pass +## argarray = list(scope_w) +## if self.code.generalargs: +## w_kwds = argarray.pop() +## w_args = argarray.pop() +## argarray.append(Arguments.frompacked(self.space, w_args, w_kwds)) +## elif self.code.starargs: +## w_args = argarray.pop() +## argarray += self.space.unpacktuple(w_args) +## if self.code.ismethod: +## argarray[0] = self.space.unwrap_builtin(argarray[0]) +## self.argarray = argarray def getfastscope(self): - raise OperationError(self.space.w_TypeError, - self.space.wrap("cannot get fastscope of a BuiltinFrame")) + pass +## raise OperationError(self.space.w_TypeError, +## self.space.wrap("cannot get fastscope of a BuiltinFrame")) def run(self): argarray = self.argarray From pedronis at codespeak.net Tue Jan 18 20:16:20 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 18 Jan 2005 20:16:20 +0100 (MET) Subject: [pypy-svn] r8404 - pypy/branch/src-typedunwrap/pypy/interpreter Message-ID: <20050118191620.BBD0127B5E@code1.codespeak.net> Author: pedronis Date: Tue Jan 18 20:16:20 2005 New Revision: 8404 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Log: corrected wrong commenting ou Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Tue Jan 18 20:16:20 2005 @@ -259,19 +259,19 @@ ## self.argarray = argarray def getfastscope(self): - pass -## raise OperationError(self.space.w_TypeError, -## self.space.wrap("cannot get fastscope of a BuiltinFrame")) + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a BuiltinFrame")) def run(self): - argarray = self.argarray - if self.code.spacearg: - w_result = self.code.func(self.space, *argarray) - else: - w_result = self.code.func(*argarray) - if w_result is None: - w_result = self.space.w_None - return w_result + pass +## argarray = self.argarray +## if self.code.spacearg: +## w_result = self.code.func(self.space, *argarray) +## else: +## w_result = self.code.func(*argarray) +## if w_result is None: +## w_result = self.space.w_None +## return w_result class Gateway(Wrappable): From ale at codespeak.net Wed Jan 19 12:47:07 2005 From: ale at codespeak.net (ale at codespeak.net) Date: Wed, 19 Jan 2005 12:47:07 +0100 (MET) Subject: [pypy-svn] r8409 - pypy/dist/pypy/appspace/test Message-ID: <20050119114707.B87E327B60@code1.codespeak.net> Author: ale Date: Wed Jan 19 12:47:07 2005 New Revision: 8409 Added: pypy/dist/pypy/appspace/test/test_struct.py Modified: pypy/dist/pypy/appspace/test/support_tests.py Log: Changed "tempdir" to "tmpdir" in support_tests.py in order to make it work. changed verbose to 0 to avoid unneccesary output. Added the python regression test for the struct module. The test module is only changed in what and how things are imported. The test produced a future warning under python 2.3.4, so unpack_* are using longs. Modified: pypy/dist/pypy/appspace/test/support_tests.py ============================================================================== --- pypy/dist/pypy/appspace/test/support_tests.py (original) +++ pypy/dist/pypy/appspace/test/support_tests.py Wed Jan 19 12:47:07 2005 @@ -9,7 +9,7 @@ from os import unlink import py -TESTFN = str(py.test.config.tempdir.join('@test')) +TESTFN = str(py.test.config.tmpdir.join('@test')) class Error(Exception): """Base class for regression test exceptions.""" @@ -35,7 +35,7 @@ and unexpected skips. """ -verbose = 1 # Flag set to 0 by regrtest.py +verbose = 0 # Flag set to 0 by regrtest.py use_resources = None # Flag set to [] by regrtest.py # _original_stdout is meant to hold stdout at the time regrtest began. @@ -121,9 +121,9 @@ -if fp is not None: - fp.close() -del fp +##if fp is not None: +## fp.close() +##del fp def findfile(file, here=__file__): """Try to find a file on sys.path and the working directory. If it is not Added: pypy/dist/pypy/appspace/test/test_struct.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/test/test_struct.py Wed Jan 19 12:47:07 2005 @@ -0,0 +1,439 @@ +import autopath +from pypy.appspace.test.support_tests import TestFailed, verbose, verify +from pypy.appspace import struct +import sys + +ISBIGENDIAN = sys.byteorder == "big" +del sys +verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN, + "bigendian determination appears wrong") + +def string_reverse(s): + chars = list(s) + chars.reverse() + return "".join(chars) + +def bigendian_to_native(value): + if ISBIGENDIAN: + return value + else: + return string_reverse(value) + +def simple_err(func, *args): + try: + func(*args) + except struct.error: + pass + else: + raise TestFailed, "%s%s did not raise struct.error" % ( + func.__name__, args) + +def any_err(func, *args): + try: + func(*args) + except (struct.error, OverflowError, TypeError): + pass + else: + raise TestFailed, "%s%s did not raise error" % ( + func.__name__, args) + + +simple_err(struct.calcsize, 'Z') + +sz = struct.calcsize('i') +if sz * 3 != struct.calcsize('iii'): + raise TestFailed, 'inconsistent sizes' + +fmt = 'cbxxxxxxhhhhiillffd' +fmt3 = '3c3b18x12h6i6l6f3d' +sz = struct.calcsize(fmt) +sz3 = struct.calcsize(fmt3) +if sz * 3 != sz3: + raise TestFailed, 'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % ( + fmt, sz, 3*sz, fmt3, sz3) + +simple_err(struct.pack, 'iii', 3) +simple_err(struct.pack, 'i', 3, 3, 3) +simple_err(struct.pack, 'i', 'foo') +simple_err(struct.pack, 'P', 'foo') +simple_err(struct.unpack, 'd', 'flap') +s = struct.pack('ii', 1, 2) +simple_err(struct.unpack, 'iii', s) +simple_err(struct.unpack, 'i', s) + +c = 'a' +b = 0 +h = 255 +i = 65535 +l = 65536 +f = 3.1415 +d = 3.1415 + +for prefix in ('', '@', '<', '>', '=', '!'): + for format in ('xcbhilfd', 'xcBHILfd'): + format = prefix + format + if verbose: + print "trying:", format + s = struct.pack(format, c, b, h, i, l, f, d) + cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) + if (cp != c or bp != b or hp != h or ip != i or lp != l or + int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): + # ^^^ calculate only to two decimal places + raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( + str(format), str((cp, bp, hp, ip, lp, fp, dp))) + +# Test some of the new features in detail + +# (format, argument, big-endian result, little-endian result, asymmetric) +tests = [ + ('c', 'a', 'a', 'a', 0), + ('xc', 'a', '\0a', '\0a', 0), + ('cx', 'a', 'a\0', 'a\0', 0), + ('s', 'a', 'a', 'a', 0), + ('0s', 'helloworld', '', '', 1), + ('1s', 'helloworld', 'h', 'h', 1), + ('9s', 'helloworld', 'helloworl', 'helloworl', 1), + ('10s', 'helloworld', 'helloworld', 'helloworld', 0), + ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1), + ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1), + ('b', 7, '\7', '\7', 0), + ('b', -7, '\371', '\371', 0), + ('B', 7, '\7', '\7', 0), + ('B', 249, '\371', '\371', 0), + ('h', 700, '\002\274', '\274\002', 0), + ('h', -700, '\375D', 'D\375', 0), + ('H', 700, '\002\274', '\274\002', 0), + ('H', 0x10000-700, '\375D', 'D\375', 0), + ('i', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0), + ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('l', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0), + ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('f', 2.0, '@\000\000\000', '\000\000\000@', 0), + ('d', 2.0, '@\000\000\000\000\000\000\000','\000\000\000\000\000\000\000@', 0), + ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), + ('d', -2.0, '\300\000\000\000\000\000\000\000','\000\000\000\000\000\000\000\300', 0), +] + +for fmt, arg, big, lil, asy in tests: + if verbose: + print "%r %r %r %r" % (fmt, arg, big, lil) + for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), + ('='+fmt, ISBIGENDIAN and big or lil)]: + res = struct.pack(xfmt, arg) + if res != exp: + raise TestFailed, "pack(%r, %r) -> %r # expected %r" % ( + fmt, arg, res, exp) + n = struct.calcsize(xfmt) + if n != len(res): + raise TestFailed, "calcsize(%r) -> %d # expected %d" % ( + xfmt, n, len(res)) + rev = struct.unpack(xfmt, res)[0] + if rev != arg and not asy: + raise TestFailed, "unpack(%r, %r) -> (%r,) # expected (%r,)" % ( + fmt, res, rev, arg) + +########################################################################### +# Simple native q/Q tests. + +has_native_qQ = 1 +try: + struct.pack("q", 5) +except struct.error: + has_native_qQ = 0 + +if verbose: + print "Platform has native q/Q?", has_native_qQ and "Yes." or "No." + +any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless +simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless +simple_err(struct.pack, "Q", "a") # ditto, but 'Q' + +def test_native_qQ(): + bytes = struct.calcsize('q') + # The expected values here are in big-endian format, primarily because + # I'm on a little-endian machine and so this is the clearest way (for + # me) to force the code to get exercised. + for format, input, expected in ( + ('q', -1, '\xff' * bytes), + ('q', 0, '\x00' * bytes), + ('Q', 0, '\x00' * bytes), + ('q', 1L, '\x00' * (bytes-1) + '\x01'), + ('Q', (1L << (8*bytes))-1, '\xff' * bytes), + ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): + got = struct.pack(format, input) + native_expected = bigendian_to_native(expected) + verify(got == native_expected, + "%r-pack of %r gave %r, not %r" % + (format, input, got, native_expected)) + retrieved = struct.unpack(format, got)[0] + verify(retrieved == input, + "%r-unpack of %r gave %r, not %r" % + (format, got, retrieved, input)) + +if has_native_qQ: + test_native_qQ() + +########################################################################### +# Standard integer tests (bBhHiIlLqQ). + +import binascii + +class IntTester: + + # XXX Most std integer modes fail to test for out-of-range. + # The "i" and "l" codes appear to range-check OK on 32-bit boxes, but + # fail to check correctly on some 64-bit ones (Tru64 Unix + Compaq C + # reported by Mark Favas). + BUGGY_RANGE_CHECK = "bBhHiIlL" + + def __init__(self, formatpair, bytesize): + assert len(formatpair) == 2 + self.formatpair = formatpair + for direction in "<>!=": + for code in formatpair: + format = direction + code + verify(struct.calcsize(format) == bytesize) + self.bytesize = bytesize + self.bitsize = bytesize * 8 + self.signed_code, self.unsigned_code = formatpair + self.unsigned_min = 0 + self.unsigned_max = 2L**self.bitsize - 1 + self.signed_min = -(2L**(self.bitsize-1)) + self.signed_max = 2L**(self.bitsize-1) - 1 + + def test_one(self, x, pack=struct.pack, + unpack=struct.unpack, + unhexlify=binascii.unhexlify): + if verbose: + print "trying std", self.formatpair, "on", x, "==", hex(x) + + # Try signed. + code = self.signed_code + if self.signed_min <= x <= self.signed_max: + # Try big -endian. + expected = long(x) + if x < 0: + expected += 1L << self.bitsize + assert expected > 0 + expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + if len(expected) & 1: + expected = "0" + expected + expected = unhexlify(expected) + expected = "\x00" * (self.bytesize - len(expected)) + expected + + # Pack work? + format = ">" + code + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + # Try little-endian. + format = "<" + code + expected = string_reverse(expected) + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + else: + # x is out of range -- verify pack realizes that. + if code in self.BUGGY_RANGE_CHECK: + if verbose: + print "Skipping buggy range check for code", code + else: + any_err(pack, ">" + code, x) + any_err(pack, "<" + code, x) + + # Much the same for unsigned. + code = self.unsigned_code + if self.unsigned_min <= x <= self.unsigned_max: + # Try big-endian. + format = ">" + code + expected = long(x) + expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + if len(expected) & 1: + expected = "0" + expected + expected = unhexlify(expected) + expected = "\x00" * (self.bytesize - len(expected)) + expected + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + # Try little-endian. + format = "<" + code + expected = string_reverse(expected) + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + else: + # x is out of range -- verify pack realizes that. + if code in self.BUGGY_RANGE_CHECK: + if verbose: + print "Skipping buggy range check for code", code + else: + any_err(pack, ">" + code, x) + any_err(pack, "<" + code, x) + + def run(self): + from random import randrange + + # Create all interesting powers of 2. + values = [] + for exp in range(self.bitsize + 3): + values.append(1L << exp) + + # Add some random values. + for i in range(self.bitsize): + val = 0L + for j in range(self.bytesize): + val = (val << 8) | randrange(256) + values.append(val) + + # Try all those, and their negations, and +-1 from them. Note + # that this tests all power-of-2 boundaries in range, and a few out + # of range, plus +-(2**n +- 1). + for base in values: + for val in -base, base: + for incr in -1, 0, 1: + x = val + incr + try: + x = int(x) + except OverflowError: + pass + self.test_one(x) + + # Some error cases. + for direction in "<>": + for code in self.formatpair: + for badobject in "a string", 3+42j, randrange: + any_err(struct.pack, direction + code, badobject) + +for args in [("bB", 1), + ("hH", 2), + ("iI", 4), + ("lL", 4), + ("qQ", 8)]: + t = IntTester(*args) + t.run() + + +########################################################################### +# The p ("Pascal string") code. + +def test_p_code(): + for code, input, expected, expectedback in [ + ('p','abc', '\x00', ''), + ('1p', 'abc', '\x00', ''), + ('2p', 'abc', '\x01a', 'a'), + ('3p', 'abc', '\x02ab', 'ab'), + ('4p', 'abc', '\x03abc', 'abc'), + ('5p', 'abc', '\x03abc\x00', 'abc'), + ('6p', 'abc', '\x03abc\x00\x00', 'abc'), + ('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]: + got = struct.pack(code, input) + if got != expected: + raise TestFailed("pack(%r, %r) == %r but expected %r" % + (code, input, got, expected)) + (got,) = struct.unpack(code, got) + if got != expectedback: + raise TestFailed("unpack(%r, %r) == %r but expected %r" % + (code, input, got, expectedback)) + +test_p_code() + + +########################################################################### +# SF bug 705836. "f" had a severe rounding bug, where a carry +# from the low-order discarded bits could propagate into the exponent +# field, causing the result to be wrong by a factor of 2. + +def test_705836(): + import math + + for base in range(1, 33): + # smaller <- largest representable float less than base. + delta = 0.5 + while base - delta / 2.0 != base: + delta /= 2.0 + smaller = base - delta + # Packing this rounds away a solid string of trailing 1 bits. + packed = struct.pack("f", smaller) + verify(bigpacked == string_reverse(packed), + ">f pack should be byte-reversal of f", bigpacked)[0] + verify(base == unpacked) + + # Largest finite IEEE single. + big = (1 << 24) - 1 + big = math.ldexp(big, 127 - 23) + packed = struct.pack(">f", big) + unpacked = struct.unpack(">f", packed)[0] + verify(big == unpacked) + + # The same, but tack on a 1 bit so it rounds up to infinity. + big = (1 << 25) - 1 + big = math.ldexp(big, 127 - 24) + try: + packed = struct.pack(">f", big) + except OverflowError: + pass + else: + TestFailed("expected OverflowError") + +test_705836() From hpk at codespeak.net Wed Jan 19 13:58:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 19 Jan 2005 13:58:17 +0100 (MET) Subject: [pypy-svn] r8413 - pypy/dist/pypy/documentation Message-ID: <20050119125817.31EE927B5B@code1.codespeak.net> Author: hpk Date: Wed Jan 19 13:58:17 2005 New Revision: 8413 Modified: pypy/dist/pypy/documentation/ (props changed) Log: ignore exactly the generated html files (and pyc and pyo ones) From pedronis at codespeak.net Wed Jan 19 15:15:20 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 19 Jan 2005 15:15:20 +0100 (MET) Subject: [pypy-svn] r8418 - pypy/branch/src-typedunwrap/pypy/interpreter Message-ID: <20050119141520.E07B827B5B@code1.codespeak.net> Author: pedronis Date: Wed Jan 19 15:15:20 2005 New Revision: 8418 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Log: refactored unwrap_spec support for interp2app gateways, unwrap_spec can be passed to interp2app or attached as an attribute to the function. It is a list of types or singleton objects: baseobjspace.ObjSpace is used to specify the space argument 'self' is used to specify a self method argument baseobjspace.W_Root is for wrapped arguments to keep wrapped argument.Arguments is for a final rest arguments Arguments object Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Wed Jan 19 15:15:20 2005 @@ -20,8 +20,13 @@ from pypy.tool.cache import Cache class Signature: - def __init__(self, func=None, argnames=None, varargname=None, kwargname=None): + def __init__(self, func=None, argnames=None, varargname=None, + kwargname=None, name = None): self.func = func + if func is not None: + self.name = func.__name__ + else: + self.name = name if argnames is None: argnames = [] self.argnames = argnames @@ -44,13 +49,9 @@ def signature(self): return self.argnames, self.varargname, self.kwargname -def parse_unwrap_spec(unwrap_spec, func, argnames, varargname, kwargname, - new_sig): - orig_sig = Signature(func, argnames, varargname, kwargname) - +def apply_unwrap_spec(unwrap_spec, orig_sig, new_sig, recipes): for el in unwrap_spec: - to_unwrap_spec_element[el](orig_sig, new_sig) - + recipes[el](orig_sig, new_sig) return new_sig @@ -62,7 +63,6 @@ self.run_args = [] self.through_scope_w = 0 - def make_frame_class(self): setfastscope = self.setfastscope if not setfastscope: @@ -78,55 +78,33 @@ w_result = self.space.w_None return w_result """ % ','.join(self.run_args) in globals(),d - return type("BuiltinFrame_for_%s" % self.func.__name__, + return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) -def unwrap_spec_space(orig_sig, new_sig): +def unwrap_spec_check_space(orig_sig, new_sig): orig_sig.next() - # - new_sig.run_args.append('self.space') -def unwrap_spec_self(orig_sig, new_sig): +def unwrap_spec_check_self(orig_sig, new_sig): argname = orig_sig.next() new_sig.append(argname) - # - new_sig.setfastscope.append( - "self.arg_%s = self.space.unwrap_builtin(scope_w[%d])" % - (argname, new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.arg_%s" % argname) -def unwrap_spec_wrapped(orig_sig, new_sig): +def unwrap_spec_check_wrapped(orig_sig, new_sig): argname = orig_sig.next() assert argname.startswith('w_'), ( "argument %s of built-in function %r should " "start with 'w_'" % (argname, orig_sig.func)) new_sig.append(argname[2:]) - # - new_sig.setfastscope.append( - "self.arg_%s = scope_w[%d]" % (argname, new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.arg_%s" % argname) -def unwrap_spec_arguments(orig_sig, new_sig): +def unwrap_spec_check_arguments(orig_sig, new_sig): argname = orig_sig.next() assert new_sig.varargname is None,( "built-in function %r has conflicting rest args specs" % orig_sig.func) new_sig.varargname = 'args' new_sig.kwargname = 'keywords' - # - cur = new_sig.through_scope_w - next = cur+1 - new_sig.through_scope_w += 2 - new_sig.setfastscope.append( - "self.arg_%s = " - "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" - % (argname, cur, next)) - new_sig.run_args.append("self.arg_%s" % argname) -def unwrap_spec_starargs(orig_sig, new_sig): +def unwrap_spec_check_starargs(orig_sig, new_sig): varargname = orig_sig.varargname assert varargname.endswith('_w'), ( "argument *%s of built-in function %r should end in '_w'" % @@ -134,22 +112,73 @@ assert new_sig.varargname is None,( "built-in function %r has conflicting rest args specs" % orig_sig.func) new_sig.varargname = varargname[:-2] - # + +# recipes for checking interp2app func argumes wrt unwrap_spec +unwrap_spec_checks = { + ObjSpace: unwrap_spec_check_space, + 'self': unwrap_spec_check_self, + W_Root: unwrap_spec_check_wrapped, + Arguments: unwrap_spec_check_arguments, + '*': unwrap_spec_check_starargs, +} + +def unwrap_spec_emit_space(orig_sig, new_sig): + new_sig.run_args.append('self.space') + +def unwrap_spec_emit_self(orig_sig, new_sig): new_sig.setfastscope.append( - "self.arg_%s = self.space.unpacktuple(scope_w[%d])" % - (varargname, new_sig.through_scope_w)) + "self.self_arg = self.space.unwrap_builtin(scope_w[%d])" % + (new_sig.through_scope_w)) new_sig.through_scope_w += 1 - new_sig.run_args.append("*self.arg_%s" % varargname) + new_sig.run_args.append("self.self_arg") + +def unwrap_spec_emit_wrapped(orig_sig, new_sig): + cur = new_sig.through_scope_w + new_sig.setfastscope.append( + "self.w_arg%d = scope_w[%d]" % (cur,cur)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.w_arg%d" % cur) -to_unwrap_spec_element = { - ObjSpace: unwrap_spec_space, - 'self': unwrap_spec_self, - W_Root: unwrap_spec_wrapped, - Arguments: unwrap_spec_arguments, - '*': unwrap_spec_starargs, +def unwrap_spec_emit_arguments(orig_sig, new_sig): + cur = new_sig.through_scope_w + new_sig.through_scope_w += 2 + new_sig.setfastscope.append( + "self.arguments_arg = " + "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" + % (cur, cur+1)) + new_sig.run_args.append("self.arguments_arg") + +def unwrap_spec_emit_starargs(orig_sig, new_sig): + new_sig.setfastscope.append( + "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" % + (new_sig.through_scope_w)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("*self.starargs_arg_w") + +# recipes for emitting unwrapping code for arguments of a interp2app func +# wrt a unwrap_spec +unwrap_spec_emit = { + ObjSpace: unwrap_spec_emit_space, + 'self': unwrap_spec_emit_self, + W_Root: unwrap_spec_emit_wrapped, + Arguments: unwrap_spec_emit_arguments, + '*': unwrap_spec_emit_starargs, } +def make_builtin_frame_class_for_unwrap_spec(unwrap_spec, cache={}): + "NOT_RPYTHON" + key = tuple(unwrap_spec) + try: + return cache[key] + except KeyError: + emit_sig = apply_unwrap_spec(unwrap_spec, None, + BuiltinCodeSignature(name=repr(key)), + unwrap_spec_emit) + + cache[key] = cls = emit_sig.make_frame_class() + return cls + class BuiltinCode(eval.Code): "The code object implementing a built-in (interpreter-level) hook." @@ -164,15 +193,29 @@ eval.Code.__init__(self, func.__name__) self.func = func self.docstring = func.__doc__ - # signature-based hacks: renaming arguments from w_xyz to xyz. + # signature-based hacks if unwrap_spec is not specified: + # renaming arguments from w_xyz to xyz. # Currently we enforce the following signature tricks: # * the first arg must be either 'self' or 'space' # * 'w_' prefixes for the rest # * '_w' suffix for the optional '*' argument # * alternatively a final '__args__' means an Arguments() # Not exactly a clean approach XXX. + # -- + # unwrap_spec can be passed to interp2app or + # attached as an attribute to the function. + # It is a list of types or singleton objects: + # baseobjspace.ObjSpace is used to specify the space argument + # 'self' is used to specify a self method argument + # baseobjspace.W_Root is for wrapped arguments to keep wrapped + # argument.Arguments is for a final rest arguments Arguments object + # First extract the signature from the (CPython-level) code object argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) + + if unwrap_spec is None: + unwrap_spec = getattr(func,'unwrap_spec',None) + if unwrap_spec is None: unwrap_spec = [] @@ -209,14 +252,16 @@ if self.starargs: unwrap_spec.append('*') else: - assert ismethod is None,("if unwrap_spec is specified," - "ismethod is not expected") - assert spacearg is None,("if unwrap_spec is specified," - "spacearg is not expected") - - new_sig = parse_unwrap_spec(unwrap_spec, func, argnames, - varargname, kwargname, - BuiltinCodeSignature(func)) + assert not ismethod, ("if unwrap_spec is specified, " + "ismethod is not expected") + assert not spacearg, ("if unwrap_spec is specified, " + "spacearg is not expected") + + orig_sig = Signature(func, argnames, varargname, kwargname) + + new_sig = apply_unwrap_spec(unwrap_spec, orig_sig, + Signature(func), + unwrap_spec_checks) self.sig = argnames, varargname, kwargname = new_sig.signature() @@ -226,7 +271,7 @@ else: self.maxargs = self.minargs - self.framecls = new_sig.make_frame_class() + self.framecls = make_builtin_frame_class_for_unwrap_spec(unwrap_spec) def create_frame(self, space, w_globals, closure=None): return self.framecls(space, self, w_globals) @@ -245,33 +290,16 @@ # via the interface defined in eval.Frame. def setfastscope(self, scope_w): - pass -## argarray = list(scope_w) -## if self.code.generalargs: -## w_kwds = argarray.pop() -## w_args = argarray.pop() -## argarray.append(Arguments.frompacked(self.space, w_args, w_kwds)) -## elif self.code.starargs: -## w_args = argarray.pop() -## argarray += self.space.unpacktuple(w_args) -## if self.code.ismethod: -## argarray[0] = self.space.unwrap_builtin(argarray[0]) -## self.argarray = argarray + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" def getfastscope(self): raise OperationError(self.space.w_TypeError, self.space.wrap("cannot get fastscope of a BuiltinFrame")) def run(self): - pass -## argarray = self.argarray -## if self.code.spacearg: -## w_result = self.code.func(self.space, *argarray) -## else: -## w_result = self.code.func(*argarray) -## if w_result is None: -## w_result = self.space.w_None -## return w_result + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" class Gateway(Wrappable): From pedronis at codespeak.net Wed Jan 19 19:46:06 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 19 Jan 2005 19:46:06 +0100 (MET) Subject: [pypy-svn] r8422 - in pypy/branch/src-typedunwrap/pypy: interpreter interpreter/test module module/test objspace objspace/std Message-ID: <20050119184606.4F85827B5B@code1.codespeak.net> Author: pedronis Date: Wed Jan 19 19:46:05 2005 New Revision: 8422 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/interpreter/error.py pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/interpreter/main.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_interpreter.py pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py pypy/branch/src-typedunwrap/pypy/module/test/test_builtin.py pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: Removed unwrapdefault Added support for unwrap_spec elements: 'args_w' for unpacktuple applied rest arguments str,int,float: unwrap argument as such type Removed type unspecific unwrap everywhere possible under module/ Used unwrap_specs where meaningful (a few places), notice that as a result e.g. space.builtin.compile needs to be called with unwrapped arguments now Also now default arguments for interp2app gateways are also stored and passed around as wrapped values, the only exception is None which is left alone, this makes life easier in using unwrap_spec because eagerly unwrapping is then the right thing to do. [ If we weren't going through setfastscope and its scope_w argument, I can imagine alternative solutions were defaults are not wrapped, and that's not a issue. For now I think we can live in this new world with wrapped defaults also for interp2app gateways] Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Wed Jan 19 19:46:05 2005 @@ -123,12 +123,6 @@ def not_(self, w_obj): return self.wrap(not self.is_true(w_obj)) - def unwrapdefault(self, w_value, default): # xxx - if w_value is None or w_value == self.w_None: - return default - else: - return self.unwrap(w_value) - def newbool(self, b): if b: return self.w_True Modified: pypy/branch/src-typedunwrap/pypy/interpreter/error.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/error.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/error.py Wed Jan 19 19:46:05 2005 @@ -134,8 +134,7 @@ This lets OperationError.print_application_traceback() print the actual source line in the traceback.""" compile = space.builtin.compile - w = space.wrap - return compile(w(source), w('\n%s'%source), w(symbol), w(0), w(0)) + return compile(source, '\n%s'%source, symbol, 0, 0) class LinePrefixer: Modified: pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/extmodule.py Wed Jan 19 19:46:05 2005 @@ -13,6 +13,17 @@ from pypy.interpreter.function import Function from pypy.interpreter.module import Module +class interplevelimport_interp2app(gateway.interp2app): + + def __init__(self, f, w_globals): + "NOT_RPYTHON" + gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False) + self.w_globals = w_globals + + def getglobals(self, space): + "NOT_RPYTHON" + return self.w_globals + class BuiltinModule(Module): """A Module subclass specifically for built-in modules.""" @@ -141,10 +152,7 @@ name = space.str_w(w_name) if not hasattr(self, 'w_' + name): f = getattr(self, name) - code = gateway.BuiltinCode(f, ismethod=False, - spacearg=False) - defs_w = list(f.func_defaults or ()) - func = Function(space, code, self.w_dict, defs_w) + func = interplevelimport_interp2app(f, self.w_dict) w_result = space.wrap(func) else: w_result = getattr(self, 'w_' + name) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Wed Jan 19 19:46:05 2005 @@ -12,6 +12,7 @@ import types, sys +from pypy.tool import hack from pypy.interpreter.error import OperationError from pypy.interpreter import eval, pycode from pypy.interpreter.function import Function, Method @@ -67,7 +68,10 @@ setfastscope = self.setfastscope if not setfastscope: setfastscope = ["pass"] - setfastscope = ["def setfastscope(self, scope_w):"] + setfastscope + setfastscope = ["def setfastscope(self, scope_w):", + #"print 'ENTER',self.code.func.__name__", + #"print scope_w" + ] + setfastscope setfastscope = '\n '.join(setfastscope) d = {} exec setfastscope in globals(),d @@ -112,6 +116,15 @@ assert new_sig.varargname is None,( "built-in function %r has conflicting rest args specs" % orig_sig.func) new_sig.varargname = varargname[:-2] + +def unwrap_spec_check_args_w(orig_sig, new_sig): + argname = orig_sig.next() + assert argname.endswith('_w'), ( + "rest arguments arg %s of built-in function %r should end in '_w'" % + (argname, orig_sig.func)) + assert new_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + new_sig.varargname = argname[:-2] # recipes for checking interp2app func argumes wrt unwrap_spec unwrap_spec_checks = { @@ -120,6 +133,7 @@ W_Root: unwrap_spec_check_wrapped, Arguments: unwrap_spec_check_arguments, '*': unwrap_spec_check_starargs, + 'args_w': unwrap_spec_check_args_w, } def unwrap_spec_emit_space(orig_sig, new_sig): @@ -132,7 +146,6 @@ new_sig.through_scope_w += 1 new_sig.run_args.append("self.self_arg") - def unwrap_spec_emit_wrapped(orig_sig, new_sig): cur = new_sig.through_scope_w new_sig.setfastscope.append( @@ -140,6 +153,7 @@ new_sig.through_scope_w += 1 new_sig.run_args.append("self.w_arg%d" % cur) + def unwrap_spec_emit_arguments(orig_sig, new_sig): cur = new_sig.through_scope_w new_sig.through_scope_w += 2 @@ -155,6 +169,13 @@ (new_sig.through_scope_w)) new_sig.through_scope_w += 1 new_sig.run_args.append("*self.starargs_arg_w") + +def unwrap_spec_emit_args_w(orig_sig, new_sig): + new_sig.setfastscope.append( + "self.args_w = self.space.unpacktuple(scope_w[%d])" % + (new_sig.through_scope_w)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.args_w") # recipes for emitting unwrapping code for arguments of a interp2app func # wrt a unwrap_spec @@ -164,8 +185,32 @@ W_Root: unwrap_spec_emit_wrapped, Arguments: unwrap_spec_emit_arguments, '*': unwrap_spec_emit_starargs, + 'args_w': unwrap_spec_emit_args_w, } +# unwrap_space_check/emit for str,int,float +for basic_type in [str,int,float]: + name = basic_type.__name__ + def unwrap_spec_check_basic(orig_sig, new_sig, name=name): + argname = orig_sig.next() + assert not argname.startswith('w_'), ( + "unwrapped %s argument %s of built-in function %r should " + "not start with 'w_'" % (name, argname, orig_sig.func)) + new_sig.append(argname) + def unwrap_spec_emit_basic(orig_sig, new_sig, name=name): + cur = new_sig.through_scope_w + new_sig.setfastscope.append( + "self.%s_arg%d = self.space.%s_w(scope_w[%d])" % + (name,cur,name,cur)) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.%s_arg%d" % (name,cur)) + unwrap_spec_checks[basic_type] = hack.func_with_new_name( + unwrap_spec_check_basic, "unwrap_spec_check_%s" % name) + unwrap_spec_emit[basic_type] = hack.func_with_new_name( + unwrap_spec_emit_basic, "unwrap_spec_emit_%s" % name) + + + def make_builtin_frame_class_for_unwrap_spec(unwrap_spec, cache={}): "NOT_RPYTHON" key = tuple(unwrap_spec) @@ -205,10 +250,12 @@ # unwrap_spec can be passed to interp2app or # attached as an attribute to the function. # It is a list of types or singleton objects: - # baseobjspace.ObjSpace is used to specify the space argument + # baseobjspace.ObjSpace is used to specify the space argument # 'self' is used to specify a self method argument # baseobjspace.W_Root is for wrapped arguments to keep wrapped # argument.Arguments is for a final rest arguments Arguments object + # 'args_w' for unpacktuple applied rest arguments + # str,int,float: unwrap argument as such type # First extract the signature from the (CPython-level) code object argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) @@ -266,7 +313,7 @@ self.sig = argnames, varargname, kwargname = new_sig.signature() self.minargs = len(argnames) - if self.starargs: + if varargname: self.maxargs = sys.maxint else: self.maxargs = self.minargs @@ -336,15 +383,8 @@ Gateway.build_all_functions, self.getcache(space)) - def build_all_functions(self, space): + def getglobals(self, space): "NOT_RPYTHON" - # the construction is supposed to be done only once in advance, - # but must be done lazily when needed only, because - # 1) it depends on the object space - # 2) the w_globals must not be built before the underlying - # _staticglobals is completely initialized, because - # w_globals must be built only once for all the Gateway - # instances of _staticglobals if self._staticglobals is None: w_globals = None else: @@ -361,7 +401,18 @@ else: # no, we build all Gateways in the _staticglobals now. w_globals = build_dict(self._staticglobals, space) - return self._build_function(space, w_globals) + return w_globals + + def build_all_functions(self, space): + "NOT_RPYTHON" + # the construction is supposed to be done only once in advance, + # but must be done lazily when needed only, because + # 1) it depends on the object space + # 2) the w_globals must not be built before the underlying + # _staticglobals is completely initialized, because + # w_globals must be built only once for all the Gateway + # instances of _staticglobals + return self._build_function(space, self.getglobals(space)) def getcache(self, space): return space._gatewaycache @@ -439,7 +490,18 @@ class interp2app(Gateway): """Build a Gateway that calls 'f' at interp-level.""" - def __init__(self, f, app_name=None): + + # NOTICE even interp2app defaults are stored and passed as + # wrapped values, this to avoid having scope_w be of mixed + # wrapped and unwrapped types, + # an exception is made for None which is passed around as default + # as an unwrapped None, unwrapped None and wrapped types are + # compatible + # + # Takes optionally an unwrap_spec, see BuiltinCode + + def __init__(self, f, app_name=None, + ismethod=None, spacearg=None, unwrap_spec = None): "NOT_RPYTHON" Gateway.__init__(self) # f must be a function whose name does NOT starts with 'app_' @@ -450,9 +512,13 @@ raise ValueError, ("function name %r suspiciously starts " "with 'app_'" % f.func_name) app_name = f.func_name - self._code = BuiltinCode(f) + self._code = BuiltinCode(f, ismethod=ismethod, + spacearg=spacearg, + unwrap_spec=unwrap_spec) self.name = app_name self._staticdefs = list(f.func_defaults or ()) + #if self._staticdefs: + # print f.__module__,f.__name__,"HAS NON TRIVIAL DEFLS",self._staticdefs self._staticglobals = None def getcode(self, space): @@ -460,7 +526,13 @@ def getdefaults(self, space): "NOT_RPYTHON" - return self._staticdefs + defs_w = [] + for val in self._staticdefs: + if val is None: + defs_w.append(val) + else: + defs_w.append(space.wrap(val)) + return defs_w def get_method(self, obj): assert self._code.ismethod, ( Modified: pypy/branch/src-typedunwrap/pypy/interpreter/main.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/main.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/main.py Wed Jan 19 19:46:05 2005 @@ -17,8 +17,7 @@ compile = space.builtin.compile w = space.wrap - w_code = compile(w(source), w(filename), w(cmd), - w(0), w(0)) + w_code = compile(source, filename, cmd, 0, 0) ec = executioncontext.ExecutionContext(space) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_interpreter.py Wed Jan 19 19:46:05 2005 @@ -12,7 +12,7 @@ compile = space.builtin.compile w = space.wrap - w_code = compile(w(source), w(''), w('exec'), w(0), w(0)) + w_code = compile(source, '', 'exec', 0, 0) ec = executioncontext.ExecutionContext(space) Modified: pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py (original) +++ pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py Wed Jan 19 19:46:05 2005 @@ -4,7 +4,7 @@ from pypy.interpreter.module import Module from pypy.interpreter.pycode import PyCode from pypy.interpreter.error import OperationError -_noarg = object() +from pypy.interpreter.baseobjspace import BaseWrappable, W_Root import __builtin__ as cpy_builtin @@ -21,13 +21,15 @@ def locals(): return _actframe().getdictscope() -def _caller_globals(w_index=None): - position = space.unwrapdefault(w_index, 1) +def _caller_globals(position=1): return _actframe(position).w_globals +# +_caller_globals.unwrap_spec = [int] -def _caller_locals(w_index=None): - position = space.unwrapdefault(w_index, 1) +def _caller_locals(position=1): return _actframe(position).getdictscope() +# +_caller_locals.unwrap_spec = [int] def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None): @@ -78,9 +80,8 @@ il_len = len -def __import__(w_modulename, w_globals=None, +def __import__(modulename, w_globals=None, w_locals=None, w_fromlist=None): - modulename = space.unwrap(w_modulename) if not isinstance(modulename, str): try: helper = ', not ' + modulename.__class__.__name__ @@ -100,13 +101,13 @@ rel_modulename = None if ctxt_w_name is not None: - ctxt_name_prefix_parts = space.unwrap(ctxt_w_name).split('.') + ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.') if ctxt_w_path is None: # context is a plain module ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1] if ctxt_name_prefix_parts: rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename]) else: # context is a package module - rel_modulename = space.unwrap(ctxt_w_name)+'.'+modulename + rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename if rel_modulename is not None: w_mod = check_sys_modules(w(rel_modulename)) if (w_mod is None or @@ -124,6 +125,8 @@ if rel_modulename is not None: space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) return w_mod +# +__import__.unwrap_spec = [str,W_Root,W_Root,W_Root] def absolute_import(modulename, baselevel, w_fromlist, tentative): w = space.wrap @@ -153,7 +156,7 @@ if w_fromlist is not None and space.is_true(w_fromlist): if w_path is not None: for w_name in space.unpackiterable(w_fromlist): - load_part(w_path, prefix, space.unwrap(w_name), w_mod, + load_part(w_path, prefix, space.str_w(w_name), w_mod, tentative=1) return w_mod else: @@ -173,14 +176,14 @@ return w_mod import os for path in space.unpackiterable(w_path): - dir = os.path.join(space.unwrap(path), partname) + dir = os.path.join(space.str_w(path), partname) if os.path.isdir(dir): f = os.path.join(dir,'__init__.py') w_mod = try_import_mod(w_modulename, f, w_parent, w(partname), pkgdir=dir) if w_mod is not None: return w_mod - f = os.path.join(space.unwrap(path), partname + '.py') + f = os.path.join(space.str_w(path), partname + '.py') w_mod = try_import_mod(w_modulename, f, w_parent, w(partname)) if w_mod is not None: return w_mod @@ -194,14 +197,8 @@ raise OperationError(space.w_ImportError, w_exc) -def compile(w_str, w_filename, w_startstr, - w_supplied_flags=None, w_dont_inherit=None): - str_ = space.unwrap(w_str) - filename = space.unwrap(w_filename) - startstr = space.unwrap(w_startstr) - supplied_flags = space.unwrapdefault(w_supplied_flags, 0) - dont_inherit = space.unwrapdefault(w_dont_inherit, 0) - +def compile(str_, filename, startstr, + supplied_flags=0, dont_inherit=0): #print (str_, filename, startstr, supplied_flags, dont_inherit) # XXX we additionally allow GENERATORS because compiling some builtins # requires it. doesn't feel quite right to do that here. @@ -217,13 +214,16 @@ except TypeError,e: raise OperationError(space.w_TypeError,space.wrap(str(e))) return space.wrap(PyCode(space)._from_code(c)) +# +compile.unwrap_spec = [str,str,str,int,int] + def eval(w_source, w_globals=None, w_locals=None): w = space.wrap if space.is_true(space.isinstance(w_source, space.w_str)): - w_codeobj = compile(w_source, w(""), w("eval")) - elif isinstance(space.unwrap(w_source), PyCode): + w_codeobj = compile(space.str_w(w_source), "", "eval") + elif space.is_true(space.isinstance(w_source, space.gettypeobject(PyCode.typedef))): w_codeobj = w_source else: raise OperationError(space.w_TypeError, @@ -235,7 +235,7 @@ elif w_locals is None: w_locals = w_globals - return space.unwrap(w_codeobj).exec_code(space, w_globals, w_locals) + return space.unwrap_builtin(w_codeobj).exec_code(space, w_globals, w_locals) def abs(w_val): "abs(number) -> number\n\nReturn the absolute value of the argument." @@ -252,12 +252,12 @@ space.delattr(w_object, w_name) return space.w_None -def getattr(w_object, w_name, w_defvalue = _noarg): +def getattr(w_object, w_name, w_defvalue=None): try: return space.getattr(w_object, w_name) except OperationError, e: if e.match(space, space.w_AttributeError): - if w_defvalue is not _noarg: + if w_defvalue is not None: return w_defvalue raise @@ -284,13 +284,13 @@ def _issubtype(w_cls1, w_cls2): return space.issubtype(w_cls1, w_cls2) -def iter(w_collection_or_callable, w_sentinel = _noarg): - if w_sentinel is _noarg: +def iter(w_collection_or_callable, w_sentinel=None): + if w_sentinel is None: return space.iter(w_collection_or_callable) else: if not space.is_true(callable(w_collection_or_callable)): raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): v must be callable')) + space.wrap('iter(v, w): w must be callable')) return _iter_generator(w_collection_or_callable, w_sentinel) def ord(w_val): Modified: pypy/branch/src-typedunwrap/pypy/module/test/test_builtin.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/module/test/test_builtin.py (original) +++ pypy/branch/src-typedunwrap/pypy/module/test/test_builtin.py Wed Jan 19 19:46:05 2005 @@ -228,6 +228,9 @@ raises(TypeError, hash, []) raises(TypeError, hash, {}) + def test_eval(self): + assert eval("1+2") == 3 + def test_compile(self): co = compile('1+2', '?', 'eval') assert eval(co) == 3 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/fake.py Wed Jan 19 19:46:05 2005 @@ -1,4 +1,5 @@ from pypy.interpreter.error import OperationError +from pypy.interpreter import baseobjspace from pypy.interpreter import eval from pypy.interpreter.function import Function from pypy.objspace.std.stdtypedef import * @@ -43,14 +44,18 @@ for s, v in cpy_type.__dict__.items(): if cpy_type is not unicode or s not in ['__add__', '__contains__']: kw[s] = v - def fake__new__(space, w_type, *args_w): + def fake__new__(space, w_type, args_w): args = [space.unwrap(w_arg) for w_arg in args_w] try: r = cpy_type.__new__(cpy_type, *args) except: wrap_exception(space) return W_Fake(space, r) - kw['__new__'] = gateway.interp2app(fake__new__) + + kw['__new__'] = gateway.interp2app(fake__new__, + unwrap_spec = [baseobjspace.ObjSpace, + baseobjspace.W_Root, + 'args_w']) if cpy_type.__base__ is not object: assert cpy_type.__base__ is basestring from pypy.objspace.std.basestringtype import basestring_typedef Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/slicetype.py Wed Jan 19 19:46:05 2005 @@ -1,3 +1,4 @@ +from pypy.interpreter import baseobjspace from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.register_all import register_all from pypy.interpreter.error import OperationError @@ -80,7 +81,7 @@ # ____________________________________________________________ -def descr__new__(space, w_slicetype, *args_w): +def descr__new__(space, w_slicetype, args_w): from pypy.objspace.std.sliceobject import W_SliceObject w_start = space.w_None w_stop = space.w_None @@ -100,6 +101,9 @@ w_obj = space.allocate_instance(W_SliceObject, w_slicetype) w_obj.__init__(space, w_start, w_stop, w_step) return w_obj +# +descr__new__.unwrap_spec = [baseobjspace.ObjSpace, baseobjspace.W_Root, + 'args_w'] # ____________________________________________________________ Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Wed Jan 19 19:46:05 2005 @@ -155,7 +155,7 @@ def str_w(self, w): if type(w) is not str: raise OperationError(self.w_TypeError, - sefl.wrap("expected string")) + self.wrap("expected string")) return w def float_w(self, w): @@ -240,6 +240,8 @@ typedef.trivialwrapperclass = cls return cls + gettypeobject = hackwrapperclass + def is_(self, w_obj1, w_obj2): return self.unwrap(w_obj1) is self.unwrap(w_obj2) From pedronis at codespeak.net Wed Jan 19 19:51:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 19 Jan 2005 19:51:15 +0100 (MET) Subject: [pypy-svn] r8423 - in pypy/branch/src-typedunwrap/pypy: interpreter objspace Message-ID: <20050119185115.1934B27B5C@code1.codespeak.net> Author: pedronis Date: Wed Jan 19 19:51:14 2005 New Revision: 8423 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: typos Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Wed Jan 19 19:51:14 2005 @@ -188,7 +188,7 @@ 'args_w': unwrap_spec_emit_args_w, } -# unwrap_space_check/emit for str,int,float +# unwrap_spec_check/emit for str,int,float for basic_type in [str,int,float]: name = basic_type.__name__ def unwrap_spec_check_basic(orig_sig, new_sig, name=name): Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Wed Jan 19 19:51:14 2005 @@ -147,10 +147,10 @@ if -sys.maxint-1 <= w <= sys.maxint: return w raise OperationError(self.w_OverflowError, - sefl.wrap("long int too large to convert to int")) + self.wrap("long int too large to convert to int")) raise OperationError(self.w_TypeError, - sefl.wrap("expected integer")) + self.wrap("expected integer")) def str_w(self, w): if type(w) is not str: @@ -161,7 +161,7 @@ def float_w(self, w): if type(w) is not float: raise OperationError(self.w_TypeError, - sefl.wrap("expected float")) + self.wrap("expected float")) return w def unwrap(self, w): From pedronis at codespeak.net Wed Jan 19 20:34:37 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 19 Jan 2005 20:34:37 +0100 (MET) Subject: [pypy-svn] r8426 - in pypy/branch/src-typedunwrap/pypy: interpreter/test objspace Message-ID: <20050119193437.6561F27B62@code1.codespeak.net> Author: pedronis Date: Wed Jan 19 20:34:37 2005 New Revision: 8426 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: some tests (and relative fixes in trivial) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py Wed Jan 19 20:34:37 2005 @@ -77,6 +77,115 @@ self.space.eq_w( space.call_function(w_app_g3, w('foo'), w('bar')), w('foobar')) + + def test_interp2app_unwrap_spec(self): + space = self.space + w = space.wrap + def g3(space, w_a, w_b): + return space.add(w_a, w_b) + app_g3 = gateway.interp2app_temp(g3, + unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root]) + w_app_g3 = space.wrap(app_g3) + self.space.eq_w( + space.call(w_app_g3, + space.newtuple([w('foo'), w('bar')]), + space.newdict([])), + w('foobar')) + self.space.eq_w( + space.call_function(w_app_g3, w('foo'), w('bar')), + w('foobar')) + + def test_interp2app_unwrap_spec_args_w(self): + space = self.space + w = space.wrap + def g3_args_w(space, args_w): + return space.add(args_w[0], args_w[1]) + app_g3_args_w = gateway.interp2app_temp(g3_args_w, + unwrap_spec=[gateway.ObjSpace, + 'args_w']) + w_app_g3_args_w = space.wrap(app_g3_args_w) + self.space.eq_w( + space.call(w_app_g3_args_w, + space.newtuple([w('foo'), w('bar')]), + space.newdict([])), + w('foobar')) + self.space.eq_w( + space.call_function(w_app_g3_args_w, w('foo'), w('bar')), + w('foobar')) + + def test_interp2app_unwrap_spec_str(self): + space = self.space + w = space.wrap + def g3_ss(space, s0, s1): + return space.wrap(s0+s1) + app_g3_ss = gateway.interp2app_temp(g3_ss, + unwrap_spec=[gateway.ObjSpace, + str,str]) + w_app_g3_ss = space.wrap(app_g3_ss) + self.space.eq_w( + space.call(w_app_g3_ss, + space.newtuple([w('foo'), w('bar')]), + space.newdict([])), + w('foobar')) + self.space.eq_w( + space.call_function(w_app_g3_ss, w('foo'), w('bar')), + w('foobar')) + + def test_interp2app_unwrap_spec_int_float(self): + space = self.space + w = space.wrap + def g3_if(space, i0, f1): + return space.wrap(i0+f1) + app_g3_if = gateway.interp2app_temp(g3_if, + unwrap_spec=[gateway.ObjSpace, + int,float]) + w_app_g3_if = space.wrap(app_g3_if) + self.space.eq_w( + space.call(w_app_g3_if, + space.newtuple([w(1), w(1.0)]), + space.newdict([])), + w(2.0)) + self.space.eq_w( + space.call_function(w_app_g3_if, w(1), w(2.0)), + w(2.0)) + + def test_interp2app_unwrap_spec_typechecks(self): + space = self.space + w = space.wrap + def g3_id(space, x): + return space.wrap(x) + app_g3_i = gateway.interp2app_temp(g3_id, + unwrap_spec=[gateway.ObjSpace, + int]) + w_app_g3_i = space.wrap(app_g3_i) + space.eq_w(space.call_function(w_app_g3_i,w(1)),w(1)) + space.eq_w(space.call_function(w_app_g3_i,w(1L)),w(1)) + raises(gateway.OperationError,space.call_function,w_app_g3_i,w(2**32)) + raises(gateway.OperationError,space.call_function,w_app_g3_i,w(None)) + raises(gateway.OperationError,space.call_function,w_app_g3_i,w("foo")) + raises(gateway.OperationError,space.call_function,w_app_g3_i,w(1.0)) + + app_g3_s = gateway.interp2app_temp(g3_id, + unwrap_spec=[gateway.ObjSpace, + str]) + w_app_g3_s = space.wrap(app_g3_s) + space.eq_w(space.call_function(w_app_g3_s,w("foo")),w("foo")) + raises(gateway.OperationError,space.call_function,w_app_g3_s,w(None)) + raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1)) + raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1.0)) + + app_g3_f = gateway.interp2app_temp(g3_id, + unwrap_spec=[gateway.ObjSpace, + float]) + w_app_g3_f = space.wrap(app_g3_f) + space.eq_w(space.call_function(w_app_g3_f,w(1.0)),w(1.0)) + space.eq_w(space.call_function(w_app_g3_f,w(1)),w(1.0)) + space.eq_w(space.call_function(w_app_g3_f,w(1L)),w(1.0)) + raises(gateway.OperationError,space.call_function,w_app_g3_f,w(None)) + raises(gateway.OperationError,space.call_function,w_app_g3_f,w("foo")) + def test_importall(self): w = self.space.wrap Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Wed Jan 19 20:34:37 2005 @@ -145,7 +145,7 @@ return w if type(w) is long: if -sys.maxint-1 <= w <= sys.maxint: - return w + return int(w) raise OperationError(self.w_OverflowError, self.wrap("long int too large to convert to int")) @@ -159,10 +159,10 @@ return w def float_w(self, w): - if type(w) is not float: + if type(w) not in (int,long,float): raise OperationError(self.w_TypeError, self.wrap("expected float")) - return w + return float(w) def unwrap(self, w): if isinstance(w, CPyWrapper): From pedronis at codespeak.net Thu Jan 20 13:19:20 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 20 Jan 2005 13:19:20 +0100 (MET) Subject: [pypy-svn] r8438 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050120121920.A554F27B75@code1.codespeak.net> Author: pedronis Date: Thu Jan 20 13:19:20 2005 New Revision: 8438 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/default.py Log: better error msgs for str_w,int_w and float_w Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/default.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/default.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/default.py Thu Jan 20 13:19:20 2005 @@ -219,17 +219,22 @@ class UnwrapError(Exception): pass +def typed_unwrap_error_msg(space, expected, w_obj): + w = space.wrap + type_name = space.str_w(space.getattr(space.type(w_obj),w("__name__"))) + return w("expected %s, got %s object" % (expected, type_name)) + def int_w__ANY(space,w_obj): raise OperationError(space.w_TypeError, - space.wrap("expected integer")) + typed_unwrap_error_msg(space, "integer", w_obj)) def str_w__ANY(space,w_obj): raise OperationError(space.w_TypeError, - space.wrap("expected str")) + typed_unwrap_error_msg(space, "string", w_obj)) def float_w__ANY(space,w_obj): raise OperationError(space.w_TypeError, - space.wrap("expected float")) + typed_unwrap_error_msg(space, "float", w_obj)) def unwrap__ANY(space, w_obj): if isinstance(w_obj, BaseWrappable): From pedronis at codespeak.net Thu Jan 20 15:31:42 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 20 Jan 2005 15:31:42 +0100 (MET) Subject: [pypy-svn] r8439 - in pypy/branch/src-typedunwrap/pypy: interpreter module objspace objspace/flow objspace/std Message-ID: <20050120143142.B71F127B66@code1.codespeak.net> Author: pedronis Date: Thu Jan 20 15:31:42 2005 New Revision: 8439 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/interpreter/eval.py pypy/branch/src-typedunwrap/pypy/interpreter/function.py pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py pypy/branch/src-typedunwrap/pypy/interpreter/main.py pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py pypy/branch/src-typedunwrap/pypy/objspace/trace.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: renamed unwrap_builtin to interpclass_w(w_obj), clarified the semantics thus: If w_obj is a wrapped internal interpreter class instance unwrap to it, otherwise this is the identity added ObjSpace.IrregularOpTable to help keeping the trace object space in sync Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Thu Jan 20 15:31:42 2005 @@ -129,6 +129,13 @@ else: return self.w_False + def interpclass_w(space, w_obj): + """ + If w_obj is a wrapped internal interpreter class instance unwrap to it, + otherwise this is the identity + """ + return w_obj # hook for hack by TrivialObjSpace + def unpackiterable(self, w_iterable, expected_length=None): """Unpack an iterable object into a real (interpreter-level) list. Raise a real ValueError if the length is wrong.""" @@ -354,15 +361,32 @@ ## Irregular part of the interface: # -# wrap(x) -> w_x -# str_w(w_str) -> str -# int_w(w_ival or w_long_ival) -> ival -# float_w(w_floatval) -> floatval -# unwrap(w_x) -> x -# is_true(w_x) -> True or False -# newtuple([w_1, w_2,...]) -> w_tuple -# newlist([w_1, w_2,...]) -> w_list -# newstring([w_1, w_2,...]) -> w_string from ascii numbers (bytes) -# newdict([(w_key,w_value),...]) -> w_dict -#newslice(w_start,w_stop,w_step) -> w_slice (any argument may be a real None) -# call_args(w_obj,Arguments()) -> w_result +# wrap(x) -> w_x +# str_w(w_str) -> str +# int_w(w_ival or w_long_ival) -> ival +# float_w(w_floatval) -> floatval +#interpclass_w(w_interpclass_inst or w_obj) -> interpclass_inst|w_obj +# unwrap(w_x) -> x +# is_true(w_x) -> True or False +# newtuple([w_1, w_2,...]) -> w_tuple +# newlist([w_1, w_2,...]) -> w_list +# newstring([w_1, w_2,...]) -> w_string from ascii numbers (bytes) +# newdict([(w_key,w_value),...]) -> w_dict +# newslice(w_start,w_stop,w_step) -> w_slice (any argument may be a real None) +# call_args(w_obj,Arguments()) -> w_result + +ObjSpace.IrregularOpTable = [ + 'wrap', + 'str_w', + 'int_w', + 'float_w', + 'interpclass_w', + 'unwrap', + 'is_true', + 'newtuple', + 'newlist', + 'newdict', + 'newslice', + 'call_args' + ] + Modified: pypy/branch/src-typedunwrap/pypy/interpreter/eval.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/eval.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/eval.py Thu Jan 20 15:31:42 2005 @@ -91,7 +91,7 @@ return self.w_locals def fget_getdictscope(space, w_self): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) return self.getdictscope() def setdictscope(self, w_locals): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/function.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/function.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/function.py Thu Jan 20 15:31:42 2005 @@ -60,24 +60,24 @@ return self.call_args(__args__) def fget_func_defaults(space, w_self): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) values_w = self.defs_w if not values_w: return space.w_None return space.newtuple(values_w) def fget_func_doc(space, w_self): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) if self.w_doc is None: self.w_doc = space.wrap(self.code.getdocstring()) return self.w_doc def fset_func_doc(space, w_self, w_doc): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) self.w_doc = w_doc def fdel_func_doc(space, w_self): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) self.w_doc = space.w_None class Method(Wrappable): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/gateway.py Thu Jan 20 15:31:42 2005 @@ -141,7 +141,7 @@ def unwrap_spec_emit_self(orig_sig, new_sig): new_sig.setfastscope.append( - "self.self_arg = self.space.unwrap_builtin(scope_w[%d])" % + "self.self_arg = self.space.interpclass_w(scope_w[%d])" % (new_sig.through_scope_w)) new_sig.through_scope_w += 1 new_sig.run_args.append("self.self_arg") Modified: pypy/branch/src-typedunwrap/pypy/interpreter/main.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/main.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/main.py Thu Jan 20 15:31:42 2005 @@ -24,7 +24,7 @@ mainmodule = module.Module(space, space.wrap("__main__")) w_globals = mainmodule.w_dict - pycode = space.unwrap_builtin(w_code) + pycode = space.interpclass_w(w_code) retval = pycode.exec_code(space, w_globals, w_globals) if eval: return retval Modified: pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/nestedscope.py Thu Jan 20 15:31:42 2005 @@ -165,10 +165,10 @@ def MAKE_CLOSURE(f, numdefaults): w_codeobj = f.valuestack.pop() - codeobj = f.space.unwrap_builtin(w_codeobj) + codeobj = f.space.interpclass_w(w_codeobj) assert isinstance(codeobj, pycode.PyCode) nfreevars = len(codeobj.co_freevars) - freevars = [f.space.unwrap_builtin(f.valuestack.pop()) for i in range(nfreevars)] + freevars = [f.space.interpclass_w(f.valuestack.pop()) for i in range(nfreevars)] freevars.reverse() defaultarguments = [f.valuestack.pop() for i in range(numdefaults)] defaultarguments.reverse() Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pycode.py Thu Jan 20 15:31:42 2005 @@ -151,7 +151,7 @@ return dis.findlabels(self.co_code) def fget_co_consts(space, w_self): - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) return space.newtuple(self.co_consts_w) def descr_code__new__(space, w_subtype, Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyframe.py Thu Jan 20 15:31:42 2005 @@ -99,7 +99,7 @@ def fget_f_lineno(space, w_self): "Returns the line number of the instruction currently being executed." - self = space.unwrap_builtin(w_self) + self = space.interpclass_w(w_self) return space.wrap(self.get_last_lineno()) def get_last_lineno(self): Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py Thu Jan 20 15:31:42 2005 @@ -321,7 +321,7 @@ w_traceback) w_type, w_value, w_traceback = f.space.unpacktuple(w_resulttuple, 3) if w_traceback is not f.space.w_None: - tb = f.space.unwrap_builtin(w_traceback) + tb = f.space.interpclass_w(w_traceback) if not isinstance(tb,pytraceback.PyTraceback): raise OperationError(f.space.w_TypeError, f.space.wrap("raise: arg 3 must be a traceback or None")) @@ -349,7 +349,7 @@ plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) if plain: w_locals = f.getdictscope() - pycode = f.space.unwrap_builtin(w_prog) + pycode = f.space.interpclass_w(w_prog) pycode.exec_code(f.space, w_globals, w_locals) if plain: f.setdictscope(w_locals) @@ -411,7 +411,7 @@ w_unroller = f.valuestack.pop() if w_unroller is not f.space.w_None: # re-raise the unroller, if any - raise f.space.unwrap_builtin(w_unroller) + raise f.space.interpclass_w(w_unroller) def BUILD_CLASS(f): w_methodsdict = f.valuestack.pop() @@ -723,7 +723,7 @@ def MAKE_FUNCTION(f, numdefaults): w_codeobj = f.valuestack.pop() - codeobj = f.space.unwrap_builtin(w_codeobj) + codeobj = f.space.interpclass_w(w_codeobj) defaultarguments = [f.valuestack.pop() for i in range(numdefaults)] defaultarguments.reverse() fn = function.Function(f.space, codeobj, f.w_globals, defaultarguments) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py Thu Jan 20 15:31:42 2005 @@ -87,17 +87,17 @@ #print w_property, w_obj, w_cls return w_property else: - return space.unwrap_builtin(w_property).fget(space, w_obj) + return space.interpclass_w(w_property).fget(space, w_obj) def descr_property_set(space, w_property, w_obj, w_value): - fset = space.unwrap_builtin(w_property).fset + fset = space.interpclass_w(w_property).fset if fset is None: raise OperationError(space.w_AttributeError, space.wrap("read-only attribute")) fset(space, w_obj, w_value) def descr_property_del(space, w_property, w_obj): - fdel = space.unwrap_builtin(w_property).fdel + fdel = space.interpclass_w(w_property).fdel if fdel is None: raise OperationError(space.w_AttributeError, space.wrap("cannot delete attribute")) @@ -112,14 +112,14 @@ def attrproperty(name): "NOT_RPYTHON: initialization-time only" def fget(space, w_obj): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) return space.wrap(getattr(obj, name)) return GetSetProperty(fget) def attrproperty_w(name): "NOT_RPYTHON: initialization-time only" def fget(space, w_obj): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) w_value = getattr(obj, name) if w_value is None: return space.w_None @@ -143,13 +143,13 @@ from pypy.interpreter.special import NotImplemented, Ellipsis def descr_get_dict(space, w_obj): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) w_dict = obj.getdict() assert w_dict is not None, repr(obj) return w_dict def descr_set_dict(space, w_obj, w_dict): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) obj.setdict(w_dict) default_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) @@ -157,16 +157,16 @@ # co_xxx interface emulation for built-in code objects def fget_co_varnames(space, w_code): - code = space.unwrap_builtin(w_code) + code = space.interpclass_w(w_code) return space.newtuple([space.wrap(name) for name in code.getvarnames()]) def fget_co_argcount(space, w_code): - code = space.unwrap_builtin(w_code) + code = space.interpclass_w(w_code) argnames, varargname, kwargname = code.signature() return space.wrap(len(argnames)) def fget_co_flags(space, w_code): - code = space.unwrap_builtin(w_code) + code = space.interpclass_w(w_code) argnames, varargname, kwargname = code.signature() flags = 0 if varargname is not None: flags |= CO_VARARGS @@ -174,7 +174,7 @@ return space.wrap(flags) def fget_co_consts(space, w_code): - code = space.unwrap_builtin(w_code) + code = space.interpclass_w(w_code) w_docstring = space.wrap(code.getdocstring()) return space.newtuple([w_docstring]) Modified: pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py (original) +++ pypy/branch/src-typedunwrap/pypy/module/__builtin__interp.py Thu Jan 20 15:31:42 2005 @@ -223,7 +223,7 @@ if space.is_true(space.isinstance(w_source, space.w_str)): w_codeobj = compile(space.str_w(w_source), "", "eval") - elif space.is_true(space.isinstance(w_source, space.gettypeobject(PyCode.typedef))): + elif isinstance(space.interpclass_w(w_source), PyCode): w_codeobj = w_source else: raise OperationError(space.w_TypeError, @@ -235,7 +235,7 @@ elif w_locals is None: w_locals = w_globals - return space.unwrap_builtin(w_codeobj).exec_code(space, w_globals, w_locals) + return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) def abs(w_val): "abs(number) -> number\n\nReturn the absolute value of the argument." Modified: pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/descroperation.py Thu Jan 20 15:31:42 2005 @@ -1,6 +1,6 @@ import operator from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import ObjSpace,W_Root +from pypy.interpreter.baseobjspace import ObjSpace, W_Root, BaseWrappable from pypy.interpreter.function import Function from pypy.interpreter.gateway import BuiltinCode from pypy.interpreter.argument import Arguments @@ -61,7 +61,7 @@ return space.lookup(w_obj, '__set__') is not None def get_and_call_args(space, w_descr, w_obj, args): - descr = space.unwrap_builtin(w_descr) + descr = space.interpclass_w(w_descr) # a special case for performance and to avoid infinite recursion if isinstance(descr, Function): return descr.call_args(args.prepend(w_obj)) @@ -73,11 +73,6 @@ args = Arguments(space, list(args_w)) return space.get_and_call_args(w_descr, w_obj, args) - def unwrap_builtin(space, w_obj): - if not isinstance(w_obj, W_Root): - raise TypeError,"cannot unwrap_builtin: " + repr(w_obj) - return w_obj # hook for hack by TrivialObjSpace - def call_args(space, w_obj, args): # a special case for performance if type(w_obj) is Function: Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Thu Jan 20 15:31:42 2005 @@ -131,7 +131,7 @@ else: raise TypeError("not wrapped: " + repr(w_obj)) - unwrap_builtin = unwrap + interpclass_w = unwrap def getexecutioncontext(self): return self.executioncontext Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py Thu Jan 20 15:31:42 2005 @@ -2,7 +2,7 @@ from pypy.interpreter.typedef import GetSetProperty def descr_get_dictproxy(space, w_obj): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) return W_DictProxyObject(space, obj.getdict()) dictproxy_descr = GetSetProperty(descr_get_dictproxy) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py Thu Jan 20 15:31:42 2005 @@ -6,7 +6,7 @@ def proxymethod(name): def fget(space, w_obj): - obj = space.unwrap_builtin(w_obj) + obj = space.interpclass_w(w_obj) return space.getattr(obj.w_dict, space.wrap(name)) return GetSetProperty(fget) Modified: pypy/branch/src-typedunwrap/pypy/objspace/trace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trace.py Thu Jan 20 15:31:42 2005 @@ -151,9 +151,7 @@ global operations if operations is None: operations = dict([(r[0], r[0]) for r in ObjSpace.MethodTable]) - for name in ["is_true", "newtuple", "newlist", "newstring", "newdict", - "newslice", "call_args", "is_", "get_and_call_function", - "wrap", "unwrap"]: + for name in ObjSpace.IrregularOpTable+ ["get_and_call_function"]: operations[name] = name return operations Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Thu Jan 20 15:31:42 2005 @@ -171,7 +171,7 @@ else: return w - unwrap_builtin = unwrap + interpclass_w = unwrap def getdict(self, w_obj): if isinstance(w_obj, CPyWrapper): From arigo at codespeak.net Thu Jan 20 16:52:22 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 20 Jan 2005 16:52:22 +0100 (MET) Subject: [pypy-svn] r8440 - pypy/branch/src-typedunwrap/pypy/objspace/std Message-ID: <20050120155222.9D2E627B4C@code1.codespeak.net> Author: arigo Date: Thu Jan 20 16:52:22 2005 New Revision: 8440 Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py Log: Moved the call to the comparison function outside the try:except: block. Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/listobject.py Thu Jan 20 16:52:22 2005 @@ -514,13 +514,14 @@ def complex_lt(self, a, b): space = self.space w_cmp = self.w_cmp + w_result = space.call_function(w_cmp, a, b) try: - result = space.int_w(space.call_function(w_cmp, a, b)) + result = space.int_w(w_result) except OperationError, e: if e.match(space, space.w_TypeError): raise OperationError(space.w_TypeError, space.wrap("comparison function must return int")) - raise e + raise return result < 0 def list_sort__List_ANY(space, w_list, w_cmp): From arigo at codespeak.net Thu Jan 20 17:10:52 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 20 Jan 2005 17:10:52 +0100 (MET) Subject: [pypy-svn] r8441 - pypy/dist/pypy/translator/java/test Message-ID: <20050120161052.EB26727B4F@code1.codespeak.net> Author: arigo Date: Thu Jan 20 17:10:52 2005 New Revision: 8441 Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py Log: Skip java tests if no javac found. Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py ============================================================================== --- pypy/dist/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/dist/pypy/translator/java/test/test_javatrans.py Thu Jan 20 17:10:52 2005 @@ -6,6 +6,12 @@ from pypy.translator.test import snippet from pypy.translator.translator import Translator +def setup_module(mod): + try: + cmdexec('javac') + except py.__impl__.process.cmdexec.ExecutionFailed: + py.test.skip("Java compiler (javac) not found.") + class TestNoTypeCGenTestCase: From arigo at codespeak.net Thu Jan 20 17:29:35 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 20 Jan 2005 17:29:35 +0100 (MET) Subject: [pypy-svn] r8442 - pypy/dist/pypy/translator/java/test Message-ID: <20050120162935.B274027B4F@code1.codespeak.net> Author: arigo Date: Thu Jan 20 17:29:35 2005 New Revision: 8442 Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py Log: Oups, this skips even on machines with javac installed. Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py ============================================================================== --- pypy/dist/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/dist/pypy/translator/java/test/test_javatrans.py Thu Jan 20 17:29:35 2005 @@ -8,7 +8,7 @@ def setup_module(mod): try: - cmdexec('javac') + cmdexec('javac -help') except py.__impl__.process.cmdexec.ExecutionFailed: py.test.skip("Java compiler (javac) not found.") From arigo at codespeak.net Thu Jan 20 18:40:01 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 20 Jan 2005 18:40:01 +0100 (MET) Subject: [pypy-svn] r8444 - in pypy/dist/pypy/translator/java: . test Message-ID: <20050120174001.1F47427B52@code1.codespeak.net> Author: arigo Date: Thu Jan 20 18:40:00 2005 New Revision: 8444 Added: pypy/dist/pypy/translator/java/Builtin.java pypy/dist/pypy/translator/java/PyString.java Modified: pypy/dist/pypy/translator/java/PyList.java pypy/dist/pypy/translator/java/PyObject.java pypy/dist/pypy/translator/java/genjava.py pypy/dist/pypy/translator/java/test/test_javatrans.py Log: Added strings and built-in functions (for now, len()). Added: pypy/dist/pypy/translator/java/Builtin.java ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/java/Builtin.java Thu Jan 20 18:40:00 2005 @@ -0,0 +1,13 @@ + +class builtin_len extends PyObject { + PyObject op_simple_call(PyObject x) + { + return new PyInt(x.len()); + } +} + +class Builtin { + + static PyObject len = new builtin_len(); + +} Modified: pypy/dist/pypy/translator/java/PyList.java ============================================================================== --- pypy/dist/pypy/translator/java/PyList.java (original) +++ pypy/dist/pypy/translator/java/PyList.java Thu Jan 20 18:40:00 2005 @@ -63,7 +63,7 @@ throw new TypeError(); } - PyObject meth_append_1(PyObject item) { + PyObject meth_append(PyObject item) { PyObject[] nitems = new PyObject[items.length + 1]; System.arraycopy(items, 0, nitems, 0, items.length); nitems[items.length] = item; Modified: pypy/dist/pypy/translator/java/PyObject.java ============================================================================== --- pypy/dist/pypy/translator/java/PyObject.java (original) +++ pypy/dist/pypy/translator/java/PyObject.java Thu Jan 20 18:40:00 2005 @@ -26,19 +26,21 @@ PyObject op_inplace_mul(PyObject other) { return op_mul(other); } int len() { throw new TypeError(); } - PyObject op_len() { return new PyInt(len()); } PyObject op_getitem(PyObject index) { throw new TypeError(); } PyObject op_setitem(PyObject index, PyObject o) { throw new TypeError(); } PyObject[] unpack(int expected_length, PyObject[] defaults) { throw new TypeError(); } + PyObject getattr(String attr) { throw new TypeError(); } + PyObject op_getattr(PyObject attr) { + return getattr(((PyString) attr).string); + } + /* CUT HERE -- automatically generated code below this line */ - PyObject meth_append_1(PyObject x) { - return op_getattr_append().op_call_1(x); + PyObject meth_append(PyObject x) { + return getattr("append").op_simple_call(x); } - PyObject op_getattr_append() { throw new TypeError(); } - PyObject op_call_0() { throw new TypeError(); } - PyObject op_call_1(PyObject x) { throw new TypeError(); } - PyObject op_call_0_5tar(PyObject stararg) { throw new TypeError(); } + PyObject op_simple_call() { throw new TypeError(); } + PyObject op_simple_call(PyObject x) { throw new TypeError(); } }; Added: pypy/dist/pypy/translator/java/PyString.java ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/java/PyString.java Thu Jan 20 18:40:00 2005 @@ -0,0 +1,48 @@ + + +class PyString extends PyObject { + + String string; + + PyString(String data) { + string = data; + } + + boolean is_true() { + return string.length() != 0; + } + + int len() { + return string.length(); + } + + boolean eq(PyObject other) { + if (other instanceof PyString) + return string.equals(((PyString) other).string); + else + return false; + } + + boolean lt(PyObject other) { + if (other instanceof PyString) + return string.compareTo(((PyString) other).string) < 0; + else + throw new TypeError(); + } + + PyObject op_getitem(PyObject index) { + if (index instanceof PyInt) { + int i = ((PyInt) index).intval; + return new PyString(string.substring(i, i+1)); + } + throw new TypeError(); + } + + PyObject op_add(PyObject other) { + if (other instanceof PyString) { + return new PyString(string.concat(((PyString) other).string)); + } + throw new TypeError(); + } + +}; Modified: pypy/dist/pypy/translator/java/genjava.py ============================================================================== --- pypy/dist/pypy/translator/java/genjava.py (original) +++ pypy/dist/pypy/translator/java/genjava.py Thu Jan 20 18:40:00 2005 @@ -57,7 +57,7 @@ self.globaldecl = [] self.globalobjects = [] self.pendingfunctions = [] - self.callpatterns = {} + self.callpatterns = {} # for now, arities seen in simple_call() # special constructors: self.has_listarg = { @@ -75,9 +75,8 @@ f = self.jdir.join('test.java').open('w') print >> f, 'class test extends PyObject {' print >> f, ' static public void main(String[] argv) {' - print >> f, ' PyObject result = %s.op_call_%d(%s);' % ( - entrypoint, len(inputargs), - ', '.join([self.nameof(x) for x in inputargs])) + print >> f, ' PyObject result = %s.op_simple_call(%s);' % ( + entrypoint, ', '.join([self.nameof(x) for x in inputargs])) print >> f, ' if (result.eq(%s))' % ( self.nameof(expectedresult),) print >> f, ' System.out.println("OK");' @@ -155,7 +154,12 @@ return "w(%s)" % value def nameof_str(self, value): - return "w(%s)" % repr(value) + content = [] + for c in value: + if not (' ' <= c < '\x7f'): + c = '\\%03o' % ord(c) + content.append(c) + return 'new PyString("%s")' % (''.join(content),) def skipped_function(self, func): # debugging only! Generates a placeholder for missing functions @@ -247,33 +251,10 @@ def nameof_builtin_function_or_method(self, func): if func.__self__ is None: # builtin function - # where does it come from? Python2.2 doesn't have func.__module__ - for modname, module in sys.modules.items(): - if hasattr(module, '__file__'): - if (module.__file__.endswith('.py') or - module.__file__.endswith('.pyc') or - module.__file__.endswith('.pyo')): - continue # skip non-builtin modules - if func is getattr(module, func.__name__, None): - break - else: - raise Exception, '%r not found in any built-in module' % (func,) - name = self.uniquename('gbltin_' + func.__name__) - if modname == '__builtin__': - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - 'PyEval_GetBuiltins(), "%s"))' % ( - name, func.__name__)) - else: - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(module), func.__name__)) + return "Builtin.%s" % func.__name__ else: # builtin (bound) method - name = self.uniquename('gbltinmethod_' + func.__name__) - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(func.__self__), func.__name__)) - return name + assert False, "to do" def nameof_classobj(self, cls): if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): @@ -429,11 +410,12 @@ f.write(data[:i]) print >> f print >> f, ' /* call patterns */' - callpatterns = self.callpatterns.items() - callpatterns.sort() - for callpattern, args in callpatterns: - print >> f, (' PyObject %s(%s) { throw new ' - 'TypeError(); }' % (callpattern, args)) + arities = self.callpatterns.keys() + arities.sort() + for arity in arities: + args = ['PyObject x%d' % i for i in range(arity)] + print >> f, (' PyObject op_simple_call(%s) { throw ' + 'new TypeError(); }' % ', '.join(args)) print >> f self.gen_initcode(f) print >> f, '};' @@ -527,10 +509,9 @@ localvars += block.inputargs # create function declaration - callpattern = "op_call_%d" % len(start.inputargs) args = arglist(start.inputargs, prefix='PyObject ') - self.callpatterns[callpattern] = args - print >> f, " PyObject %s(%s) {" % (callpattern, args) + self.callpatterns[len(start.inputargs)] = True + print >> f, " PyObject op_simple_call(%s) {" % args for v in localvars: print >> f, " PyObject %s = null;" % v print >> f, " int block = %d; // startblock" % blocknum[start] Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py ============================================================================== --- pypy/dist/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/dist/pypy/translator/java/test/test_javatrans.py Thu Jan 20 18:40:00 2005 @@ -59,3 +59,17 @@ def test_sieve_of_eratosthenes(self): self.build_jfunc(snippet.sieve_of_eratosthenes) self.check([], 1028) + + def test_string(self): + def tstring(name): + return len("hello " + name) + self.build_jfunc(tstring) + self.check(["world"], 11) + + def DONT_test_list_append(self): + def tlistappend(): + l = [] + l.append(5) + return l[0] + self.build_jfunc(tlistappend) + self.check([], 5) From pedronis at codespeak.net Thu Jan 20 18:44:03 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 20 Jan 2005 18:44:03 +0100 (MET) Subject: [pypy-svn] r8447 - in pypy/branch/src-typedunwrap/pypy: interpreter objspace objspace/std Message-ID: <20050120174403.B7C3127B52@code1.codespeak.net> Author: pedronis Date: Thu Jan 20 18:44:03 2005 New Revision: 8447 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py pypy/branch/src-typedunwrap/pypy/objspace/std/stdtypedef.py pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Log: nailed down the semantics of interpclass_w(w_obj) to: if w_obj is a wrapped internal interpreter class instance unwrap to it, otherwise return None Modified: pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/baseobjspace.py Thu Jan 20 18:44:03 2005 @@ -132,9 +132,11 @@ def interpclass_w(space, w_obj): """ If w_obj is a wrapped internal interpreter class instance unwrap to it, - otherwise this is the identity + otherwise return None """ - return w_obj # hook for hack by TrivialObjSpace + if isinstance(w_obj, BaseWrappable): + return w_obj + return None def unpackiterable(self, w_iterable, expected_length=None): """Unpack an iterable object into a real (interpreter-level) list. Modified: pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/pyopcode.py Thu Jan 20 18:44:03 2005 @@ -4,7 +4,7 @@ pyfastscope.py and pynestedscope.py. """ -from pypy.interpreter.baseobjspace import OperationError +from pypy.interpreter.baseobjspace import OperationError, BaseWrappable from pypy.interpreter.eval import UNDEFINED from pypy.interpreter import gateway, function from pypy.interpreter import pyframe, pytraceback Modified: pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/typedef.py Thu Jan 20 18:44:03 2005 @@ -109,14 +109,14 @@ __delete__ = interp2app(descr_property_del), ) -def attrproperty(name): +def interp_attrproperty(name): "NOT_RPYTHON: initialization-time only" def fget(space, w_obj): obj = space.interpclass_w(w_obj) return space.wrap(getattr(obj, name)) return GetSetProperty(fget) -def attrproperty_w(name): +def interp_attrproperty_w(name): "NOT_RPYTHON: initialization-time only" def fget(space, w_obj): obj = space.interpclass_w(w_obj) @@ -152,7 +152,7 @@ obj = space.interpclass_w(w_obj) obj.setdict(w_dict) -default_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) +interp_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) # co_xxx interface emulation for built-in code objects @@ -179,7 +179,7 @@ return space.newtuple([w_docstring]) Code.typedef = TypeDef('internal-code', - co_name = attrproperty('co_name'), + co_name = interp_attrproperty('co_name'), co_varnames = GetSetProperty(fget_co_varnames), co_argcount = GetSetProperty(fget_co_argcount), co_flags = GetSetProperty(fget_co_flags), @@ -187,38 +187,38 @@ ) Frame.typedef = TypeDef('internal-frame', - f_code = attrproperty('code'), + f_code = interp_attrproperty('code'), f_locals = GetSetProperty(Frame.fget_getdictscope.im_func), - f_globals = attrproperty_w('w_globals'), + f_globals = interp_attrproperty_w('w_globals'), ) PyCode.typedef = TypeDef('code', __new__ = interp2app(PyCode.descr_code__new__.im_func), - co_argcount = attrproperty('co_argcount'), - co_nlocals = attrproperty('co_nlocals'), - co_stacksize = attrproperty('co_stacksize'), - co_flags = attrproperty('co_flags'), - co_code = attrproperty('co_code'), + co_argcount = interp_attrproperty('co_argcount'), + co_nlocals = interp_attrproperty('co_nlocals'), + co_stacksize = interp_attrproperty('co_stacksize'), + co_flags = interp_attrproperty('co_flags'), + co_code = interp_attrproperty('co_code'), co_consts = GetSetProperty(PyCode.fget_co_consts), - co_names = attrproperty('co_names'), - co_varnames = attrproperty('co_varnames'), - co_freevars = attrproperty('co_freevars'), - co_cellvars = attrproperty('co_cellvars'), - co_filename = attrproperty('co_filename'), - co_name = attrproperty('co_name'), - co_firstlineno = attrproperty('co_firstlineno'), - co_lnotab = attrproperty('co_lnotab'), + co_names = interp_attrproperty('co_names'), + co_varnames = interp_attrproperty('co_varnames'), + co_freevars = interp_attrproperty('co_freevars'), + co_cellvars = interp_attrproperty('co_cellvars'), + co_filename = interp_attrproperty('co_filename'), + co_name = interp_attrproperty('co_name'), + co_firstlineno = interp_attrproperty('co_firstlineno'), + co_lnotab = interp_attrproperty('co_lnotab'), ) PyFrame.typedef = TypeDef('frame', - f_builtins = attrproperty_w('w_builtins'), + f_builtins = interp_attrproperty_w('w_builtins'), f_lineno = GetSetProperty(PyFrame.fget_f_lineno.im_func), **Frame.typedef.rawdict) Module.typedef = TypeDef("module", __new__ = interp2app(Module.descr_module__new__.im_func), __init__ = interp2app(Module.descr_module__init__.im_func), - __dict__ = default_dict_descr, + __dict__ = interp_dict_descr, ) getset_func_doc = GetSetProperty(Function.fget_func_doc, @@ -228,24 +228,24 @@ Function.typedef = TypeDef("function", __call__ = interp2app(Function.descr_function_call.im_func), __get__ = interp2app(Function.descr_function_get.im_func), - func_code = attrproperty('code'), + func_code = interp_attrproperty('code'), func_doc = getset_func_doc, - func_name = attrproperty('name'), - func_dict = attrproperty_w('w_func_dict'), + func_name = interp_attrproperty('name'), + func_dict = interp_attrproperty_w('w_func_dict'), func_defaults = GetSetProperty(Function.fget_func_defaults), - func_globals = attrproperty_w('w_func_globals'), + func_globals = interp_attrproperty_w('w_func_globals'), __doc__ = getset_func_doc, - __name__ = attrproperty('name'), - __dict__ = default_dict_descr, + __name__ = interp_attrproperty('name'), + __dict__ = interp_dict_descr, # XXX func_closure, etc.pp ) Method.typedef = TypeDef("method", __call__ = interp2app(Method.descr_method_call.im_func), __get__ = interp2app(Method.descr_method_get.im_func), - im_func = attrproperty_w('w_function'), - im_self = attrproperty_w('w_instance'), - im_class = attrproperty_w('w_class'), + im_func = interp_attrproperty_w('w_function'), + im_self = interp_attrproperty_w('w_instance'), + im_class = interp_attrproperty_w('w_class'), __getattribute__ = interp2app(Method.descr_method_getattribute.im_func), # XXX getattribute/setattribute etc.pp ) @@ -256,17 +256,17 @@ ) PyTraceback.typedef = TypeDef("traceback", - tb_frame = attrproperty('frame'), - tb_lasti = attrproperty('lasti'), - tb_lineno = attrproperty('lineno'), - tb_next = attrproperty('next'), + tb_frame = interp_attrproperty('frame'), + tb_lasti = interp_attrproperty('lasti'), + tb_lineno = interp_attrproperty('lineno'), + tb_next = interp_attrproperty('next'), ) GeneratorIterator.typedef = TypeDef("generator", next = interp2app(GeneratorIterator.descr_next.im_func), __iter__ = interp2app(GeneratorIterator.descr__iter__.im_func), - gi_running = attrproperty('running'), - gi_frame = attrproperty('frame'), + gi_running = interp_attrproperty('running'), + gi_frame = interp_attrproperty('frame'), ) Cell.typedef = TypeDef("Cell") Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxyobject.py Thu Jan 20 18:44:03 2005 @@ -2,8 +2,7 @@ from pypy.interpreter.typedef import GetSetProperty def descr_get_dictproxy(space, w_obj): - obj = space.interpclass_w(w_obj) - return W_DictProxyObject(space, obj.getdict()) + return W_DictProxyObject(space, w_obj.getdict()) dictproxy_descr = GetSetProperty(descr_get_dictproxy) Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/dictproxytype.py Thu Jan 20 18:44:03 2005 @@ -6,8 +6,7 @@ def proxymethod(name): def fget(space, w_obj): - obj = space.interpclass_w(w_obj) - return space.getattr(obj.w_dict, space.wrap(name)) + return space.getattr(w_obj.w_dict, space.wrap(name)) return GetSetProperty(fget) # ____________________________________________________________ Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/stdtypedef.py Thu Jan 20 18:44:03 2005 @@ -1,7 +1,6 @@ from pypy.interpreter import eval, function, gateway from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import TypeDef, GetSetProperty -from pypy.interpreter.typedef import attrproperty, attrproperty_w from pypy.objspace.std.multimethod import MultiMethod, FailedToImplement __all__ = ['StdTypeDef', 'newmethod', 'gateway', @@ -30,6 +29,31 @@ return False return True +def attrproperty(name): + "NOT_RPYTHON: initialization-time only" + def fget(space, w_obj): + return space.wrap(getattr(w_obj, name)) + return GetSetProperty(fget) + +def attrproperty_w(name): + "NOT_RPYTHON: initialization-time only" + def fget(space, w_obj): + w_value = getattr(w_obj, name) + if w_value is None: + return space.w_None + else: + return w_value + return GetSetProperty(fget) + +def descr_get_dict(space, w_obj): + w_dict = w_obj.getdict() + assert w_dict is not None, repr(w_obj) + return w_dict + +def descr_set_dict(space, w_obj, w_dict): + w_obj.setdict(w_dict) + +std_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) def newmethod(descr_new): "NOT_RPYTHON: initialization-time only." Modified: pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/std/typeobject.py Thu Jan 20 18:44:03 2005 @@ -1,8 +1,7 @@ from pypy.objspace.std.objspace import * from pypy.interpreter.function import Function, StaticMethod -from pypy.interpreter.typedef import default_dict_descr from pypy.interpreter.argument import Arguments -from pypy.objspace.std.stdtypedef import issubtypedef +from pypy.objspace.std.stdtypedef import std_dict_descr, issubtypedef from pypy.objspace.std.objecttype import object_typedef class W_TypeObject(W_Object): @@ -34,7 +33,7 @@ # even for instances that may override the mro. This probably is not # a good thing to do. if forcedict and not w_self.lookup('__dict__'): - w_self.dict_w['__dict__'] = space.wrap(default_dict_descr) + w_self.dict_w['__dict__'] = space.wrap(std_dict_descr) if overridetypedef is None: w_type = space.type(w_self) if not space.is_true(space.is_(w_type, space.w_type)): Modified: pypy/branch/src-typedunwrap/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/trivial.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/trivial.py Thu Jan 20 18:44:03 2005 @@ -171,7 +171,11 @@ else: return w - interpclass_w = unwrap + def interpclass_w(self, w): + w = self.unwrap(w) + if isinstance(w, BaseWrappable): + return w + return None def getdict(self, w_obj): if isinstance(w_obj, CPyWrapper): @@ -240,8 +244,6 @@ typedef.trivialwrapperclass = cls return cls - gettypeobject = hackwrapperclass - def is_(self, w_obj1, w_obj2): return self.unwrap(w_obj1) is self.unwrap(w_obj2) From pedronis at codespeak.net Fri Jan 21 12:48:49 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 21 Jan 2005 12:48:49 +0100 (MET) Subject: [pypy-svn] r8453 - pypy/branch/src-typedunwrap/pypy/objspace/flow Message-ID: <20050121114849.448B727B72@code1.codespeak.net> Author: pedronis Date: Fri Jan 21 12:48:48 2005 New Revision: 8453 Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Log: updated flow/objspace to match interpclass_w semantics. the branch seems ready to be merged, doc changes will be needed in wrapping.txt and some other places Modified: pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/objspace/flow/objspace.py Fri Jan 21 12:48:48 2005 @@ -1,6 +1,6 @@ # ______________________________________________________________________ import sys, operator, types -from pypy.interpreter.baseobjspace import ObjSpace +from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable from pypy.interpreter.pycode import PyCode from pypy.interpreter.error import OperationError from pypy.objspace.flow.model import * @@ -131,7 +131,11 @@ else: raise TypeError("not wrapped: " + repr(w_obj)) - interpclass_w = unwrap + def interpclass_w(self, w_obj): + obj = self.unwrap(w_obj) + if isinstance(obj, BaseWrappable): + return obj + return None def getexecutioncontext(self): return self.executioncontext From arigo at codespeak.net Sat Jan 22 12:59:48 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 22 Jan 2005 12:59:48 +0100 (MET) Subject: [pypy-svn] r8468 - pypy/dist/pypy/translator/java/test Message-ID: <20050122115948.C81F427B56@code1.codespeak.net> Author: arigo Date: Sat Jan 22 12:59:48 2005 New Revision: 8468 Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py Log: Removed my javac detection code and moved Holger's into setup_module(). Modified: pypy/dist/pypy/translator/java/test/test_javatrans.py ============================================================================== --- pypy/dist/pypy/translator/java/test/test_javatrans.py (original) +++ pypy/dist/pypy/translator/java/test/test_javatrans.py Sat Jan 22 12:59:48 2005 @@ -6,23 +6,18 @@ from pypy.translator.test import snippet from pypy.translator.translator import Translator -def setup_module(mod): + +def setup_module(mod): try: - cmdexec('javac -help') - except py.__impl__.process.cmdexec.ExecutionFailed: - py.test.skip("Java compiler (javac) not found.") + py.path.local.sysfind('javac') + except py.error.ENOENT: + py.test.skip("javac not found") class TestNoTypeCGenTestCase: objspacename = 'flow' - def setup_class(cls): - try: - py.path.local.sysfind('javac') - except py.error.ENOENT: - py.test.skip("javac not found") - def build_jfunc(self, func): try: func = func.im_func except AttributeError: pass From odie at codespeak.net Sat Jan 22 17:16:49 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sat, 22 Jan 2005 17:16:49 +0100 (MET) Subject: [pypy-svn] r8471 - pypy/dist/pypy/objspace/flow Message-ID: <20050122161649.F2E2127B5B@code1.codespeak.net> Author: odie Date: Sat Jan 22 17:16:49 2005 New Revision: 8471 Modified: pypy/dist/pypy/objspace/flow/flowcontext.py pypy/dist/pypy/objspace/flow/model.py Log: Propagate variable names to improve readability. Modified: pypy/dist/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/dist/pypy/objspace/flow/flowcontext.py (original) +++ pypy/dist/pypy/objspace/flow/flowcontext.py Sat Jan 22 17:16:49 2005 @@ -111,6 +111,10 @@ return next_instr = frame.next_instr self.crnt_offset = next_instr # save offset for opcode + varnames = frame.code.getvarnames() + for name, w_value in zip(varnames, frame.getfastscope()): + if isinstance(w_value, Variable): + w_value.rename(name) if next_instr in self.joinpoints: currentstate = FrameState(frame) # can 'currentstate' be merged with one of the blocks that @@ -223,6 +227,6 @@ if isinstance(node, EggBlock): mapping = {} for a in node.inputargs: - mapping[a] = Variable() + mapping[a] = Variable(a) node.renamevariables(mapping) traverse(fixegg, self.graph) Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Sat Jan 22 17:16:49 2005 @@ -118,15 +118,31 @@ class Variable: counter = 0 instances = {} + renamed = False + def __init__(self, name=None): - if name is None: - name = 'v%d' % Variable.counter - Variable.counter += 1 - self.name = name - Variable.instances[name] = self + self.name = 'v%d' % Variable.counter + Variable.instances[self.name] = self + Variable.counter += 1 + if name is not None: + self.rename(name) + def __repr__(self): return '%s' % self.name + def rename(self, name): + if self.renamed: + return + if isinstance(name, Variable): + if not name.renamed: + return + name = name.name[:name.name.rfind('_')] + del Variable.instances[self.name] + self.renamed = True + self.name = name + '_' + self.name[1:] + Variable.instances[self.name] = self + + class Constant: def __init__(self, value): self.value = value # a concrete value From hpk at codespeak.net Sat Jan 22 21:08:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 22 Jan 2005 21:08:50 +0100 (MET) Subject: [pypy-svn] r8472 - in pypy/dist: . pypy/tool/tb_server Message-ID: <20050122200850.BC2FC27B48@code1.codespeak.net> Author: hpk Date: Sat Jan 22 21:08:50 2005 New Revision: 8472 Modified: pypy/dist/ (props changed) pypy/dist/pypy/tool/tb_server/render.py pypy/dist/pypy/tool/tb_server/server.py Log: finally get rid of the 'xpy' dependency in favor of the cleaner py.xml one. Fixed the "-H" (Traceback HTTP Server) on the way because it was completly broken anyway. Modified: pypy/dist/pypy/tool/tb_server/render.py ============================================================================== --- pypy/dist/pypy/tool/tb_server/render.py (original) +++ pypy/dist/pypy/tool/tb_server/render.py Sat Jan 22 21:08:50 2005 @@ -1,7 +1,6 @@ from pypy.tool.tb_server.server import TBRequestHandler -from xpy import html, xml - -from py.magic import dyncode +import py +html = py.xml.html import traceback import cgi @@ -41,7 +40,7 @@ import sys, traceback lines = traceback.format_exception(*sys.exc_info()) inner = html.pre( - xml.escape(''.join( + py.xml.escape(''.join( ['Internal Rendering Error, traceback follows\n'] + lines))) tag = html.html( @@ -50,14 +49,16 @@ inner ) ) - return tag.to_unicode() + return tag.unicode(indent=2) class TracebackView(Renderer): - def __init__(self, exc): + def __init__(self, excinfo): self.name = 'traceback%d' % len(views) views[self.name] = self - self.exc = exc + if not isinstance(excinfo, py.code.ExceptionInfo): + excinfo = py.code.ExceptionInfo(excinfo) + self.excinfo = excinfo def render_self(self, url, args): lines = html.div() @@ -68,33 +69,32 @@ opts.setdefault(ent, {})[opt] = val i = 0 - for tb in dyncode.listtb(self.exc[2]): - lines.append(self.render_tb(url, tb, i, - **opts.get('entry' + str(i), {}))) + for tbentry in self.excinfo.traceback: + lines.append(self.render_tb( + url, tbentry, i, + **opts.get('entry' + str(i), {}))) i += 1 - lines.append(html.pre(xml.escape( - ''.join(traceback.format_exception_only(self.exc[0], self.exc[1]))))) + lines.append(html.pre(py.xml.escape(self.excinfo.exconly()))) return lines - def render_tb(self, url, tb, i, showlocals=0): + def render_tb(self, url, tbentry, i, showlocals=0): lines = html.pre() - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - name = tb.tb_frame.f_code.co_name - link = '/file' + filename + '?line=' + str(lineno) + '#' + str(lineno) + filename = tbentry.frame.code.path + lineno = tbentry.lineno + 1 + name = tbentry.frame.code.name + link = '/file%s?line=%d#%d' %(filename, lineno, lineno) lines.append(' File "%s", line %d, in %s\n'%( - html.a(filename, href=link).to_unicode().encode('utf-8'), - lineno, name)) + html.a(filename, href=link), lineno, name)) lines.append(html.a('locals', href=url.link_with_options( - {'entry%s:showlocals'%i:1-showlocals}))) + {'entry%d:showlocals' % i : 1-showlocals}))) lines.append(' ' + - dyncode.getline(filename, lineno).lstrip()) + filename.readlines()[lineno-1].lstrip()) if showlocals: - for k, v in tb.tb_frame.f_locals.items(): + for k, v in tbentry.frame.f_locals.items(): if k[0] == '_': continue - lines.append(xml.escape('%s=%s\n'%(k, repr(v)[:1000]))) + lines.append(py.xml.escape('%s=%s\n'%(k, repr(v)[:1000]))) return lines @@ -115,7 +115,7 @@ row = html.tr( html.td(html.a("%03d" % i, name=str(i))), html.td( - html.pre(xml.escape(line)[:-1], + html.pre(py.xml.escape(line)[:-1], **kws), ), ) Modified: pypy/dist/pypy/tool/tb_server/server.py ============================================================================== --- pypy/dist/pypy/tool/tb_server/server.py (original) +++ pypy/dist/pypy/tool/tb_server/server.py Sat Jan 22 21:08:50 2005 @@ -92,5 +92,5 @@ print "traceback is at http://localhost:%d/%s" % (server_port, x.name) if __name__ == "__main__": - t = main() + t = start() wait_until_interrupt() From pedronis at codespeak.net Sun Jan 23 10:42:41 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sun, 23 Jan 2005 10:42:41 +0100 (MET) Subject: [pypy-svn] r8475 - pypy/branch/src-typedunwrap/pypy/interpreter/test Message-ID: <20050123094241.0E64927B4C@code1.codespeak.net> Author: pedronis Date: Sun Jan 23 10:42:40 2005 New Revision: 8475 Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_extmodule.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_main.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_module.py pypy/branch/src-typedunwrap/pypy/interpreter/test/test_objspace.py Log: asserts appear in interpreter test Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_extmodule.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_extmodule.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_extmodule.py Sun Jan 23 10:42:40 2005 @@ -10,16 +10,16 @@ m = BuiltinModule(space, 'foo', sourcefile=sourcefile) w = space.wrap w_m = space.wrap(m) - self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo')) - self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile)) + assert self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo')) + assert self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile)) # check app-level definitions - self.space.eq_w(m.w_foo, space.w_Ellipsis) - self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) - self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) - self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) - self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello')) - self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) + assert self.space.eq_w(m.w_foo, space.w_Ellipsis) + assert self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) + assert self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) + assert self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) + assert self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello')) + assert self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) # check interp-level definitions - self.space.eq_w(m.w_foo2, w('hello')) - self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) - self.space.eq_w(m.fortytwo, w(42)) + assert self.space.eq_w(m.w_foo2, w('hello')) + assert self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) + assert self.space.eq_w(m.fortytwo, w(42)) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_gateway.py Sun Jan 23 10:42:40 2005 @@ -33,7 +33,7 @@ (w('hello'), self.space.newtuple([w(0), w(True)])), ]) w_result = code.exec_code(self.space, w_dict, w_dict) - self.space.eq_w(w_result, w(102)) + assert self.space.eq_w(w_result, w(102)) def test_call_args(self): def c(space, w_x, w_y, __args__): @@ -51,7 +51,7 @@ (w('keywords'), self.space.newdict([(w('boo'), w(10))])), ]) w_result = code.exec_code(self.space, w_dict, w_dict) - self.space.eq_w(w_result, w(1020)) + assert self.space.eq_w(w_result, w(1020)) class TestGateway: @@ -60,7 +60,7 @@ def app_g3(a, b): return a+b g3 = gateway.app2interp_temp(app_g3) - self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar')) + assert self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar')) def test_interp2app(self): space = self.space @@ -69,12 +69,12 @@ return space.add(w_a, w_b) app_g3 = gateway.interp2app_temp(g3) w_app_g3 = space.wrap(app_g3) - self.space.eq_w( + assert self.space.eq_w( space.call(w_app_g3, space.newtuple([w('foo'), w('bar')]), space.newdict([])), w('foobar')) - self.space.eq_w( + assert self.space.eq_w( space.call_function(w_app_g3, w('foo'), w('bar')), w('foobar')) @@ -88,12 +88,12 @@ gateway.W_Root, gateway.W_Root]) w_app_g3 = space.wrap(app_g3) - self.space.eq_w( + assert self.space.eq_w( space.call(w_app_g3, space.newtuple([w('foo'), w('bar')]), space.newdict([])), w('foobar')) - self.space.eq_w( + assert self.space.eq_w( space.call_function(w_app_g3, w('foo'), w('bar')), w('foobar')) @@ -106,12 +106,12 @@ unwrap_spec=[gateway.ObjSpace, 'args_w']) w_app_g3_args_w = space.wrap(app_g3_args_w) - self.space.eq_w( + assert self.space.eq_w( space.call(w_app_g3_args_w, space.newtuple([w('foo'), w('bar')]), space.newdict([])), w('foobar')) - self.space.eq_w( + assert self.space.eq_w( space.call_function(w_app_g3_args_w, w('foo'), w('bar')), w('foobar')) @@ -124,12 +124,12 @@ unwrap_spec=[gateway.ObjSpace, str,str]) w_app_g3_ss = space.wrap(app_g3_ss) - self.space.eq_w( + assert self.space.eq_w( space.call(w_app_g3_ss, space.newtuple([w('foo'), w('bar')]), space.newdict([])), w('foobar')) - self.space.eq_w( + assert self.space.eq_w( space.call_function(w_app_g3_ss, w('foo'), w('bar')), w('foobar')) @@ -142,13 +142,13 @@ unwrap_spec=[gateway.ObjSpace, int,float]) w_app_g3_if = space.wrap(app_g3_if) - self.space.eq_w( + assert self.space.eq_w( space.call(w_app_g3_if, space.newtuple([w(1), w(1.0)]), space.newdict([])), w(2.0)) - self.space.eq_w( - space.call_function(w_app_g3_if, w(1), w(2.0)), + assert self.space.eq_w( + space.call_function(w_app_g3_if, w(1), w(1.0)), w(2.0)) def test_interp2app_unwrap_spec_typechecks(self): @@ -160,8 +160,8 @@ unwrap_spec=[gateway.ObjSpace, int]) w_app_g3_i = space.wrap(app_g3_i) - space.eq_w(space.call_function(w_app_g3_i,w(1)),w(1)) - space.eq_w(space.call_function(w_app_g3_i,w(1L)),w(1)) + assert space.eq_w(space.call_function(w_app_g3_i,w(1)),w(1)) + assert space.eq_w(space.call_function(w_app_g3_i,w(1L)),w(1)) raises(gateway.OperationError,space.call_function,w_app_g3_i,w(2**32)) raises(gateway.OperationError,space.call_function,w_app_g3_i,w(None)) raises(gateway.OperationError,space.call_function,w_app_g3_i,w("foo")) @@ -171,7 +171,7 @@ unwrap_spec=[gateway.ObjSpace, str]) w_app_g3_s = space.wrap(app_g3_s) - space.eq_w(space.call_function(w_app_g3_s,w("foo")),w("foo")) + assert space.eq_w(space.call_function(w_app_g3_s,w("foo")),w("foo")) raises(gateway.OperationError,space.call_function,w_app_g3_s,w(None)) raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1)) raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1.0)) @@ -180,9 +180,9 @@ unwrap_spec=[gateway.ObjSpace, float]) w_app_g3_f = space.wrap(app_g3_f) - space.eq_w(space.call_function(w_app_g3_f,w(1.0)),w(1.0)) - space.eq_w(space.call_function(w_app_g3_f,w(1)),w(1.0)) - space.eq_w(space.call_function(w_app_g3_f,w(1L)),w(1.0)) + assert space.eq_w(space.call_function(w_app_g3_f,w(1.0)),w(1.0)) + assert space.eq_w(space.call_function(w_app_g3_f,w(1)),w(1.0)) + assert space.eq_w(space.call_function(w_app_g3_f,w(1L)),w(1.0)) raises(gateway.OperationError,space.call_function,w_app_g3_f,w(None)) raises(gateway.OperationError,space.call_function,w_app_g3_f,w("foo")) @@ -198,7 +198,7 @@ """ in g gateway.importall(g, temporary=True) g1 = g['g1'] - self.space.eq_w(g1(self.space, w('bar')), w('foobar')) + assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) def test_exportall(self): w = self.space.wrap @@ -211,4 +211,4 @@ """ in g gateway.exportall(g, temporary=True) g1 = gateway.app2interp_temp(g['app_g1']) - self.space.eq_w(g1(self.space, w('bar')), w('foobar')) + assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_main.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_main.py Sun Jan 23 10:42:40 2005 @@ -51,4 +51,4 @@ def test_eval_string(self): w_x = main.eval_string('2+2', space=self.space) - self.space.eq_w(w_x, self.space.wrap(4)) + assert self.space.eq_w(w_x, self.space.wrap(4)) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_module.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_module.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_module.py Sun Jan 23 10:42:40 2005 @@ -11,13 +11,13 @@ def test_name(self): w = self.space.wrap w_m = w(self.m) - self.space.eq_w(self.space.getattr(w_m, w('__name__')), w('m')) + assert self.space.eq_w(self.space.getattr(w_m, w('__name__')), w('m')) def test_attr(self): w = self.space.wrap w_m = w(self.m) self.space.setattr(w_m, w('x'), w(15)) - self.space.eq_w(self.space.getattr(w_m, w('x')), w(15)) + assert self.space.eq_w(self.space.getattr(w_m, w('x')), w(15)) self.space.delattr(w_m, w('x')) self.space.raises_w(self.space.w_AttributeError, self.space.delattr, w_m, w('x')) Modified: pypy/branch/src-typedunwrap/pypy/interpreter/test/test_objspace.py ============================================================================== --- pypy/branch/src-typedunwrap/pypy/interpreter/test/test_objspace.py (original) +++ pypy/branch/src-typedunwrap/pypy/interpreter/test/test_objspace.py Sun Jan 23 10:42:40 2005 @@ -9,7 +9,7 @@ w = self.space.wrap s = 'abc' chars_w = [w(ord(c)) for c in s] - self.space.eq_w(w(s), self.space.newstring(chars_w)) + assert self.space.eq_w(w(s), self.space.newstring(chars_w)) def test_newstring_fail(self): w = self.space.wrap @@ -26,7 +26,7 @@ w = self.space.wrap l = range(10) w_l = self.space.newlist([w(i) for i in l]) - self.space.eq_w(w_l, w(l)) + assert self.space.eq_w(w_l, w(l)) def test_newdict(self): w = self.space.wrap @@ -34,13 +34,13 @@ items_w = [(w(k), w(v)) for (k, v) in items] d = dict(items) w_d = self.space.newdict(items_w) - self.space.eq_w(w_d, w(d)) + assert self.space.eq_w(w_d, w(d)) def test_newtuple(self): w = self.space.wrap t = tuple(range(10)) w_t = self.space.newtuple([w(i) for i in t]) - self.space.eq_w(w_t, w(t)) + assert self.space.eq_w(w_t, w(t)) def test_is_true(self): w = self.space.wrap From arigo at codespeak.net Sun Jan 23 12:01:03 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:01:03 +0100 (MET) Subject: [pypy-svn] r8478 - in pypy/branch/src-typedunwrap/pypy: appspace appspace/test documentation objspace/flow tool/tb_server translator/java translator/java/test translator/test Message-ID: <20050123110103.A6F9427B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:01:03 2005 New Revision: 8478 Added: pypy/branch/src-typedunwrap/pypy/appspace/struct.py - copied unchanged from r8477, pypy/dist/pypy/appspace/struct.py pypy/branch/src-typedunwrap/pypy/appspace/test/support_tests.py - copied unchanged from r8477, pypy/dist/pypy/appspace/test/support_tests.py pypy/branch/src-typedunwrap/pypy/appspace/test/test_file.py - copied unchanged from r8477, pypy/dist/pypy/appspace/test/test_file.py pypy/branch/src-typedunwrap/pypy/appspace/test/test_struct.py - copied unchanged from r8477, pypy/dist/pypy/appspace/test/test_struct.py pypy/branch/src-typedunwrap/pypy/documentation/ - copied from r8477, pypy/dist/pypy/documentation/ pypy/branch/src-typedunwrap/pypy/objspace/flow/flowcontext.py - copied unchanged from r8477, pypy/dist/pypy/objspace/flow/flowcontext.py pypy/branch/src-typedunwrap/pypy/objspace/flow/model.py - copied unchanged from r8477, pypy/dist/pypy/objspace/flow/model.py pypy/branch/src-typedunwrap/pypy/tool/tb_server/render.py - copied unchanged from r8477, pypy/dist/pypy/tool/tb_server/render.py pypy/branch/src-typedunwrap/pypy/tool/tb_server/server.py - copied unchanged from r8477, pypy/dist/pypy/tool/tb_server/server.py pypy/branch/src-typedunwrap/pypy/translator/java/Builtin.java - copied unchanged from r8477, pypy/dist/pypy/translator/java/Builtin.java pypy/branch/src-typedunwrap/pypy/translator/java/PyList.java - copied unchanged from r8477, pypy/dist/pypy/translator/java/PyList.java pypy/branch/src-typedunwrap/pypy/translator/java/PyObject.java - copied unchanged from r8477, pypy/dist/pypy/translator/java/PyObject.java pypy/branch/src-typedunwrap/pypy/translator/java/PyString.java - copied unchanged from r8477, pypy/dist/pypy/translator/java/PyString.java pypy/branch/src-typedunwrap/pypy/translator/java/genjava.py - copied unchanged from r8477, pypy/dist/pypy/translator/java/genjava.py pypy/branch/src-typedunwrap/pypy/translator/java/test/test_javatrans.py - copied unchanged from r8477, pypy/dist/pypy/translator/java/test/test_javatrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_cltrans.py - copied unchanged from r8477, pypy/dist/pypy/translator/test/test_cltrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_ctrans.py - copied unchanged from r8477, pypy/dist/pypy/translator/test/test_ctrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_pyrextrans.py - copied unchanged from r8477, pypy/dist/pypy/translator/test/test_pyrextrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_sourcegen.py - copied unchanged from r8477, pypy/dist/pypy/translator/test/test_sourcegen.py Log: Merge, step 2: copied files from the head into the branch. History comes with them. From arigo at codespeak.net Sun Jan 23 12:01:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:01:26 +0100 (MET) Subject: [pypy-svn] r8479 - pypy/dist/pypy Message-ID: <20050123110126.7F01427B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:01:26 2005 New Revision: 8479 Removed: pypy/dist/pypy/ Log: Merge, step 3: delete the head! From arigo at codespeak.net Sun Jan 23 12:02:41 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:02:41 +0100 (MET) Subject: [pypy-svn] r8480 - pypy/dist/pypy Message-ID: <20050123110241.1403327B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:02:40 2005 New Revision: 8480 Added: pypy/dist/pypy/ - copied from r8479, pypy/branch/src-typedunwrap/pypy/ Log: Merge, last step: copy branch as head. From arigo at codespeak.net Sun Jan 23 12:04:05 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:04:05 +0100 (MET) Subject: [pypy-svn] r8481 - pypy/branch/src-typedunwrap Message-ID: <20050123110405.B3F7227B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:04:05 2005 New Revision: 8481 Removed: pypy/branch/src-typedunwrap/ Log: Delete the branch. From mwh at codespeak.net Sun Jan 23 12:12:57 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Sun, 23 Jan 2005 12:12:57 +0100 (MET) Subject: [pypy-svn] r8483 - pypy/dist/pypy/objspace/std Message-ID: <20050123111257.62B9B27B49@code1.codespeak.net> Author: mwh Date: Sun Jan 23 12:12:57 2005 New Revision: 8483 Modified: pypy/dist/pypy/objspace/std/dictobject.py Log: remove old comments Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Sun Jan 23 12:12:57 2005 @@ -83,13 +83,7 @@ freeslot = None perturb = lookup_hash - ##c = len(self.data) + 99 while 1: - ##c -= 1 - ##if not c: - ## import sys, pdb - ## print >> sys.stderr, 'dict lookup lost in infinite loop' - ## pdb.set_trace() i = (i << 2) + i + perturb + 1 entry = self.data[i%len(self.data)] if entry.w_value is None: From arigo at codespeak.net Sun Jan 23 12:22:23 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:22:23 +0100 (MET) Subject: [pypy-svn] r8484 - pypy/dist/pypy/objspace/flow Message-ID: <20050123112223.2145527B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:22:22 2005 New Revision: 8484 Modified: pypy/dist/pypy/objspace/flow/model.py Log: Don't put strange characters in variable names. Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Sun Jan 23 12:22:22 2005 @@ -137,6 +137,8 @@ if not name.renamed: return name = name.name[:name.name.rfind('_')] + # remove strange characters in the name + name = ''.join([c for c in name if c.isalnum() or c == '_']) del Variable.instances[self.name] self.renamed = True self.name = name + '_' + self.name[1:] From arigo at codespeak.net Sun Jan 23 12:27:41 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:27:41 +0100 (MET) Subject: [pypy-svn] r8485 - pypy/dist/pypy/objspace/flow Message-ID: <20050123112741.0884327B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:27:40 2005 New Revision: 8485 Modified: pypy/dist/pypy/objspace/flow/model.py Log: Grumble. Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Sun Jan 23 12:27:40 2005 @@ -139,6 +139,10 @@ name = name.name[:name.name.rfind('_')] # remove strange characters in the name name = ''.join([c for c in name if c.isalnum() or c == '_']) + if not name: + return + if '0' <= name[0] <= '9': + name = '_' + name del Variable.instances[self.name] self.renamed = True self.name = name + '_' + self.name[1:] From arigo at codespeak.net Sun Jan 23 11:58:24 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 11:58:24 +0100 (MET) Subject: [pypy-svn] r8477 - in pypy/branch/src-typedunwrap/pypy: appspace appspace/test objspace/flow tool/tb_server translator/java translator/java/test translator/test Message-ID: <20050123105824.2F5BA27B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 11:58:23 2005 New Revision: 8477 Removed: pypy/branch/src-typedunwrap/pypy/appspace/struct.py pypy/branch/src-typedunwrap/pypy/appspace/test/support_tests.py pypy/branch/src-typedunwrap/pypy/appspace/test/test_file.py pypy/branch/src-typedunwrap/pypy/objspace/flow/flowcontext.py pypy/branch/src-typedunwrap/pypy/objspace/flow/model.py pypy/branch/src-typedunwrap/pypy/tool/tb_server/render.py pypy/branch/src-typedunwrap/pypy/tool/tb_server/server.py pypy/branch/src-typedunwrap/pypy/translator/java/PyList.java pypy/branch/src-typedunwrap/pypy/translator/java/PyObject.java pypy/branch/src-typedunwrap/pypy/translator/java/genjava.py pypy/branch/src-typedunwrap/pypy/translator/java/test/test_javatrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_cltrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_ctrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_pyrextrans.py pypy/branch/src-typedunwrap/pypy/translator/test/test_sourcegen.py Log: Merging head into branch: step 1 (removing files that changed only in the head). Deleted: /pypy/branch/src-typedunwrap/pypy/appspace/struct.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/appspace/struct.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,343 +0,0 @@ -import math,sys - -"""Functions to convert between Python values and C structs. -Python strings are used to hold the data representing the C struct -and also as format strings to describe the layout of data in the C struct. - -The optional first format char indicates byte order, size and alignment: - @: native order, size & alignment (default) - =: native order, std. size & alignment - <: little-endian, std. size & alignment - >: big-endian, std. size & alignment - !: same as > - -The remaining chars indicate types of args and must match exactly; -these can be preceded by a decimal repeat count: - x: pad byte (no data); - c:char; - b:signed byte; - B:unsigned byte; - h:short; - H:unsigned short; - i:int; - I:unsigned int; - l:long; - L:unsigned long; - f:float; - d:double. -Special cases (preceding decimal count indicates length): - s:string (array of char); p: pascal string (with count byte). -Special case (only available in native format): - P:an integer type that is wide enough to hold a pointer. -Special case (not in native mode unless 'long long' in platform C): - q:long long; - Q:unsigned long long -Whitespace between formats is ignored. - -The variable struct.error is an exception raised on errors.""" - -# TODO: XXX Find a way to get information on native sizes and alignments -class StructError(Exception): - pass -error = StructError -def unpack_int(data,index,size,le): - bytes = [ord(b) for b in data[index:index+size]] - if le == 'little': - bytes.reverse() - number = 0 - for b in bytes: - number = number << 8 | b - return number - -def unpack_signed_int(data,index,size,le): - number = unpack_int(data,index,size,le) - max = 2**(size*8) - if number > 2**(size*8 - 1) - 1: - number = -1*(max - number) - return number - -def unpack_float(data,index,size,le): - bytes = [ord(b) for b in data[index:index+size]] - if len(bytes) != size: - raise StructError,"Not enough data to unpack" - if le == 'big': - bytes.reverse() - if size == 4: - bias = 127 - exp = 8 - prec = 23 - else: - bias = 1023 - exp = 11 - prec = 52 -# print bytes,size,index,len(data),data - mantissa = bytes[size-2] & (2**(15-exp)-1) -# print mantissa - for b in bytes[size-3::-1]: - mantissa = mantissa << 8 | b -# print mantissa - mantissa = 1 + (1.0*mantissa)/(2**(prec)) - mantissa /= 2 -# print mantissa - e = (bytes[-1] & 0x7f) << (exp - 7) - e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1) - e -= bias - e += 1 - sign = bytes[-1] & 0x80 - number = math.ldexp(mantissa,e) -# print number,index,mantissa,e,bytes#,data - if sign : number *= -1 - return number - -def unpack_char(data,index,size,le): - return data[index:index+size] - -def pack_int(number,size,le): - x=number - res=[] - for i in range(size): - res.append(chr(x&0xff)) - x >>= 8 - if le == 'big': - res.reverse() - return ''.join(res) - -def pack_signed_int(number,size,le): - if type(number) not in [int,long]: - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" - if number > 2**(8*size-1)-1 or number < -1*2**(8*size-1): - raise OverflowError,"Number:%i to large to convert" % number - return pack_int(number,size,le) - -def pack_unsigned_int(number,size,le): - if type(number) not in [int,long]: - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" - if number < 0: - raise TypeError,"can't convert negative long to unsigned" - if number > 2**(8*size)-1: - raise OverflowError,"Number:%i to large to convert" % number - return pack_int(number,size,le) - -def pack_char(char,size,le): -# print char - return str(char) - -def sane_float(man,e): - # TODO: XXX Implement checks for floats - return True - -def pack_float(number,size,le): - - if number < 0: - sign=1 - number *= -1 - else: - sign =0 - if size == 4: - bias = 127 - exp = 8 - prec = 23 - else: - bias = 1023 - exp = 11 - prec = 52 - - man,e = math.frexp(number) - if 0.5 <= man and man < 1.0: - man *= 2 - e -= 1 - if sane_float(man,e): - man -= 1 - e += bias - mantissa = int(2**prec *(man) +0.5) - res=[] - - for i in range(size-2): - res += [ mantissa & 0xff] - mantissa >>= 8 - res += [ (mantissa & (2**(15-exp)-1)) | ((e & (2**(exp-7)-1))<<(15-exp))] - res += [sign << 7 | e >> (exp - 7)] - if le == 'big': - res.reverse() - return ''.join([chr(x) for x in res]) - # TODO: What todo with insane floats/doubles. handle in sanefloat? - -big_endian_format = { - 'x':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'b':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'B':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'c':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_char, 'unpack' : unpack_char}, - 's':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'p':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'h':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'H':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'i':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'I':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'l':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'L':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'Q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'f':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, - 'd':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, - } -default = big_endian_format -formatmode={ '<' : (default, 'little'), - '>' : (default, 'big'), - '!' : (default, 'big'), - '=' : (default, sys.byteorder), - '@' : (default, sys.byteorder) - } - -def getmode(fmt): - try: - formatdef,endianness = formatmode[fmt[0]] - index = 1 - except KeyError: - formatdef,endianness = formatmode['@'] - index = 0 - return formatdef,endianness,index -def getNum(fmt,i): - num=None - cur = fmt[i] - while ('0'<= cur ) and ( cur <= '9'): - if num == None: - num = int(cur) - else: - num = 10*num + int(cur) - i += 1 - cur = fmt[i] - return num,i - -def calcsize(fmt): - """calcsize(fmt) -> int - Return size of C struct described by format string fmt. - See struct.__doc__ for more on format strings.""" - - formatdef,endianness,i = getmode(fmt) - num = 0 - result = 0 - while i string - Return string containing values v1, v2, ... packed according to fmt. - See struct.__doc__ for more on format strings.""" - formatdef,endianness,i = getmode(fmt) - args = list(args) - n_args = len(args) - result = [] - while i=0: - result += [args[0][:num] + '\0'*padding] - else: - result += [args[0][:num]] - args.pop() - else: - raise StructError,"arg for string format not a string" - elif cur == 'p': - if type(args[0]) == str: - padding = num - len(args[0]) - 1 - - if padding > 0: - result += [chr(len(args[0])) + args[0][:num-1] + '\0'*padding] - else: - if num<255: - result += [chr(num-1) + args[0][:num-1]] - else: - result += [chr(255) + args[0][:num-1]] - args.pop() - else: - raise StructError,"arg for string format not a string" - - else: - if len(args) == 0: - raise StructError,"insufficient arguments to pack" - for var in args[:num]: - result += [format['pack'](var,format['size'],endianness)] - args=args[num:] - num = None - i += 1 - if len(args) != 0: - raise StructError,"too many arguments for pack format" - return ''.join(result) - -def unpack(fmt,data): - """unpack(fmt, string) -> (v1, v2, ...) - Unpack the string, containing packed C structure data, according - to fmt. Requires len(string)==calcsize(fmt). - See struct.__doc__ for more on format strings.""" - formatdef,endianness,i = getmode(fmt) -# print fmt,data - j = 0 - num = 0 - result = [] - length= calcsize(fmt) - if length != len (data): - raise StructError,"unpack str size does not match format" - while i= num: - n = num-1 - result.append(data[j+1:j+n+1]) - j += num - i += 1 - else: - for n in range(num): - result += [format['unpack'](data,j,format['size'],endianness)] - j += format['size'] - i += 1 - - return result - -if __name__ == '__main__': - print pack_float(1.23,4,'little') - import struct - print struct.pack('f',1.23), pack('f',1.23) - print unpack('f',pack('f',1.23)) \ No newline at end of file Deleted: /pypy/branch/src-typedunwrap/pypy/appspace/test/support_tests.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/appspace/test/support_tests.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,180 +0,0 @@ -"""Supporting definitions for the Python regression tests.""" - -''' -if __name__ != 'test.test_support': - raise ImportError, 'test_support must be imported from the test package' -''' - -import sys -from os import unlink - -import py -TESTFN = str(py.test.config.tempdir.join('@test')) - -class Error(Exception): - """Base class for regression test exceptions.""" - -class TestFailed(Error): - """Test failed.""" - -class TestSkipped(Error): - """Test skipped. - - This can be raised to indicate that a test was deliberatly - skipped, but not because a feature wasn't available. For - example, if some resource can't be used, such as the network - appears to be unavailable, this should be raised instead of - TestFailed. - """ - -class ResourceDenied(TestSkipped): - """Test skipped because it requested a disallowed resource. - - This is raised when a test calls requires() for a resource that - has not be enabled. It is used to distinguish between expected - and unexpected skips. - """ - -verbose = 1 # Flag set to 0 by regrtest.py -use_resources = None # Flag set to [] by regrtest.py - -# _original_stdout is meant to hold stdout at the time regrtest began. -# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. -# The point is to have some flavor of stdout the user can actually see. -_original_stdout = None -def record_original_stdout(stdout): - global _original_stdout - _original_stdout = stdout - -def get_original_stdout(): - return _original_stdout or sys.stdout - -def unload(name): - try: - del sys.modules[name] - except KeyError: - pass - -def forget(modname): - '''"Forget" a module was ever imported by removing it from sys.modules and - deleting any .pyc and .pyo files.''' - unload(modname) - import os - for dirname in sys.path: - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) - except os.error: - pass - # Deleting the .pyo file cannot be within the 'try' for the .pyc since - # the chance exists that there is no .pyc (and thus the 'try' statement - # is exited) but there is a .pyo file. - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) - except os.error: - pass - -def is_resource_enabled(resource): - """Test whether a resource is enabled. Known resources are set by - regrtest.py.""" - return use_resources is not None and resource in use_resources - -def requires(resource, msg=None): - """Raise ResourceDenied if the specified resource is not available. - - If the caller's module is __main__ then automatically return True. The - possibility of False being returned occurs when regrtest.py is executing.""" - # see if the caller's module is __main__ - if so, treat as if - # the resource was set - if sys._getframe().f_back.f_globals.get("__name__") == "__main__": - return - if not is_resource_enabled(resource): - if msg is None: - msg = "Use of the `%s' resource not enabled" % resource - raise ResourceDenied(msg) - -FUZZ = 1e-6 - -def fcmp(x, y): # fuzzy comparison function - if type(x) == type(0.0) or type(y) == type(0.0): - try: - x, y = float(x), float(y) - fuzz = (abs(x) + abs(y)) * FUZZ - if abs(x-y) <= fuzz: - return 0 - except: - pass - elif type(x) == type(y) and type(x) in (type(()), type([])): - for i in range(min(len(x), len(y))): - outcome = fcmp(x[i], y[i]) - if outcome != 0: - return outcome - return cmp(len(x), len(y)) - return cmp(x, y) - -try: - unicode - have_unicode = 0 # XXX UNICODE 1 -except NameError: - have_unicode = 0 - -is_jython = sys.platform.startswith('java') - - - -if fp is not None: - fp.close() -del fp - -def findfile(file, here=__file__): - """Try to find a file on sys.path and the working directory. If it is not - found the argument passed to the function is returned (this does not - necessarily signal failure; could still be the legitimate path).""" - import os - if os.path.isabs(file): - return file - path = sys.path - path = [os.path.dirname(here)] + path - for dn in path: - fn = os.path.join(dn, file) - if os.path.exists(fn): return fn - return file - -def verify(condition, reason='test failed'): - """Verify that condition is true. If not, raise TestFailed. - - The optional argument reason can be given to provide - a better error text. - """ - - if not condition: - raise TestFailed(reason) - -def vereq(a, b): - """Raise TestFailed if a == b is false. - - This is better than verify(a == b) because, in case of failure, the - error message incorporates repr(a) and repr(b) so you can see the - inputs. - - Note that "not (a == b)" isn't necessarily the same as "a != b"; the - former is tested. - """ - - if not (a == b): - raise TestFailed, "%r == %r" % (a, b) - -def sortdict(dict): - "Like repr(dict), but in sorted order." - items = dict.items() - items.sort() - reprpairs = ["%r: %r" % pair for pair in items] - withcommas = ", ".join(reprpairs) - return "{%s}" % withcommas - -def check_syntax(statement): - try: - compile(statement, '', 'exec') - except SyntaxError: - pass - else: - print 'Missing SyntaxError: "%s"' % statement Deleted: /pypy/branch/src-typedunwrap/pypy/appspace/test/test_file.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/appspace/test/test_file.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,24 +0,0 @@ -import os -import autopath -from pypy.appspace import _file -from py.test import raises -import unittest - -class TestFile: - def setup_method(self, method): - filename = os.path.join(autopath.this_dir, 'test_file.py') - self.fd = _file.file_(filename, 'r') - - def teardown_method(self, method): - self.fd.close() - - def test_case_1(self): - assert self.fd.tell() == 0 - - def test_case_readonly(self): - f=_file.file_('/tmp/tt', 'w') - assert f.name == '/tmp/tt' - assert f.mode == 'w' - assert f.closed == False - assert f.encoding == None # Fix when we find out what this is - raises(TypeError, setattr, f, 'name', 42) Deleted: /pypy/branch/src-typedunwrap/pypy/objspace/flow/flowcontext.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/objspace/flow/flowcontext.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,228 +0,0 @@ -from pypy.interpreter.executioncontext import ExecutionContext -from pypy.interpreter.pyframe import ExitFrame -from pypy.interpreter.error import OperationError -from pypy.objspace.flow.model import * -from pypy.objspace.flow.framestate import FrameState - - -class SpamBlock(Block): - dead = False - - def __init__(self, framestate): - Block.__init__(self, framestate.getvariables()) - self.framestate = framestate - - def patchframe(self, frame, executioncontext): - if self.dead: - raise ExitFrame(None) - self.framestate.restoreframe(frame) - executioncontext.crnt_block = self - executioncontext.crnt_ops = self.operations - - -class EggBlock(Block): - - def __init__(self, inputargs, prevblock, booloutcome): - Block.__init__(self, inputargs) - self.prevblock = prevblock - self.booloutcome = booloutcome - - def patchframe(self, frame, executioncontext): - parentblocks = [] - block = self - while isinstance(block, EggBlock): - block = block.prevblock - parentblocks.append(block) - # parentblocks = [Egg, Egg, ..., Egg, Spam] not including self - block.patchframe(frame, executioncontext) - replaylist = self.operations - prevblock = self - for block in parentblocks: - replaylist = ReplayList(block.operations, - prevblock, prevblock.booloutcome, - replaylist) - prevblock = block - executioncontext.crnt_ops = replaylist - -class ReplayList: - - def __init__(self, listtoreplay, nextblock, booloutcome, nextreplaylist): - self.listtoreplay = listtoreplay - self.nextblock = nextblock - self.booloutcome = booloutcome - self.nextreplaylist = nextreplaylist - self.index = 0 - - def append(self, operation): - operation.result = self.listtoreplay[self.index].result - assert operation == self.listtoreplay[self.index], ( - '\n'.join(["Not generating the same operation sequence:"] + - [str(s) for s in self.listtoreplay[:self.index]] + - [" ---> | while repeating we see here"] + - [" | %s" % operation] + - [str(s) for s in self.listtoreplay[self.index:]])) - self.index += 1 - - def finished(self): - return self.index == len(self.listtoreplay) - -class ConcreteNoOp: - # In "concrete mode", no SpaceOperations between Variables are allowed. - # Concrete mode is used to precompute lazily-initialized caches, - # when we don't want this precomputation to show up on the flow graph. - def append(self, operation): - raise AssertionError, "concrete mode: cannot perform %s" % operation - -class FlowExecutionContext(ExecutionContext): - - def __init__(self, space, code, globals, constargs={}, closure=None, - name=None): - ExecutionContext.__init__(self, space) - self.code = code - self.w_globals = w_globals = space.wrap(globals) - self.crnt_offset = -1 - if closure is None: - self.closure = None - else: - from pypy.interpreter.nestedscope import Cell - self.closure = [Cell(Constant(value)) for value in closure] - frame = self.create_frame() - formalargcount = code.getformalargcount() - arg_list = [Variable() for i in range(formalargcount)] - for position, value in constargs.items(): - arg_list[position] = Constant(value) - frame.setfastscope(arg_list) - self.joinpoints = {} - for joinpoint in code.getjoinpoints(): - self.joinpoints[joinpoint] = [] # list of blocks - initialblock = SpamBlock(FrameState(frame).copy()) - self.pendingblocks = [initialblock] - self.graph = FunctionGraph(name or code.co_name, initialblock) - - def create_frame(self): - # create an empty frame suitable for the code object - # while ignoring any operation like the creation of the locals dict - self.crnt_ops = [] - return self.code.create_frame(self.space, self.w_globals, - self.closure) - - def bytecode_trace(self, frame): - if not isinstance(self.crnt_ops, list): - return - next_instr = frame.next_instr - self.crnt_offset = next_instr # save offset for opcode - if next_instr in self.joinpoints: - currentstate = FrameState(frame) - # can 'currentstate' be merged with one of the blocks that - # already exist for this bytecode position? - for block in self.joinpoints[next_instr]: - newstate = block.framestate.union(currentstate) - if newstate is not None: - # yes - finished = newstate == block.framestate - break - else: - # no - newstate = currentstate.copy() - finished = False - block = None - - if finished: - newblock = block - else: - newblock = SpamBlock(newstate) - # unconditionally link the current block to the newblock - outputargs = currentstate.getoutputargs(newstate) - self.crnt_block.closeblock(Link(outputargs, newblock)) - # phew - if finished: - raise ExitFrame(None) - if block is not None and block.exits: - # to simplify the graph, we patch the old block to point - # directly at the new block which is its generalization - block.dead = True - block.operations = () - block.exitswitch = None - outputargs = block.framestate.getoutputargs(newstate) - block.recloseblock(Link(outputargs, newblock)) - newblock.patchframe(frame, self) - self.joinpoints[next_instr].insert(0, newblock) - - def guessbool(self, w_condition, cases=[False,True], - replace_last_variable_except_in_first_case = None): - if isinstance(self.crnt_ops, list): - block = self.crnt_block - vars = vars2 = block.getvariables() - links = [] - for case in cases: - egg = EggBlock(vars2, block, case) - self.pendingblocks.append(egg) - link = Link(vars, egg, case) - links.append(link) - if replace_last_variable_except_in_first_case is not None: - assert block.operations[-1].result is vars[-1] - vars = vars[:-1] - vars.extend(replace_last_variable_except_in_first_case) - vars2 = vars2[:-1] - while len(vars2) < len(vars): - vars2.append(Variable()) - replace_last_variable_except_in_first_case = None - block.exitswitch = w_condition - block.closeblock(*links) - # forked the graph. Note that False comes before True by default - # in the exits tuple so that (just in case we need it) we - # actually have block.exits[False] = elseLink and - # block.exits[True] = ifLink. - raise ExitFrame(None) - if isinstance(self.crnt_ops, ReplayList): - replaylist = self.crnt_ops - assert replaylist.finished() - self.crnt_block = replaylist.nextblock - self.crnt_ops = replaylist.nextreplaylist - return replaylist.booloutcome - raise AssertionError, "concrete mode: cannot guessbool(%s)" % ( - w_condition,) - - def guessexception(self, *classes): - outcome = self.guessbool(Constant(last_exception), - cases = [None] + list(classes), - replace_last_variable_except_in_first_case = [ - Constant(last_exception), # exc. class - Constant(last_exc_value)]) # exc. value - if outcome is None: - w_exc_cls, w_exc_value = None, None - else: - w_exc_cls, w_exc_value = self.crnt_block.inputargs[-2:] - return outcome, w_exc_cls, w_exc_value - - def build_flow(self): - from pypy.objspace.flow.objspace import UnwrapException - while self.pendingblocks: - block = self.pendingblocks.pop(0) - frame = self.create_frame() - try: - block.patchframe(frame, self) - except ExitFrame: - continue # restarting a dead SpamBlock - try: - w_result = frame.resume() - except OperationError, e: - link = Link([e.w_type, e.w_value], self.graph.exceptblock) - self.crnt_block.closeblock(link) - else: - if w_result is not None: - link = Link([w_result], self.graph.returnblock) - self.crnt_block.closeblock(link) - self.fixeggblocks() - - def fixeggblocks(self): - # EggBlocks reuse the variables of their previous block, - # which is deemed not acceptable for simplicity of the operations - # that will be performed later on the flow graph. - def fixegg(node): - if isinstance(node, EggBlock): - mapping = {} - for a in node.inputargs: - mapping[a] = Variable() - node.renamevariables(mapping) - traverse(fixegg, self.graph) Deleted: /pypy/branch/src-typedunwrap/pypy/objspace/flow/model.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/objspace/flow/model.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,348 +0,0 @@ -# The model produced by the flowobjspace -# this is to be used by the translator mainly. -# -# the below object/attribute model evolved from -# a discussion in Berlin, 4th of october 2003 -from __future__ import generators - -class FunctionGraph: - def __init__(self, name, startblock, return_var=None): - self.name = name # function name (possibly mangled already) - self.startblock = startblock - self.startblock.isstartblock = True - # build default returnblock - self.returnblock = Block([return_var or Variable()]) - self.returnblock.operations = () - self.returnblock.exits = () - # block corresponding to exception results - self.exceptblock = Block([Variable(), # exception class - Variable()]) # exception value - self.exceptblock.operations = () - self.exceptblock.exits = () - - def getargs(self): - return self.startblock.inputargs - - def getreturnvar(self): - return self.returnblock.inputargs[0] - - def hasonlyexceptionreturns(self): - try: - return self._onlyex - except AttributeError: - def visit(link): - if isinstance(link, Link): - if link.target == self.returnblock: - raise ValueError(link) - try: - traverse(visit, self) - except ValueError: - self._onlyex = False - else: - self._onlyex = True - return self._onlyex - - def show(self): - from pypy.translator.tool.graphpage import SingleGraphPage - SingleGraphPage(self).display() - -class Link: - def __init__(self, args, target, exitcase=None): - assert len(args) == len(target.inputargs), "output args mismatch" - self.args = list(args) # mixed list of var/const - self.target = target # block - self.exitcase = exitcase # this is a concrete value - self.prevblock = None # the block this Link is an exit of - - def __repr__(self): - return "link from %s to %s" % (str(self.prevblock), str(self.target)) - -class Block: - isstartblock = False - - def __init__(self, inputargs): - self.inputargs = list(inputargs) # mixed list of variable/const - self.operations = [] # list of SpaceOperation(s) - self.exitswitch = None # a variable or - # Constant(last_exception), see below - self.exits = [] # list of Link(s) - - def __str__(self): - if self.operations: - txt = "block@%d" % self.operations[0].offset - else: - txt = "codeless block" - return txt - - def __repr__(self): - txt = "%s with %d exits" % (str(self), len(self.exits)) - if self.exitswitch: - txt = "%s(%s)" % (txt, self.exitswitch) - return txt - - def getvariables(self): - "Return all variables mentioned in this Block." - result = self.inputargs[:] - for op in self.operations: - result += op.args - result.append(op.result) - return uniqueitems([w for w in result if isinstance(w, Variable)]) - - def getconstants(self): - "Return all constants mentioned in this Block." - result = self.inputargs[:] - for op in self.operations: - result += op.args - return uniqueitems([w for w in result if isinstance(w, Constant)]) - - def renamevariables(self, mapping): - for a in mapping: - assert isinstance(a, Variable), a - self.inputargs = [mapping.get(a, a) for a in self.inputargs] - for op in self.operations: - op.args = [mapping.get(a, a) for a in op.args] - op.result = mapping.get(op.result, op.result) - for link in self.exits: - link.args = [mapping.get(a, a) for a in link.args] - - def closeblock(self, *exits): - assert self.exits == [], "block already closed" - self.recloseblock(*exits) - - def recloseblock(self, *exits): - for exit in exits: - exit.prevblock = self - self.exits = exits - - -class Variable: - counter = 0 - instances = {} - def __init__(self, name=None): - if name is None: - name = 'v%d' % Variable.counter - Variable.counter += 1 - self.name = name - Variable.instances[name] = self - def __repr__(self): - return '%s' % self.name - -class Constant: - def __init__(self, value): - self.value = value # a concrete value - # try to be smart about constant mutable or immutable values - key = type(self.value), self.value # to avoid confusing e.g. 0 and 0.0 - try: - hash(key) - except TypeError: - key = id(self.value) - self.key = key - - def __eq__(self, other): - return self.__class__ is other.__class__ and self.key == other.key - - def __ne__(self, other): - return not (self == other) - - def __hash__(self): - return hash(self.key) - - def __repr__(self): - # try to limit the size of the repr to make it more readable - r = repr(self.value) - if (r.startswith('<') and r.endswith('>') and - hasattr(self.value, '__name__')): - r = '%s %s' % (type(self.value).__name__, self.value.__name__) - elif len(r) > 60 or (len(r) > 30 and type(self.value) is not str): - r = r[:20] + '...' + r[-8:] - return '(%s)' % r - -# hack! it is useful to have UNDEFINED be an instance of Constant too. -# PyFrame then automatically uses this Constant as a marker for -# non-initialized variables. -from pypy.interpreter.eval import UNDEFINED -UndefinedConstant = UNDEFINED.__class__ -UndefinedConstant.__bases__ += (Constant,) -Constant.__init__(UNDEFINED, None) - -class SpaceOperation: - def __init__(self, opname, args, result): - self.opname = opname # operation name - self.args = list(args) # mixed list of var/const - self.result = result # either Variable or Constant instance - self.offset = -1 # offset in code string, to be added later - - def __eq__(self, other): - return (self.__class__ is other.__class__ and - self.opname == other.opname and - self.args == other.args and - self.result == other.result) - - def __ne__(self, other): - return not (self == other) - - def __hash__(self): - return hash((self.opname,tuple(self.args),self.result)) - - def __repr__(self): - return "%r = %s(%s)" % (self.result, self.opname, ", ".join(map(repr, self.args))) - -class Atom: - "NOT_RPYTHON" - def __init__(self, name): - self.name = name - def __repr__(self): - return self.name -last_exception = Atom('last_exception') -last_exc_value = Atom('last_exc_value') -# if Block().exitswitch == Constant(last_exception), it means that we are -# interested in catching the exception that the *last operation* of the -# block could raise. The exitcases of the links are None for no exception -# or XxxError classes to catch the matching exceptions. - -def uniqueitems(lst): - "Returns a list with duplicate elements removed." - result = [] - seen = {} - for item in lst: - if item not in seen: - result.append(item) - seen[item] = True - return result - - -#_________________________________________________________ -# a visitor for easy traversal of the above model - -import inspect # for getmro - -class traverse: - edgedef = { - FunctionGraph : ('startblock',), - Block : ('exits',), - Link : ('target',), - } - - def __init__(self, visitor, functiongraph): - """ send the visitor over all (reachable) nodes. - the visitor needs to have either callable attributes 'visit_typename' - or otherwise is callable itself. - """ - self.visitor = visitor - self.seen = {} - self.visit(functiongraph) - - def visit(self, node): - if id(node) in self.seen: - return - - # do the visit - cls = node.__class__ - for subclass in inspect.getmro(cls): - consume = getattr(self.visitor, "visit_" + subclass.__name__, None) - if consume: - break - else: - consume = getattr(self.visitor, 'visit', self.visitor) - - assert callable(consume), "visitor not found for %r on %r" % (cls, self.visitor) - self.seen[id(node)] = consume(node) - - # recurse - for dispclass, attrs in self.edgedef.items(): - for subclass in inspect.getmro(cls): - if subclass == dispclass: - for attr in attrs: - for obj in flattenobj(getattr(node, attr)): - self.visit(obj) - return - - raise ValueError, "could not dispatch %r" % cls - -def flatten(funcgraph): - l = [] - traverse(l.append, funcgraph) - return l - -def flattenobj(*args): - for arg in args: - try: - for atom in flattenobj(*arg): - yield atom - except: yield arg - -def mkentrymap(funcgraph): - "Returns a dict mapping Blocks to lists of Links." - startlink = Link(funcgraph.getargs(), funcgraph.startblock) - result = {funcgraph.startblock: [startlink]} - def visit(link): - if isinstance(link, Link): - lst = result.setdefault(link.target, []) - lst.append(link) - traverse(visit, funcgraph) - return result - -def checkgraph(graph): - "Check the consistency of a flow graph." - if __debug__: - this_block = [None] - exitblocks = {graph.returnblock: 1, # retval - graph.exceptblock: 2} # exc_cls, exc_value - - def visit(block): - if isinstance(block, Block): - this_block[0] = block - assert bool(block.isstartblock) == (block is graph.startblock) - if not block.exits: - assert block in exitblocks - vars = {} - resultvars = [op.result for op in block.operations] - for v in block.inputargs + resultvars: - assert isinstance(v, Variable) - assert v not in vars, "duplicate variable %r" % (v,) - assert v not in vars_previous_blocks, ( - "variable %r used in more than one block" % (v,)) - vars[v] = True - for op in block.operations: - for v in op.args: - assert isinstance(v, (Constant, Variable)) - if isinstance(v, Variable): - assert v in vars - if block.exitswitch is None: - assert len(block.exits) <= 1 - if block.exits: - assert block.exits[0].exitcase is None - elif block.exitswitch == Constant(last_exception): - assert len(block.operations) >= 1 - assert len(block.exits) >= 1 - assert block.exits[0].exitcase is None - for link in block.exits[1:]: - assert issubclass(link.exitcase, Exception) - else: - assert isinstance(block.exitswitch, Variable) - assert block.exitswitch in vars - for link in block.exits: - assert len(link.args) == len(link.target.inputargs) - assert link.prevblock is block - for v in link.args: - assert isinstance(v, (Constant, Variable)) - if isinstance(v, Variable): - assert v in vars - vars_previous_blocks.update(vars) - - try: - for block, nbargs in exitblocks.items(): - this_block[0] = block - assert len(block.inputargs) == nbargs - assert not block.operations - assert not block.exits - - vars_previous_blocks = {} - - traverse(visit, graph) - - except AssertionError, e: - # hack for debug tools only - if this_block[0] and not hasattr(e, '__annotator_block'): - setattr(e, '__annotator_block', this_block[0]) - raise Deleted: /pypy/branch/src-typedunwrap/pypy/tool/tb_server/render.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/tool/tb_server/render.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,127 +0,0 @@ -from pypy.tool.tb_server.server import TBRequestHandler -from xpy import html, xml - -from py.magic import dyncode - -import traceback -import cgi -import urllib - -views = TBRequestHandler.views - -class URL(object): - attrs='scm','netloc','path','params','query','fragment' - attrindex = dict(zip(attrs, range(len(attrs)))) - # XXX authentication part is not parsed - - def __init__(self, string='', **kw): - from urlparse import urlparse - for name,value in zip(self.attrs, urlparse(string, 'http')): - setattr(self, name, value) - self.__dict__.update(kw) - self.query = cgi.parse_qs(self.query) - - def link_with_options(self, kw): - nq = {} - for k in self.query: - nq[k] = self.query[k][0] - nq.update(kw) - query = urllib.urlencode(nq) - from urlparse import urlunparse - return urlunparse(('', self.netloc, self.path, - self.params, query, self.fragment)) - -class Renderer: - def render(self, path): - url = URL(path) - args = url.path.split('/')[2:] - try: - inner = self.render_self(url, args) - except: - import sys, traceback - lines = traceback.format_exception(*sys.exc_info()) - inner = html.pre( - xml.escape(''.join( - ['Internal Rendering Error, traceback follows\n'] + lines))) - - tag = html.html( - html.head(), - html.body( - inner - ) - ) - return tag.to_unicode() - - -class TracebackView(Renderer): - def __init__(self, exc): - self.name = 'traceback%d' % len(views) - views[self.name] = self - self.exc = exc - - def render_self(self, url, args): - lines = html.div() - opts = {} - for k in url.query: - ent, opt = k.split(':') - val = int(url.query[k][0]) - opts.setdefault(ent, {})[opt] = val - - i = 0 - for tb in dyncode.listtb(self.exc[2]): - lines.append(self.render_tb(url, tb, i, - **opts.get('entry' + str(i), {}))) - i += 1 - - lines.append(html.pre(xml.escape( - ''.join(traceback.format_exception_only(self.exc[0], self.exc[1]))))) - return lines - - def render_tb(self, url, tb, i, showlocals=0): - lines = html.pre() - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - name = tb.tb_frame.f_code.co_name - link = '/file' + filename + '?line=' + str(lineno) + '#' + str(lineno) - lines.append(' File "%s", line %d, in %s\n'%( - html.a(filename, href=link).to_unicode().encode('utf-8'), - lineno, name)) - lines.append(html.a('locals', href=url.link_with_options( - {'entry%s:showlocals'%i:1-showlocals}))) - lines.append(' ' + - dyncode.getline(filename, lineno).lstrip()) - if showlocals: - for k, v in tb.tb_frame.f_locals.items(): - if k[0] == '_': - continue - lines.append(xml.escape('%s=%s\n'%(k, repr(v)[:1000]))) - return lines - - -def ln(lineno): - return html.a(name=str(lineno)) - -class FileSystemView(Renderer): - def render_self(self, url, args): - fname = '/' + '/'.join(args) - lines = html.table() - i = 1 - hilite = int(url.query.get('line', [-1])[0]) - for line in open(fname): - if i == hilite: - kws = {'style': 'font-weight: bold;'} - else: - kws = {} - row = html.tr( - html.td(html.a("%03d" % i, name=str(i))), - html.td( - html.pre(xml.escape(line)[:-1], - **kws), - ), - ) - lines.append(row) - i += 1 - return lines - -views['file'] = FileSystemView() - Deleted: /pypy/branch/src-typedunwrap/pypy/tool/tb_server/server.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/tool/tb_server/server.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,96 +0,0 @@ -from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer -import threading -import sys - -server_thread = None -server_port = None - -class TBRequestHandler(BaseHTTPRequestHandler): - views = {} - - def do_GET(self): - if self.path == '/quit': - global server_thread - server_thread = None - raise SystemExit - i = self.path.find('/', 1) - parts = self.path[1:].split('/', 1) - if not parts: - tp_name = 'traceback' - else: - tb_name = parts[0] - if not self.views.has_key(tb_name): - self.send_response(404) - self.send_header("Content-Type", "text/plain") - self.end_headers() - self.wfile.write('traceback named %r not found' % tb_name) - else: - tbview = self.views[tb_name] - s = tbview.render(self.path) - self.send_response(200) - self.send_header("Content-Type", "text/html; charset=utf-8") - self.end_headers() - self.wfile.write(unicode(s).encode('utf8')) - - def log_message(self, format, *args): - pass - -class TBServer(HTTPServer): - def handle_error(self, request, client_address): - exc = sys.exc_info()[1] - if isinstance(exc, (SystemExit, KeyboardInterrupt)): - raise - else: - HTTPServer.handle_error(self, request, client_address) - -def serve(): - import socket - port = 8080 - while 1: - try: - server = TBServer(('localhost', port), TBRequestHandler) - except socket.error: - port += 1 - continue - else: - break - global server_port - server_port = port - print "serving on", port - server.serve_forever() - -def start(): - global server_thread - server_thread = threading.Thread(target=serve) - server_thread.start() - return server_thread - -def stop(): - if server_thread is None: - return - import urllib2 - try: - urllib2.urlopen('http://localhost:%s/quit'%(server_port,)) - except urllib2.HTTPError: - pass - -def wait_until_interrupt(): - if server_thread is None: - return - print "waiting" - import signal - try: - signal.pause() - except KeyboardInterrupt: - stop() - -def publish_exc(exc): - if server_thread is None: - return - from pypy.tool.tb_server.render import TracebackView - x = TracebackView(exc) - print "traceback is at http://localhost:%d/%s" % (server_port, x.name) - -if __name__ == "__main__": - t = main() - wait_until_interrupt() Deleted: /pypy/branch/src-typedunwrap/pypy/translator/java/PyList.java ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/java/PyList.java Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,74 +0,0 @@ - - -class PyList extends PySequence { - - PyList(PyObject[] x) { - super(x); - } - - PyObject op_setitem(PyObject index, PyObject o) { - if (index instanceof PyInt) { - int i = ((PyInt) index).intval; - items[i] = o; - return null; - } - throw new TypeError(); - } - - PyObject op_add(PyObject other) { - if (other instanceof PyList) { - PyObject[] items2 = ((PyList) other).items; - PyObject[] nitems = new PyObject[items.length + items2.length]; - System.arraycopy(items, 0, nitems, 0, items.length); - System.arraycopy(items2, 0, nitems, items.length, items2.length); - return new PyList(nitems); - } - throw new TypeError(); - } - - PyObject op_inplace_add(PyObject other) { - if (other instanceof PySequence) { - PyObject[] items2 = ((PySequence) other).items; - PyObject[] nitems = new PyObject[items.length + items2.length]; - System.arraycopy(items, 0, nitems, 0, items.length); - System.arraycopy(items2, 0, nitems, items.length, items2.length); - items = nitems; - return this; - } - throw new TypeError(); - } - - PyObject op_mul(PyObject other) { - if (items.length == 1 && other instanceof PyInt) { - int i, count = ((PyInt) other).intval; - PyObject item = items[0]; - PyObject[] nitems = new PyObject[count]; - for (i=0; i> f, 'class test extends PyObject {' - print >> f, ' static public void main(String[] argv) {' - print >> f, ' PyObject result = %s.op_call_%d(%s);' % ( - entrypoint, len(inputargs), - ', '.join([self.nameof(x) for x in inputargs])) - print >> f, ' if (result.eq(%s))' % ( - self.nameof(expectedresult),) - print >> f, ' System.out.println("OK");' - print >> f, ' else' - print >> f, ' System.out.println("FAIL");' - print >> f, ' }' - self.gen_initcode(f) - print >> f, '};' - f.close() - - def nameof(self, obj): - key = Constant(obj).key - try: - return self.javanames[key] - except KeyError: - #name = "w(%s)" % str(obj) - #self.javanames[key] = name - #return name - if (type(obj).__module__ != '__builtin__' and - not isinstance(obj, type)): # skip user-defined metaclasses - # assume it's a user defined thingy - name = self.nameof_instance(obj) - else: - for cls in type(obj).__mro__: - meth = getattr(self, - 'nameof_' + cls.__name__.replace(' ', ''), - None) - if meth: - break - else: - raise Exception, "nameof(%r) in %r" % (obj, self.current_func) - name = meth(obj) - self.javanames[key] = name - return name - - def uniquename(self, basename): - n = self.seennames.get(basename, 0) - self.seennames[basename] = n+1 - if n == 0: - self.globalobjects.append(basename) - self.globaldecl.append('static PyObject *%s;' % (basename,)) - return basename - else: - return self.uniquename('%s_%d' % (basename, n)) - - def nameof_object(self, value): - if type(value) is not object: - raise Exception, "nameof(%r) in %r" % (value, self.current_func) - name = self.uniquename('g_object') - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*)&PyBaseObject_Type, ""))'%name) - return name - - def nameof_module(self, value): - assert value is os or not hasattr(value, "__file__") or \ - not (value.__file__.endswith('.pyc') or - value.__file__.endswith('.py') or - value.__file__.endswith('.pyo')), \ - "%r is not a builtin module (probably :)"%value - name = self.uniquename('mod%s'%value.__name__) - self.initcode.append('INITCHK(%s = PyImport_ImportModule("%s"))'%(name, value.__name__)) - return name - - - def nameof_int(self, value): - return "new PyInt(%d)" % value - - def nameof_long(self, value): - # assume we want them in hex most of the time - if value < 256L: - return "%dL" % value - else: - return "0x%08xL" % value - - def nameof_float(self, value): - return "w(%s)" % value - - def nameof_str(self, value): - return "w(%s)" % repr(value) - - def skipped_function(self, func): - # debugging only! Generates a placeholder for missing functions - # that raises an exception when called. - name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('static PyMethodDef ml_%s = { "%s", &skipped, METH_VARARGS };' % (name, name)) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\tPy_INCREF(%s);' % name) - self.initcode.append('\tPyCFunction_GET_SELF(%s) = %s;' % (name, name)) - return name - - def nameof_function(self, func): - printable_name = '(%s:%d) %s' % ( - func.func_globals.get('__name__', '?'), - func.func_code.co_firstlineno, - func.__name__) - if self.translator.frozen: - if func not in self.translator.flowgraphs: - print "NOT GENERATING", printable_name - return self.skipped_function(func) - else: - if (func.func_doc and - func.func_doc.lstrip().startswith('NOT_RPYTHON')): - print "skipped", printable_name - return self.skipped_function(func) - name = self.uniquename('gfunc_' + func.__name__) - self.initcode.append('static PyObject %s = new C_%s();' % (name, name)) - self.pendingfunctions.append(func) - return name - - def nameof_staticmethod(self, sm): - # XXX XXX XXXX - func = sm.__get__(42.5) - name = self.uniquename('gsm_' + func.__name__) - functionname = self.nameof(func) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, functionname)) - return name - - def nameof_instancemethod(self, meth): - if meth.im_self is None: - # no error checking here - return self.nameof(meth.im_func) - else: - ob = self.nameof(meth.im_self) - func = self.nameof(meth.im_func) - typ = self.nameof(meth.im_class) - name = self.uniquename('gmeth_'+meth.im_func.__name__) - self.initcode.append( - 'INITCHK(%s = gencfunc_descr_get(%s, %s, %s))'%( - name, func, ob, typ)) - return name - - def should_translate_attr(self, pbc, attr): - ann = self.translator.annotator - if ann is None: - ignore = getattr(pbc.__class__, 'NOT_RPYTHON_ATTRIBUTES', []) - if attr in ignore: - return False - else: - return "probably" # True - if attr in ann.getpbcattrs(pbc): - return True - classdef = ann.getuserclasses().get(pbc.__class__) - if (classdef and - classdef.about_attribute(attr) != annmodel.SomeImpossibleValue()): - return True - return False - - def later(self, gen): - self.latercode.append(gen) - - def nameof_instance(self, instance): - name = self.uniquename('ginst_' + instance.__class__.__name__) - cls = self.nameof(instance.__class__) - def initinstance(): - content = instance.__dict__.items() - content.sort() - for key, value in content: - if self.should_translate_attr(instance, key): - yield 'INITCHK(SETUP_INSTANCE_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) - self.initcode.append('INITCHK(SETUP_INSTANCE(%s, %s))' % ( - name, cls)) - self.later(initinstance()) - return name - - def nameof_builtin_function_or_method(self, func): - if func.__self__ is None: - # builtin function - # where does it come from? Python2.2 doesn't have func.__module__ - for modname, module in sys.modules.items(): - if hasattr(module, '__file__'): - if (module.__file__.endswith('.py') or - module.__file__.endswith('.pyc') or - module.__file__.endswith('.pyo')): - continue # skip non-builtin modules - if func is getattr(module, func.__name__, None): - break - else: - raise Exception, '%r not found in any built-in module' % (func,) - name = self.uniquename('gbltin_' + func.__name__) - if modname == '__builtin__': - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - 'PyEval_GetBuiltins(), "%s"))' % ( - name, func.__name__)) - else: - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(module), func.__name__)) - else: - # builtin (bound) method - name = self.uniquename('gbltinmethod_' + func.__name__) - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(func.__self__), func.__name__)) - return name - - def nameof_classobj(self, cls): - if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): - raise Exception, "%r should never be reached" % (cls,) - - metaclass = "&PyType_Type" - if issubclass(cls, Exception): - if cls.__module__ == 'exceptions': - return 'w(%s)'%cls.__name__ - #else: - # # exceptions must be old-style classes (grr!) - # metaclass = "&PyClass_Type" - # For the moment, use old-style classes exactly when the - # pypy source uses old-style classes, to avoid strange problems. - if not isinstance(cls, type): - assert type(cls) is type(Exception) - metaclass = "&PyClass_Type" - - name = self.uniquename('gcls_' + cls.__name__) - basenames = [self.nameof(base) for base in cls.__bases__] - def initclassobj(): - content = cls.__dict__.items() - content.sort() - for key, value in content: - if key.startswith('__'): - if key in ['__module__', '__doc__', '__dict__', - '__weakref__', '__repr__', '__metaclass__']: - continue - # XXX some __NAMES__ are important... nicer solution sought - #raise Exception, "unexpected name %r in class %s"%(key, cls) - if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: - print value - continue - if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: - print value - continue - - yield 'INITCHK(SETUP_CLASS_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) - - baseargs = ", ".join(basenames) - if baseargs: - baseargs = ', '+baseargs - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*) %s,' - %(name, metaclass)) - self.initcode.append('\t\t"s(%s){}", "%s"%s))' - %("O"*len(basenames), cls.__name__, baseargs)) - - self.later(initclassobj()) - return name - - nameof_class = nameof_classobj # for Python 2.2 - - - def nameof_type(self, cls): - return "w(%s)" % cls.__name__ ##?? - if cls in self.typename_mapping: - return '(PyObject*) %s' % self.typename_mapping[cls] - assert cls.__module__ != '__builtin__', \ - "built-in class %r not found in typename_mapping" % (cls,) - return self.nameof_classobj(cls) - - def nameof_tuple(self, tup): - name = self.uniquename('g%dtuple' % len(tup)) - args = [self.nameof(x) for x in tup] - args.insert(0, '%d' % len(tup)) - args = ', '.join(args) - self.initcode.append('INITCHK(%s = PyTuple_Pack(%s))' % (name, args)) - return name - - def nameof_list(self, lis): - name = self.uniquename('g%dlist' % len(lis)) - def initlist(): - for i in range(len(lis)): - item = self.nameof(lis[i]) - yield '\tPy_INCREF(%s);' % item - yield '\tPyList_SET_ITEM(%s, %d, %s);' % (name, i, item) - self.initcode.append('INITCHK(%s = PyList_New(%d))' % (name, len(lis))) - self.later(initlist()) - return name - - def nameof_dict(self, dic): - return 'space.newdict([w("sorry", "not yet"])' - assert dic is not __builtins__ - assert '__builtins__' not in dic, 'Seems to be the globals of %s' % ( - dic.get('__name__', '?'),) - name = self.uniquename('g%ddict' % len(dic)) - def initdict(): - for k in dic: - if type(k) is str: - yield ('\tINITCHK(PyDict_SetItemString' - '(%s, "%s", %s) >= 0)'%( - name, k, self.nameof(dic[k]))) - else: - yield ('\tINITCHK(PyDict_SetItem' - '(%s, %s, %s) >= 0)'%( - name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('INITCHK(%s = PyDict_New())' % (name,)) - self.later(initdict()) - return name - - # strange prebuilt instances below, don't look too closely - # XXX oh well. - def nameof_member_descriptor(self, md): - name = self.uniquename('gdescriptor_%s_%s' % ( - md.__objclass__.__name__, md.__name__)) - cls = self.nameof(md.__objclass__) - self.initcode.append('INITCHK(PyType_Ready((PyTypeObject*) %s) >= 0)' % - cls) - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - '((PyTypeObject*) %s)->tp_dict, "%s"))' % - (name, cls, md.__name__)) - return name - nameof_getset_descriptor = nameof_member_descriptor - nameof_method_descriptor = nameof_member_descriptor - nameof_wrapper_descriptor = nameof_member_descriptor - - def nameof_file(self, fil): - if fil is sys.stdin: - return 'PySys_GetObject("stdin")' - if fil is sys.stdout: - return 'PySys_GetObject("stdout")' - if fil is sys.stderr: - return 'PySys_GetObject("stderr")' - raise Exception, 'Cannot translate an already-open file: %r' % (fil,) - - def gen_source(self): -## info = { -## 'modname': self.modname, -## 'entrypointname': self.translator.functions[0].__name__, -## 'entrypoint': self.nameof(self.translator.functions[0]), -## } - - # function implementations - while self.pendingfunctions: - func = self.current_func = self.pendingfunctions.pop() - self.gen_javafunction(func) - # collect more of the latercode after each function - self.collect_latercode() - #self.gen_global_declarations() - - # copy over the PyXxx classes - mydir = os.path.dirname(__file__) - for fn in os.listdir(mydir): - if fn.lower().endswith('.java'): - g = open(os.path.join(mydir, fn), 'r') - f = self.jdir.join(fn).open('w') - data = g.read() - i = data.find('/* CUT HERE') - if i < 0: - f.write(data) - else: - f.write(data[:i]) - print >> f - print >> f, ' /* call patterns */' - callpatterns = self.callpatterns.items() - callpatterns.sort() - for callpattern, args in callpatterns: - print >> f, (' PyObject %s(%s) { throw new ' - 'TypeError(); }' % (callpattern, args)) - print >> f - self.gen_initcode(f) - print >> f, '};' - f.close() - g.close() - - def collect_latercode(self): - while self.latercode: - gen = self.latercode.pop() - #self.initcode.extend(gen) -- eats TypeError! bad CPython! - for line in gen: - self.initcode.append(line) - - def gen_initcode(self, f): - self.collect_latercode() - print >> f, ' /* init code */' - for line in self.initcode: - print >> f, ' ' + line - print >> f - self.initcode = [] - - def gen_javafunction(self, func): - t = self.translator - #t.simplify(func) - graph = t.getflowgraph(func) - remove_direct_loops(graph) - checkgraph(graph) - - name = self.nameof(func) - f = self.jdir.join('C_%s.java' % name).open('w') - try: - src = graph.source - except AttributeError: - pass - else: - print >> f, '//' - for line in src.rstrip().split('\n'): - print >> f, '// ', line - print >> f, '//' - print >> f - print >> f, 'class C_%s extends PyObject {' % name - print >> f - - def expr(v): - if isinstance(v, Variable): - return v.name - elif isinstance(v, Constant): - return self.nameof(v.value) - else: - raise TypeError, "expr(%r)" % (v,) - - def arglist(args, prefix=''): - res = [prefix + expr(arg) for arg in args] - return ", ".join(res) - - def oper(op): - if op.opname in self.has_listarg: - fmt = "PyObject[] a_%s = {%s}; PyObject %s = new %s(a_%s);" - v = expr(op.result) - return fmt % (v, arglist(op.args), v, - self.has_listarg[op.opname], v) - else: - fmt = "PyObject %s = %s.op_%s(%s);" - return fmt % (expr(op.result), expr(op.args[0]), - op.opname, arglist(op.args[1:])) - - def gen_link(link, linklocalvars={}): - "Generate the code to jump across the given Link." - for a1, a2 in zip(link.args, link.target.inputargs): - if a1 in linklocalvars: - src = linklocalvars[a1] - else: - src = expr(a1) - yield "%s = %s;" % (expr(a2), src) - goto = blocknum[link.target] - if goto == blocknum[block]+1: - yield '// falls through' - else: - yield 'block = %d;' % goto - yield 'continue;' - - start = graph.startblock - blocks = ordered_blocks(graph) - nblocks = len(blocks) - - blocknum = {} - localvars = [] - for block in blocks: - blocknum[block] = len(blocknum)+1 - if block is not start: - localvars += block.inputargs - - # create function declaration - callpattern = "op_call_%d" % len(start.inputargs) - args = arglist(start.inputargs, prefix='PyObject ') - self.callpatterns[callpattern] = args - print >> f, " PyObject %s(%s) {" % (callpattern, args) - for v in localvars: - print >> f, " PyObject %s = null;" % v - print >> f, " int block = %d; // startblock" % blocknum[start] - print >> f, " while (true) switch (block) {" - - def render_block(block): - catch_exception = block.exitswitch == Constant(last_exception) - regular_op = len(block.operations) - catch_exception - # render all but maybe the last op - for op in block.operations[:regular_op]: - yield "%s" % oper(op) - # render the last op if it is exception handled - for op in block.operations[regular_op:]: - yield "try {" - yield " %s" % oper(op) - - if len(block.exits) == 0: - if len(block.inputargs) == 2: # exc_cls, exc_value - # exceptional return block - exc_cls = expr(block.inputargs[0]) - exc_val = expr(block.inputargs[1]) - XXX - yield "raise OperationError(%s, %s)" % (exc_cls, exc_val) - else: - # regular return block - retval = expr(block.inputargs[0]) - yield "return %s;" % retval - return - elif block.exitswitch is None: - # single-exit block - assert len(block.exits) == 1 - for op in gen_link(block.exits[0]): - yield "%s" % op - elif catch_exception: - XXX - # block catching the exceptions raised by its last operation - # we handle the non-exceptional case first - link = block.exits[0] - assert link.exitcase is None - for op in gen_link(link): - yield " %s" % op - # we must catch the exception raised by the last operation, - # which goes to the last err%d_%d label written above. - for link in block.exits[1:]: - assert issubclass(link.exitcase, Exception) - yield "except OperationError, e:" - print "*"*10, link.exitcase - for op in gen_link(link, { - Constant(last_exception): 'e.w_type', - Constant(last_exc_value): 'e.w_value'}): - yield " %s" % op - else: - # block ending in a switch on a value - exits = list(block.exits) - if len(exits) == 2 and ( - exits[0].exitcase is False and exits[1].exitcase is True): - # order these guys like Python does - exits.reverse() - q = "if" - for link in exits[:-1]: - yield "%s (%s.eq(%s)) {" % (q, expr(block.exitswitch), - self.nameof(link.exitcase)) - for op in gen_link(link): - yield " %s" % op - yield "}" - q = "else if" - link = exits[-1] - yield "else {" - yield " // assert %s.eq(%s)" % (expr(block.exitswitch), - self.nameof(link.exitcase)) - for op in gen_link(exits[-1]): - yield " %s" % op - yield "}" - - for block in blocks: - blockno = blocknum[block] - print >> f - print >> f, " case %d:" % blockno - for line in render_block(block): - print >> f, " %s" % line - - print >> f, " }" - print >> f, " }" - print >> f - print >> f, "};" - f.close() Deleted: /pypy/branch/src-typedunwrap/pypy/translator/java/test/test_javatrans.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/java/test/test_javatrans.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,48 +0,0 @@ -import autopath, os -from py.process import cmdexec -from pypy.tool.udir import udir -from pypy.translator.java.genjava import GenJava -from pypy.translator.test import snippet -from pypy.translator.translator import Translator - - -class TestNoTypeCGenTestCase: - - objspacename = 'flow' - - def build_jfunc(self, func): - try: func = func.im_func - except AttributeError: pass - t = Translator(func) - t.simplify() - name = func.func_name - self.jdir = udir.mkdir(name) - self.gen = GenJava(self.jdir, t) - - def check(self, inputargs, expectedresult): - self.gen.gen_test_class(inputargs, expectedresult) - cwd = os.getcwd() - try: - os.chdir(str(self.jdir)) - cmdexec('javac *.java') - assert cmdexec('java test').strip() == 'OK' - finally: - os.chdir(cwd) - - def test_simple_func(self): - self.build_jfunc(snippet.simple_func) - self.check([123], 124) - - def test_if_then_else(self): - self.build_jfunc(snippet.if_then_else) - self.check([2,3,4], 3) - self.check([0,3,4], 4) - self.check([-1,3,4], 3) - - def test_two_plus_two(self): - self.build_jfunc(snippet.two_plus_two) - self.check([], 4) - - def test_sieve_of_eratosthenes(self): - self.build_jfunc(snippet.sieve_of_eratosthenes) - self.check([], 1028) Deleted: /pypy/branch/src-typedunwrap/pypy/translator/test/test_cltrans.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/test/test_cltrans.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,132 +0,0 @@ -import autopath -from pypy.tool.udir import udir -import py -import os - -def get_cl(): - cl = os.getenv("PYPY_CL") - if cl: return cl - cl = cl_detect() - if cl: return cl - return None - -def cl_detect(): - if is_on_path("clisp"): - return "clisp" - if is_on_path("lisp"): - if is_on_path("cmuclinvoke.sh"): - return "cmuclinvoke.sh" - if is_on_path("sbcl"): - if is_on_path("sbclinvoke.sh"): - return "sbclinvoke.sh" - return None - -def is_on_path(name): - try: - return os.system("which %s >/dev/null 2>/dev/null" % name) == 0 - except OSError: - pass - -global_cl = get_cl() - -def make_cl_func(func, argtypes=[]): - from pypy.translator.tool.buildcl import _make_cl_func - return _make_cl_func(func, global_cl, udir, argtypes) - - -from pypy.translator.test import snippet as t -from pypy.translator.tool.buildcl import Literal - -class TestGenCLTestCase: - - objspacename = 'flow' - - def setup_method(self,method): - if not global_cl: - py.test.skip("Common Lisp neither configured nor detected.") - - def test_if(self): - cl_if = make_cl_func(t.if_then_else) - assert cl_if(True, 50, 100) == 50 - assert cl_if(False, 50, 100) == 100 - assert cl_if(0, 50, 100) == 100 - assert cl_if(1, 50, 100) == 50 - assert cl_if([], 50, 100) == 100 - assert cl_if([[]], 50, 100) == 50 - - def test_gcd(self): - cl_gcd = make_cl_func(t.my_gcd, [int, int]) - assert cl_gcd(96, 64) == 32 - - def test_is_perfect(self): # pun intended - cl_perfect = make_cl_func(t.is_perfect_number, [int]) - assert cl_perfect(24) == False - assert cl_perfect(28) == True - - def test_bool(self): - cl_bool = make_cl_func(t.my_bool) - assert cl_bool(0) == False - assert cl_bool(42) == True - assert cl_bool(True) == True - - def test_array(self): - cl_four = make_cl_func(t.two_plus_two) - assert cl_four() == 4 - - def test_sieve(self): - cl_sieve = make_cl_func(t.sieve_of_eratosthenes) - assert cl_sieve() == 1028 - - def test_easy(self): - # These are the Pyrex tests which were easy to adopt. - f1 = make_cl_func(t.simple_func, [int]) - assert f1(1) == 2 - f2 = make_cl_func(t.while_func, [int]) - assert f2(10) == 55 - f3 = make_cl_func(t.simple_id) - assert f3(9) == 9 - f4 = make_cl_func(t.branch_id) - assert f4(1, 2, 3) == 2 - assert f4(0, 2, 3) == 3 - f5 = make_cl_func(t.int_id, [int]) - assert f5(3) == 3 - f6 = make_cl_func(t.time_waster, [int]) - assert f6(30) == 3657 - - def test_string(self): - cl_greet = make_cl_func(t.greet, [str]) - assert cl_greet("world") == "helloworld" - cl_stringmaker = make_cl_func(t.nested_whiles, [int, int]) - assert cl_stringmaker(111, 114) == ( - "...!...!...!...!...!") - - def test_for(self): - cl_python = make_cl_func(t.choose_last) - assert cl_python() == "python" - - def test_builtin(self): - cl_builtinusage = make_cl_func(t.builtinusage) - assert cl_builtinusage() == 4 - - def test_slice(self): - cl_half = make_cl_func(t.half_of_n, [int]) - assert cl_half(10) == 5 - - def test_powerset(self): - cl_powerset = make_cl_func(t.powerset, [int]) - result = cl_powerset(3) - assert result.__class__ == Literal - assert result.val == ( - '#(#() #(0) #(1) #(0 1) #(2) #(0 2) #(1 2) #(0 1 2))') - def test_yast(self): - cl_sum = make_cl_func(t.yast) # yet another sum test - assert cl_sum(range(12)) == 66 - - -# TODO -# poor_man_range -# - append/reverse. not RPython. delegate? -# attrs -# - attribute. need object. symbol-plist? -# yast -# - need way to specify that argument is list of int. Deleted: /pypy/branch/src-typedunwrap/pypy/translator/test/test_ctrans.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/test/test_ctrans.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,285 +0,0 @@ -import autopath -from pypy.tool.udir import udir -from pypy.translator.genc import GenC -from pypy.objspace.flow.model import * -from pypy.translator.tool.buildpyxmodule import make_module_from_c -from pypy.translator.translator import Translator - -from pypy.translator.test import snippet - -# XXX this tries to make compiling faster for full-scale testing -from pypy.translator.tool import buildpyxmodule -buildpyxmodule.enable_fast_compilation() - - -class TestNoTypeCGenTestCase: - - objspacename = 'flow' - - def build_cfunc(self, func): - try: func = func.im_func - except AttributeError: pass - t = Translator(func) - t.simplify() - return t.ccompile() - - def test_simple_func(self): - cfunc = self.build_cfunc(snippet.simple_func) - assert cfunc(1) == 2 - - def test_while_func(self): - while_func = self.build_cfunc(snippet.while_func) - assert while_func(10) == 55 - - def test_nested_whiles(self): - nested_whiles = self.build_cfunc(snippet.nested_whiles) - assert nested_whiles(111, 114) == ( - '...!...!...!...!...!') - - def test_poor_man_range(self): - poor_man_range = self.build_cfunc(snippet.poor_man_range) - assert poor_man_range(10) == range(10) - - def poor_man_rev_range(self): - poor_man_rev_range = self.build_cfunc(snippet.poor_man_rev_range) - assert poor_man_rev_range(10) == range(9,-1,-1) - - def test_simple_id(self): - #we just want to see, if renaming of parameter works correctly - #if the first branch is the end branch - simple_id = self.build_cfunc(snippet.simple_id) - assert simple_id(9) == 9 - - def test_branch_id(self): - branch_id = self.build_cfunc(snippet.branch_id) - assert branch_id(1, 2, 3) == 2 - assert branch_id(0, 2, 3) == 3 - - def test_int_id(self): - int_id = self.build_cfunc(snippet.int_id) - assert int_id(3) == 3 - - def dont_test_attrs(self): - attrs = self.build_cfunc(snippet.attrs) - assert attrs() == 9 - - def test_builtinusage(self): - fun = self.build_cfunc(snippet.builtinusage) - assert fun() == 4 - - def test_sieve(self): - sieve = self.build_cfunc(snippet.sieve_of_eratosthenes) - assert sieve() == 1028 - - def test_slice(self): - half = self.build_cfunc(snippet.half_of_n) - assert half(10) == 5 - - def test_poly_branch(self): - poly_branch = self.build_cfunc(snippet.poly_branch) - assert poly_branch(10) == [1,2,3]*2 - assert poly_branch(0) == ['a','b','c']*2 - - def test_and(self): - sand = self.build_cfunc(snippet.s_and) - assert sand(5, 6) == "yes" - assert sand(5, 0) == "no" - assert sand(0, 6) == "no" - assert sand(0, 0) == "no" - - def test_yast(self): - yast = self.build_cfunc(snippet.yast) - assert yast([1000,100,10,1]) == 1111 - assert yast(range(100)) == (99*100)/2 - - def test_with_init(self): - with_init = self.build_cfunc(snippet.with_init) - assert with_init(0) == 0 - assert with_init(-100) == -100 - - def test_with_more_init(self): - with_more_init = self.build_cfunc(snippet.with_more_init) - assert with_more_init(10, False) == -10 - assert with_more_init(20, True) == 20 - - def test_global_instance(self): - global_instance = self.build_cfunc(snippet.global_instance) - assert global_instance() == 42 - - def test_global_newstyle_instance(self): - global_newstyle_instance = self.build_cfunc(snippet.global_newstyle_instance) - assert global_newstyle_instance().a == 1 - - def test_global_recursive_list(self): - global_recursive_list = self.build_cfunc(snippet.global_recursive_list) - lst = global_recursive_list() - assert len(lst) == 1 - assert lst[0] is lst - -## def test_global_badinit(self): -## global_badinit = self.build_cfunc(snippet.global_badinit) -## self.assertEquals(global_badinit(), 1) - - def test_multiple_inheritance(self): - multiple_inheritance = self.build_cfunc(snippet.multiple_inheritance) - assert multiple_inheritance() == 1+2+3+4 - - def test_call_star_args(self): - call_star_args = self.build_cfunc(snippet.call_star_args) - assert call_star_args(42) == 52 - - def test_call_default_args(self): - call_default_args = self.build_cfunc(snippet.call_default_args) - assert call_default_args(42) == 111+42+3 - - def test_call_default_and_star_args(self): - call_default_and_star_args = self.build_cfunc( - snippet.call_default_and_star_args) - assert call_default_and_star_args(42) == ( - (111+42+3+0, -1000-2000-3000+2)) - - def test_call_with_star(self): - call_with_star = self.build_cfunc(snippet.call_with_star) - assert call_with_star(()) == -15L - assert call_with_star((4,)) == -13L - assert call_with_star((4,7)) == -9L - assert call_with_star([]) == -15L - assert call_with_star([4]) == -13L - assert call_with_star([4,7]) == -9L - raises(TypeError, call_with_star, (4,7,12)) - raises(TypeError, call_with_star, [4,7,12,63]) - raises(TypeError, call_with_star, 521) - - def test_call_with_keyword(self): - call_with_keyword = self.build_cfunc(snippet.call_with_keyword) - assert call_with_keyword(100) == 82 - - def test_finallys(self): - finallys = self.build_cfunc(snippet.finallys) - assert finallys(['hello']) == 8 - assert finallys('X') == 8 - assert finallys([]) == 6 - assert finallys('XY') == 6 - - def test_finally2(self): - finally2 = self.build_cfunc(snippet.finally2) - lst = range(10) - finally2(lst, 5) - assert lst == [0,1,2,3,4, 6, 6,7,8, 'done'] - dic = {} - raises(KeyError, finally2, dic, "won't find this key") - assert dic == {-1: 'done'} - - def test_bare_raise(self): - bare_raise = self.build_cfunc(snippet.bare_raise) - assert bare_raise(range(0, 100, 10), False) == 50 - assert bare_raise(range(0, 100, 10), True) == 50 - raises(IndexError, bare_raise, range(0, 30, 10), False) - assert bare_raise(range(0, 30, 10), True) == None - - def test_get_set_del_slice(self): - fn = self.build_cfunc(snippet.get_set_del_slice) - l = list('abcdefghij') - result = fn(l) - assert l == [3, 'c', 8, 11, 'h', 9] - assert result == ([3, 'c'], [9], [11, 'h']) - -class TestTypedTestCase: - - def getcompiled(self, func): - t = Translator(func, simplifying=True) - # builds starting-types from func_defs - argstypelist = [] - 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 - argstypelist.append(spec) - a = t.annotate(argstypelist) - a.simplify() - return t.ccompile() - - def test_set_attr(self): - set_attr = self.getcompiled(snippet.set_attr) - assert set_attr() == 2 - - def test_inheritance2(self): - inheritance2 = self.getcompiled(snippet.inheritance2) - assert inheritance2() == ((-12, -12), (3, "world")) - - def test_factorial2(self): - factorial2 = self.getcompiled(snippet.factorial2) - assert factorial2(5) == 120 - - def test_factorial(self): - factorial = self.getcompiled(snippet.factorial) - assert factorial(5) == 120 - - def test_simple_method(self): - simple_method = self.getcompiled(snippet.simple_method) - assert simple_method(55) == 55 - - def test_sieve_of_eratosthenes(self): - sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes) - assert sieve_of_eratosthenes() == 1028 - - def test_nested_whiles(self): - nested_whiles = self.getcompiled(snippet.nested_whiles) - assert nested_whiles(5,3) == '!!!!!' - - def test_call_five(self): - call_five = self.getcompiled(snippet.call_five) - 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) - result = call_unpack_56() - assert result == (2, 5, 6) - - def test_class_defaultattr(self): - class K: - n = "hello" - def class_defaultattr(): - k = K() - k.n += " world" - return k.n - fn = self.getcompiled(class_defaultattr) - assert fn() == "hello world" - - def test_tuple_repr(self): - def tuple_repr(x=int, y=object): - z = x, y - while x: - x = x-1 - return z - fn = self.getcompiled(tuple_repr) - assert fn(6,'a') == (6,'a') - - def test_classattribute(self): - fn = self.getcompiled(snippet.classattribute) - assert fn(1) == 123 - assert fn(2) == 456 - assert fn(3) == 789 - assert fn(4) == 789 - assert fn(5) == 101112 - - def test_get_set_del_slice(self): - fn = self.getcompiled(snippet.get_set_del_slice) - 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=int): - 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') Deleted: /pypy/branch/src-typedunwrap/pypy/translator/test/test_pyrextrans.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/test/test_pyrextrans.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,140 +0,0 @@ -import autopath -import py -from pypy.tool.udir import udir -from pypy.translator.genpyrex import GenPyrex -from pypy.objspace.flow.model import * -from pypy.translator.tool.buildpyxmodule import build_cfunc -from pypy.translator.translator import Translator - -from pypy.translator.test import snippet - -# XXX this tries to make compiling faster for full-scale testing -from pypy.translator.tool import buildpyxmodule -buildpyxmodule.enable_fast_compilation() - - -class TestNoTypePyrexGenTestCase: - - objspacename = 'flow' - - def build_cfunc(self, func): - try: func = func.im_func - except AttributeError: pass - - dot = py.test.config.option.verbose >0 and 1 or 0 - options = { - 'simplify' : 1, - 'dot' : dot, - } - return build_cfunc(func, **options) - - def test_simple_func(self): - cfunc = self.build_cfunc(snippet.simple_func) - assert cfunc(1) == 2 - - def test_while_func(self): - while_func = self.build_cfunc(snippet.while_func) - assert while_func(10) == 55 - - def test_nested_whiles(self): - nested_whiles = self.build_cfunc(snippet.nested_whiles) - assert nested_whiles(111, 114) == ( - '...!...!...!...!...!') - - def test_poor_man_range(self): - poor_man_range = self.build_cfunc(snippet.poor_man_range) - assert poor_man_range(10) == range(10) - - def poor_man_rev_range(self): - poor_man_rev_range = self.build_cfunc(snippet.poor_man_rev_range) - assert poor_man_rev_range(10) == range(9,-1,-1) - - def test_simple_id(self): - #we just want to see, if renaming of parameter works correctly - #if the first branch is the end branch - simple_id = self.build_cfunc(snippet.simple_id) - assert simple_id(9) == 9 - - def test_branch_id(self): - branch_id = self.build_cfunc(snippet.branch_id) - assert branch_id(1, 2, 3) == 2 - assert branch_id(0, 2, 3) == 3 - - def test_int_id(self): - int_id = self.build_cfunc(snippet.int_id) - assert int_id(3) == 3 - - def dont_test_attrs(self): - attrs = self.build_cfunc(snippet.attrs) - assert attrs() == 9 - - def test_builtinusage(self): - fun = self.build_cfunc(snippet.builtinusage) - assert fun() == 4 - - def test_sieve(self): - sieve = self.build_cfunc(snippet.sieve_of_eratosthenes) - assert sieve() == 1028 - - def test_slice(self): - half = self.build_cfunc(snippet.half_of_n) - assert half(10) == 5 - - def test_poly_branch(self): - poly_branch = self.build_cfunc(snippet.poly_branch) - assert poly_branch(10) == [1,2,3]*2 - assert poly_branch(0) == ['a','b','c']*2 - - def test_and(self): - sand = self.build_cfunc(snippet.s_and) - assert sand(5, 6) == "yes" - assert sand(5, 0) == "no" - assert sand(0, 6) == "no" - assert sand(0, 0) == "no" - -class TestTypedTestCase: - - def getcompiled(self, func): - t = Translator(func) - t.simplify() - # builds starting-types from func_defs - argstypelist = [] - 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 - argstypelist.append(spec) - t.annotate(argstypelist) - return t.compile() - - def test_set_attr(self): - set_attr = self.getcompiled(snippet.set_attr) - assert set_attr() == 2 - - def test_inheritance2(self): - inheritance2 = self.getcompiled(snippet.inheritance2) - assert inheritance2() == ((-12, -12), (3, "world")) - - def test_factorial2(self): - factorial2 = self.getcompiled(snippet.factorial2) - assert factorial2(5) == 120 - - def test_factorial(self): - factorial = self.getcompiled(snippet.factorial) - assert factorial(5) == 120 - - def test_simple_method(self): - simple_method = self.getcompiled(snippet.simple_method) - assert simple_method(55) == 55 - - def test_sieve_of_eratosthenes(self): - sieve_of_eratosthenes = self.getcompiled(snippet.sieve_of_eratosthenes) - assert sieve_of_eratosthenes() == 1028 - - def test_nested_whiles(self): - nested_whiles = self.getcompiled(snippet.nested_whiles) - assert nested_whiles(5,3) == '!!!!!' - - def test_call_five(self): - call_five = self.getcompiled(snippet.call_five) - assert call_five() == [5] Deleted: /pypy/branch/src-typedunwrap/pypy/translator/test/test_sourcegen.py ============================================================================== --- /pypy/branch/src-typedunwrap/pypy/translator/test/test_sourcegen.py Sun Jan 23 11:58:23 2005 +++ (empty file) @@ -1,94 +0,0 @@ - -import autopath -from pypy.tool.udir import udir - -from pypy.translator.genpyrex import GenPyrex -from pypy.objspace.flow.model import * - -from pypy.translator.tool.buildpyxmodule import make_module_from_pyxstring -#from pypy.translator.test.make_dot import make_ps - -# XXX this tries to make compiling faster for full-scale testing -from pypy.translator.tool import buildpyxmodule -buildpyxmodule.enable_fast_compilation() - - -class TestSourceGenTestCase: - def test_simple_func(self): - """ - one test source: - def f(x): - return x+1 - """ - x = Variable("x") - result = Variable("result") - op = SpaceOperation("add", [x, Constant(1)], result) - block = Block([x]) - fun = FunctionGraph("f", block) - block.operations.append(op) - block.closeblock(Link([result], fun.returnblock)) - result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source1', udir, result) - assert mod.f(1) == 2 - - def test_if(self): - """ - one test source: - def f(i, j): - if i < 0: - i = j - return i - """ - i = Variable("i") - j = Variable("j") - - conditionres = Variable("conditionres") - conditionop = SpaceOperation("lt", [i, Constant(0)], conditionres) - startblock = Block([i, j]) - - fun = FunctionGraph("f", startblock) - startblock.operations.append(conditionop) - startblock.exitswitch = conditionres - startblock.closeblock(Link([i], fun.returnblock, False), - Link([j], fun.returnblock, True)) - - result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source2', udir, result) - assert mod.f(-1, 42) == 42 - assert mod.f(3, 5) == 3 - - def test_while_sum(self): - """ - one test source: - def f(i): - sum = 0 - while i > 0: - sum = sum + i - i = i - 1 - return sum - """ - i = Variable("i") - sum = Variable("sum") - - conditionres = Variable("conditionres") - conditionop = SpaceOperation("gt", [i, Constant(0)], conditionres) - decop = SpaceOperation("add", [i, Constant(-1)], i) - addop = SpaceOperation("add", [i, sum], sum) - startblock = Block([i]) - headerblock = Block([i, sum]) - whileblock = Block([i, sum]) - - fun = FunctionGraph("f", startblock) - startblock.closeblock(Link([i, Constant(0)], headerblock)) - headerblock.operations.append(conditionop) - headerblock.exitswitch = conditionres - headerblock.closeblock(Link([sum], fun.returnblock, False), - Link([i, sum], whileblock, True)) - whileblock.operations.append(addop) - whileblock.operations.append(decop) - whileblock.closeblock(Link([i, sum], headerblock)) - - result = GenPyrex(fun).emitcode() - mod = make_module_from_pyxstring('test_source4', udir, result) - assert mod.f(3) == 6 - assert mod.f(-3) == 0 From arigo at codespeak.net Sun Jan 23 12:44:27 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 12:44:27 +0100 (MET) Subject: [pypy-svn] r8486 - pypy/dist/pypy/module Message-ID: <20050123114427.620C027B49@code1.codespeak.net> Author: arigo Date: Sun Jan 23 12:44:27 2005 New Revision: 8486 Modified: pypy/dist/pypy/module/sysinterp.py Log: Remove 'struct' from the list of stolen modules. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Sun Jan 23 12:44:27 2005 @@ -38,7 +38,7 @@ for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', 'itertools', 'math', '_codecs', '_random', '_sre', 'time', '_socket', 'errno', - 'marshal', 'struct', 'binascii', 'parser']: + 'marshal', 'binascii', 'parser']: if fn not in builtin_modules: try: builtin_modules[fn] = hack_cpython_module(fn) From mwh at codespeak.net Sun Jan 23 14:33:39 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Sun, 23 Jan 2005 14:33:39 +0100 (MET) Subject: [pypy-svn] r8487 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050123133339.871FB27B45@code1.codespeak.net> Author: mwh Date: Sun Jan 23 14:33:39 2005 New Revision: 8487 Modified: pypy/dist/pypy/objspace/std/longobject.py pypy/dist/pypy/objspace/std/test/test_floatobject.py Log: Deal with overflow in long->float conversion. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Sun Jan 23 14:33:39 2005 @@ -39,7 +39,11 @@ return w_value # 9999999999999L.__int__() == 9999999999999L def float__Long(space, w_longobj): - return space.newfloat(float(w_longobj.longval)) + try: + return space.newfloat(float(w_longobj.longval)) + except OverflowError: + raise OperationError(space.w_OverflowError, + space.wrap("long int too large to convert to float")) def long__Float(space, w_floatobj): return W_LongObject(space, long(w_floatobj.floatval)) Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_floatobject.py Sun Jan 23 14:33:39 2005 @@ -53,6 +53,12 @@ def test_float_string(self): assert 42.0 == float("42") + def test_float_long(self): + assert 42.0 == float(42L) + assert 10000000000.0 == float(10000000000L) + raises(OverflowError, float, 10**400) + + def test_round(self): assert 1.0 == round(1.0) assert 1.0 == round(1.1) From mwh at codespeak.net Sun Jan 23 14:39:45 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Sun, 23 Jan 2005 14:39:45 +0100 (MET) Subject: [pypy-svn] r8488 - pypy/dist/pypy/documentation Message-ID: <20050123133945.9A13727B45@code1.codespeak.net> Author: mwh Date: Sun Jan 23 14:39:45 2005 New Revision: 8488 Modified: pypy/dist/pypy/documentation/architecture.txt pypy/dist/pypy/documentation/objspaceinterface.txt pypy/dist/pypy/documentation/wrapping.txt Log: Documentation for the post-merge type-specific unwrapping operations. Modified: pypy/dist/pypy/documentation/architecture.txt ============================================================================== --- pypy/dist/pypy/documentation/architecture.txt (original) +++ pypy/dist/pypy/documentation/architecture.txt Sun Jan 23 14:39:45 2005 @@ -226,12 +226,13 @@ The ``w_`` prefixes so lavishly used in the previous example indicate, by PyPy coding convention, that we are dealing with *wrapped* objects, -that is, interpreter-level objects which the object space constructs to -implement corresponding application-level objects. Each object space -supplies ``wrap`` and ``unwrap`` operations that move between the two -levels for objects of simple built-in types; each object space also -implements other Python types with suitable interpreter-level classes -with some amount of internal structure. +that is, interpreter-level objects which the object space constructs +to implement corresponding application-level objects. Each object +space supplies ``wrap`` and ``unwrap``, ``int_w``, ``interpclass_w``, +etc. operations that move between the two levels for objects of simple +built-in types; each object space also implements other Python types +with suitable interpreter-level classes with some amount of internal +structure. For example, an application-level Python ``list`` is implemented as an instance of ``W_ListObject``, which has an instance attribute Modified: pypy/dist/pypy/documentation/objspaceinterface.txt ============================================================================== --- pypy/dist/pypy/documentation/objspaceinterface.txt (original) +++ pypy/dist/pypy/documentation/objspaceinterface.txt Sun Jan 23 14:39:45 2005 @@ -86,6 +86,18 @@ **unwrap(w_x):** Return Interpreter Level equivalent of w_x +**interpclass_w(w_x):** + If w_x is a wrapped instance of an interpreter class -- for example Function, Frame, Cell, etc. -- return it unwrapped. Otherwise return None. + +**int_w(w_x):** + If w_x is an application-level integer or long which can be converted without overflow to an integer, return an interpreter-level integer. Otherwise raise TypeError or OverflowError. + +**str_w(w_x):** + If w_x is an application-level string, return an interpreter-level string. Otherwise raise TypeError. + +**float_w(w_x):** + If w_x is an application-level float, integer or long, return interpreter-level float. Otherwise raise TypeError or OverflowError in case of very large longs. + **is_true(w_x):** Return a interpreter level bool (True or False). Modified: pypy/dist/pypy/documentation/wrapping.txt ============================================================================== --- pypy/dist/pypy/documentation/wrapping.txt (original) +++ pypy/dist/pypy/documentation/wrapping.txt Sun Jan 23 14:39:45 2005 @@ -67,7 +67,15 @@ * ``space.unpackiterable(w_x)``: this helper iterates ``w_x`` (using ``space.iter()`` and ``space.next()``) and collects the resulting wrapped objects in a list. Of course, in cases where iterating directly is better than collecting the elements in a list first, you should use ``space.iter()`` and ``space.next()`` directly. -* ``space.unwrap(w_x)``: inverse of ``space.wrap()``. Attention! Using ``space.unwrap()`` must be avoided whenever possible. Actually, it should only be used when you are sure that ``w_x`` contains a simple object or an internal interpreter object that was wrapped with ``space.wrap()``. This function is a bit buggy anyway, and it should probably be fixed at some point: we should specify what kind of unwrapped result is expected (and raise a TypeError appropriately). +* ``space.unwrap(w_x)``: inverse of ``space.wrap()``. Attention! Using ``space.unwrap()`` must be avoided whenever possible, i.e. only use this when you are well aware that you are cheating, in unit tests or bootstrapping code. + +* ``space.interpclass_w(w_x)``: If w_x is a wrapped instance of an interpreter class -- for example Function, Frame, Cell, etc. -- return it unwrapped. Otherwise return None. + +* ``space.int_w(w_x)``: If w_x is an application-level integer or long which can be converted without overflow to an integer, return an interpreter-level integer. Otherwise raise TypeError or OverflowError. + +* ``space.str_w(w_x)``: If w_x is an application-level string, return an interpreter-level string. Otherwise raise TypeError. + +* ``space.float_w(w_x)``: If w_x is an application-level float, integer or long, return interpreter-level float. Otherwise raise TypeError or OverflowError in case of very large longs. Remember that you can usually obtain the information you want by invoking operations or methods on the wrapped objects; e.g. ``space.call_method(w_dict, 'iterkeys')`` returns a wrapped iterable that you can decode with ``space.unpackiterable()``. From odie at codespeak.net Sun Jan 23 14:48:10 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 14:48:10 +0100 (MET) Subject: [pypy-svn] r8489 - pypy/dist/pypy/module Message-ID: <20050123134810.F2A7B27B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 14:48:10 2005 New Revision: 8489 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: Version information were missing. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Sun Jan 23 14:48:10 2005 @@ -68,7 +68,6 @@ [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) # XXX - Replace with appropriate PyPy version numbering -w_hexversion = space.wrap(cpy_sys.hexversion) w_platform = space.wrap(cpy_sys.platform) w_maxint = space.wrap(cpy_sys.maxint) w_byteorder = space.wrap(cpy_sys.byteorder) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Sun Jan 23 14:48:10 2005 @@ -11,7 +11,7 @@ # Objects from interpreter-level from __interplevel__ import stdin, stdout, stderr, maxint -from __interplevel__ import hexversion, platform, byteorder +from __interplevel__ import platform, byteorder from __interplevel__ import pypy_objspaceclass # Functions from interpreter-level @@ -20,7 +20,9 @@ # Dummy executable = '' prefix = '' -version = '0.5.0 (not released yet)' +version = '2.3a0 (pypy build)' +version_info = (2, 3, 0, 'alpha', 0) +hexversion = 0x020300a0 ps1 = '>>>> ' ps2 = '.... ' From odie at codespeak.net Sun Jan 23 15:07:59 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 15:07:59 +0100 (MET) Subject: [pypy-svn] r8490 - in pypy/dist/pypy/interpreter: . test Message-ID: <20050123140759.262FE27B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 15:07:58 2005 New Revision: 8490 Modified: pypy/dist/pypy/interpreter/module.py pypy/dist/pypy/interpreter/test/test_module.py Log: Modules can have docstring at construction time. Modified: pypy/dist/pypy/interpreter/module.py ============================================================================== --- pypy/dist/pypy/interpreter/module.py (original) +++ pypy/dist/pypy/interpreter/module.py Sun Jan 23 15:07:58 2005 @@ -14,6 +14,8 @@ self.w_dict = w_dict self.w_name = w_name space.setitem(w_dict, space.wrap('__name__'), w_name) + if not space.is_true(space.contains(w_dict, space.wrap('__doc__'))): + space.setitem(w_dict, space.wrap('__doc__'), space.w_None) def getdict(self): return self.w_dict @@ -26,7 +28,9 @@ module.__init__(space, space.wrap('?')) return space.wrap(module) - def descr_module__init__(self, w_name): + def descr_module__init__(self, w_name, w_doc=None): space = self.space self.w_name = w_name space.setitem(self.w_dict, space.wrap('__name__'), w_name) + if w_doc is not None: + space.setitem(self.w_dict, space.wrap('__doc__'), w_doc) Modified: pypy/dist/pypy/interpreter/test/test_module.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_module.py (original) +++ pypy/dist/pypy/interpreter/test/test_module.py Sun Jan 23 15:07:58 2005 @@ -37,3 +37,10 @@ delattr(m, 'x') raises(AttributeError, getattr, m, 'x') raises(AttributeError, delattr, m, 'x') + def test_docstring(self): + import sys + foo = type(sys)('foo') + assert foo.__name__ == 'foo' + assert foo.__doc__ is None + bar = type(sys)('bar','docstring') + assert bar.__doc__ == 'docstring' From odie at codespeak.net Sun Jan 23 15:27:30 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 15:27:30 +0100 (MET) Subject: [pypy-svn] r8491 - in pypy/dist/pypy: appspace/test module Message-ID: <20050123142730.3B21C27B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 15:27:30 2005 New Revision: 8491 Modified: pypy/dist/pypy/appspace/test/support_tests.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: Hack: get temporary directory from either py or sys.pypy_getudir whether we are at interpreter or application level respectively. Modified: pypy/dist/pypy/appspace/test/support_tests.py ============================================================================== --- pypy/dist/pypy/appspace/test/support_tests.py (original) +++ pypy/dist/pypy/appspace/test/support_tests.py Sun Jan 23 15:27:30 2005 @@ -5,11 +5,15 @@ raise ImportError, 'test_support must be imported from the test package' ''' -import sys +import sys, os from os import unlink -import py -TESTFN = str(py.test.config.tmpdir.join('@test')) +try: + tmpdir = sys.pypy_getudir() +except AttributeError: + import py + tmpdir = str(py.test.config.tmpdir) +TESTFN = os.path.join(tmpdir, '@test') class Error(Exception): """Base class for regression test exceptions.""" Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Sun Jan 23 15:27:30 2005 @@ -118,3 +118,7 @@ else: return space.newtuple([operror.w_type,operror.w_value, space.wrap(operror.application_traceback)]) + +def pypy_getudir(): + from pypy.tool.udir import udir + return space.wrap(udir) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Sun Jan 23 15:27:30 2005 @@ -15,7 +15,7 @@ from __interplevel__ import pypy_objspaceclass # Functions from interpreter-level -from __interplevel__ import _getframe, exc_info +from __interplevel__ import _getframe, exc_info, pypy_getudir # Dummy executable = '' From odie at codespeak.net Sun Jan 23 15:32:52 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 15:32:52 +0100 (MET) Subject: [pypy-svn] r8492 - pypy/dist/pypy/module Message-ID: <20050123143252.58A1727B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 15:32:52 2005 New Revision: 8492 Modified: pypy/dist/pypy/module/sysinterp.py Log: Oops! wrap the string repr not the object. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Sun Jan 23 15:32:52 2005 @@ -121,4 +121,4 @@ def pypy_getudir(): from pypy.tool.udir import udir - return space.wrap(udir) + return space.wrap(str(udir)) From odie at codespeak.net Sun Jan 23 16:14:53 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 16:14:53 +0100 (MET) Subject: [pypy-svn] r8493 - pypy/dist/pypy/objspace/std Message-ID: <20050123151453.2039B27B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 16:14:52 2005 New Revision: 8493 Modified: pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/slicetype.py Log: Fix list index method to support index larger than maxint. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Sun Jan 23 16:14:52 2005 @@ -406,15 +406,10 @@ eq = space.eq items = w_list.ob_item size = w_list.ob_size + w_start = slicetype.adapt_bound(space, w_start, space.wrap(size)) + w_stop = slicetype.adapt_bound(space, w_stop, space.wrap(size)) start = space.int_w(w_start) - if start < 0: - start += size - start = min(max(0,start),size) stop = space.int_w(w_stop) - if stop < 0: - stop += size - stop = min(max(start,stop),size) - for i in range(start,stop): cmp = eq(items[i], w_any) if space.is_true(cmp): Modified: pypy/dist/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/slicetype.py (original) +++ pypy/dist/pypy/objspace/std/slicetype.py Sun Jan 23 16:14:52 2005 @@ -77,6 +77,15 @@ return (space.int_w(w_1), space.int_w(w_2), space.int_w(w_3), space.int_w(w_4)) +def adapt_bound(space, w_index, w_size): + if space.is_true(space.lt(w_index, space.wrap(0))): + w_index = space.add(w_index, w_size) + if space.is_true(space.lt(w_index, space.wrap(0))): + w_index = space.wrap(0) + if space.is_true(space.gt(w_index, w_size)): + w_index = w_size + return w_index + register_all(vars(), globals()) # ____________________________________________________________ From odie at codespeak.net Sun Jan 23 16:37:37 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 16:37:37 +0100 (MET) Subject: [pypy-svn] r8494 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050123153737.8A58627B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 16:37:37 2005 New Revision: 8494 Modified: pypy/dist/pypy/objspace/std/slicetype.py pypy/dist/pypy/objspace/std/test/test_listobject.py Log: list index method should only accept int and long. Modified: pypy/dist/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/slicetype.py (original) +++ pypy/dist/pypy/objspace/std/slicetype.py Sun Jan 23 16:37:37 2005 @@ -78,6 +78,10 @@ space.int_w(w_3), space.int_w(w_4)) def adapt_bound(space, w_index, w_size): + if not (space.is_true(space.isinstance(w_index, space.w_int)) or + space.is_true(space.isinstance(w_index, space.w_long))): + raise OperationError(space.w_TypeError, + space.wrap("slice indices must be integers")) if space.is_true(space.lt(w_index, space.wrap(0))): w_index = space.add(w_index, w_size) if space.is_true(space.lt(w_index, space.wrap(0))): Modified: pypy/dist/pypy/objspace/std/test/test_listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_listobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_listobject.py Sun Jan 23 16:37:37 2005 @@ -336,3 +336,8 @@ l += [4,5] assert l is l0 assert l == [1,2,3,4,5] + + def test_index(self): + l = ['a', 'b', 'c', 'd', 'e', 'f'] + raises(TypeError, l.index, 'c', 0, 4.3) + raises(TypeError, l.index, 'c', 1.0, 5.6) From odie at codespeak.net Sun Jan 23 16:44:23 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 16:44:23 +0100 (MET) Subject: [pypy-svn] r8495 - pypy/dist/pypy/objspace/std/test Message-ID: <20050123154423.C287527B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 16:44:23 2005 New Revision: 8495 Modified: pypy/dist/pypy/objspace/std/test/test_stringobject.py Log: Enable old disabled test for lost reasons. Modified: pypy/dist/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_stringobject.py Sun Jan 23 16:44:23 2005 @@ -328,11 +328,10 @@ assert 'abcdefghiabc'.index('def') == 3 assert 'abcdefghiabc'.index('abc') == 0 assert 'abcdefghiabc'.index('abc', 1) == 9 - #XXX it comes UnicodeError - #self.assertRaises(ValueError, 'abcdefghiabc'.index('hib')) - #self.assertRaises(ValueError, 'abcdefghiab'.index('abc', 1)) - #self.assertRaises(ValueError, 'abcdefghi'.index('ghi', 8)) - #self.assertRaises(ValueError, 'abcdefghi'.index('ghi', -1)) + raises(ValueError, 'abcdefghiabc'.index, 'hib') + raises(ValueError, 'abcdefghiab'.index, 'abc', 1) + raises(ValueError, 'abcdefghi'.index, 'ghi', 8) + raises(ValueError, 'abcdefghi'.index, 'ghi', -1) def test_rfind(self): assert 'abcdefghiabc'.rfind('abc') == 9 @@ -345,12 +344,11 @@ assert 'abcdefghiabc'.rindex('def') == 3 assert 'abcdefghiabc'.rindex('abc') == 9 assert 'abcdefghiabc'.rindex('abc', 0, -1) == 0 - #XXX it comes UnicodeError - #self.assertRaises(ValueError, 'abcdefghiabc'.rindex('hib')) - #self.assertRaises(ValueError, 'defghiabc'.rindex('def', 1)) - #self.assertRaises(ValueError, 'defghiabc'.rindex('abc', 0, -1)) - #self.assertRaises(ValueError, 'abcdefghi'.rindex('ghi', 0, 8)) - #self.assertRaises(ValueError, 'abcdefghi'.rindex('ghi', 0, -1)) + raises(ValueError, 'abcdefghiabc'.rindex, 'hib') + raises(ValueError, 'defghiabc'.rindex, 'def', 1) + raises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1) + raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8) + raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1) def test_split_maxsplit(self): From odie at codespeak.net Sun Jan 23 17:21:55 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 17:21:55 +0100 (MET) Subject: [pypy-svn] r8496 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050123162155.0CE5727B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 17:21:54 2005 New Revision: 8496 Modified: pypy/dist/pypy/objspace/std/stringobject.py pypy/dist/pypy/objspace/std/stringtype.py pypy/dist/pypy/objspace/std/test/test_stringobject.py Log: String index, rindex and count method support for int and long. Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Sun Jan 23 17:21:54 2005 @@ -395,31 +395,28 @@ def _convert_idx_params(space, w_self, w_sub, w_start, w_end): self = w_self._value sub = w_sub._value - if space.is_true(space.is_(w_start,space.w_None)): - start = 0 - else: - start = space.int_w(w_start) - if space.is_true(space.is_(w_end,space.w_None)): - end = len(self) - else: - end = space.int_w(w_end) + w_start = slicetype.adapt_bound(space, w_start, space.wrap(len(self))) + w_end = slicetype.adapt_bound(space, w_end, space.wrap(len(self))) + + start = space.int_w(w_start) + end = space.int_w(w_end) return (self, sub, start, end) -def str_find__String_String_ANY_ANY(space, w_self, w_sub, w_start=None, w_end=None): +def str_find__String_String_ANY_ANY(space, w_self, w_sub, w_start, w_end): (self, sub, start, end) = _convert_idx_params(space, w_self, w_sub, w_start, w_end) res = _find(self, sub, start, end, 1) return space.wrap(res) -def str_rfind__String_String_ANY_ANY(space, w_self, w_sub, w_start=None, w_end=None): +def str_rfind__String_String_ANY_ANY(space, w_self, w_sub, w_start, w_end): (self, sub, start, end) = _convert_idx_params(space, w_self, w_sub, w_start, w_end) res = _find(self, sub, start, end, -1) return space.wrap(res) -def str_index__String_String_ANY_ANY(space, w_self, w_sub, w_start=None, w_end=None): +def str_index__String_String_ANY_ANY(space, w_self, w_sub, w_start, w_end): (self, sub, start, end) = _convert_idx_params(space, w_self, w_sub, w_start, w_end) res = _find(self, sub, start, end, 1) @@ -431,7 +428,7 @@ return space.wrap(res) -def str_rindex__String_String_ANY_ANY(space, w_self, w_sub, w_start=None, w_end=None): +def str_rindex__String_String_ANY_ANY(space, w_self, w_sub, w_start, w_end): (self, sub, start, end) = _convert_idx_params(space, w_self, w_sub, w_start, w_end) res = _find(self, sub, start, end, -1) @@ -590,26 +587,16 @@ u_self = w_self._value u_arg = w_arg._value - if space.is_true(space.is_(w_start,space.w_None)): - u_start = 0 - else: - u_start = space.int_w(w_start) - - if space.is_true(space.is_(w_end,space.w_None)): - u_end = len(u_self) - else: - u_end = space.int_w(w_end) - if u_end < 0: - u_end += len(u_self) - - area = u_self [u_start:u_end] + w_start = slicetype.adapt_bound(space, w_start, space.wrap(len(u_self))) + w_end = slicetype.adapt_bound(space, w_end, space.wrap(len(u_self))) + u_start = space.int_w(w_start) + u_end = space.int_w(w_end) count = 0 - pos = -1 + pos = u_start - 1 while 1: - pos = _find(area, u_arg, pos+1, u_end, 1) - #pos = area.find(u_arg, pos+1, u_end) + pos = _find(u_self, u_arg, pos+1, u_end, 1) if pos == -1: break count += 1 Modified: pypy/dist/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringtype.py (original) +++ pypy/dist/pypy/objspace/std/stringtype.py Sun Jan 23 17:21:54 2005 @@ -1,6 +1,7 @@ from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.basestringtype import basestring_typedef +from sys import maxint str_join = MultiMethod('join', 2) str_split = MultiMethod('split', 3, defaults=(None,-1)) @@ -18,17 +19,17 @@ str_swapcase = MultiMethod('swapcase', 1) str_capitalize = MultiMethod('capitalize', 1) str_title = MultiMethod('title', 1) -str_find = MultiMethod('find', 4, defaults=(None, None)) -str_rfind = MultiMethod('rfind', 4, defaults=(None, None)) -str_index = MultiMethod('index', 4, defaults=(None, None)) -str_rindex = MultiMethod('rindex', 4, defaults=(None, None)) +str_find = MultiMethod('find', 4, defaults=(0, maxint)) +str_rfind = MultiMethod('rfind', 4, defaults=(0, maxint)) +str_index = MultiMethod('index', 4, defaults=(0, maxint)) +str_rindex = MultiMethod('rindex', 4, defaults=(0, maxint)) str_replace = MultiMethod('replace', 4, defaults=(-1,)) str_zfill = MultiMethod('zfill', 2) str_strip = MultiMethod('strip', 2, defaults=('', ' ')) str_rstrip = MultiMethod('rstrip', 2, defaults=('', ' ')) str_lstrip = MultiMethod('lstrip', 2, defaults=('', ' ')) str_center = MultiMethod('center', 2, ) -str_count = MultiMethod('count', 4, defaults=(None,None)) +str_count = MultiMethod('count', 4, defaults=(0, maxint)) str_endswith = MultiMethod('endswith', 2) #[optional arguments not supported now] str_expandtabs = MultiMethod('expandtabs', 2, defaults=(8,)) str_splitlines = MultiMethod('splitlines', 2, defaults=(0,)) Modified: pypy/dist/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_stringobject.py Sun Jan 23 17:21:54 2005 @@ -324,14 +324,18 @@ assert 'abcdefghiabc'.find('def', 4) == -1 def test_index(self): + from sys import maxint assert 'abcdefghiabc'.index('') == 0 assert 'abcdefghiabc'.index('def') == 3 assert 'abcdefghiabc'.index('abc') == 0 assert 'abcdefghiabc'.index('abc', 1) == 9 + assert 'abcdefghiabc'.index('def', -4*maxint, 4*maxint) == 3 raises(ValueError, 'abcdefghiabc'.index, 'hib') raises(ValueError, 'abcdefghiab'.index, 'abc', 1) raises(ValueError, 'abcdefghi'.index, 'ghi', 8) raises(ValueError, 'abcdefghi'.index, 'ghi', -1) + raises(TypeError, 'abcdefghijklmn'.index, 'abc', 0, 0.0) + raises(TypeError, 'abcdefghijklmn'.index, 'abc', -10.0, 30) def test_rfind(self): assert 'abcdefghiabc'.rfind('abc') == 9 @@ -340,15 +344,19 @@ assert 'abcdefghiabc'.rfind('abcz') == -1 def test_rindex(self): + from sys import maxint assert 'abcdefghiabc'.rindex('') == 12 assert 'abcdefghiabc'.rindex('def') == 3 assert 'abcdefghiabc'.rindex('abc') == 9 assert 'abcdefghiabc'.rindex('abc', 0, -1) == 0 + assert 'abcdefghiabc'.rindex('abc', -4*maxint, 4*maxint) == 9 raises(ValueError, 'abcdefghiabc'.rindex, 'hib') raises(ValueError, 'defghiabc'.rindex, 'def', 1) raises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1) raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8) raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1) + raises(TypeError, 'abcdefghijklmn'.rindex, 'abc', 0, 0.0) + raises(TypeError, 'abcdefghijklmn'.rindex, 'abc', -10.0, 30) def test_split_maxsplit(self): From odie at codespeak.net Sun Jan 23 18:22:39 2005 From: odie at codespeak.net (odie at codespeak.net) Date: Sun, 23 Jan 2005 18:22:39 +0100 (MET) Subject: [pypy-svn] r8498 - pypy/dist/pypy/objspace/std/test Message-ID: <20050123172239.A58D627B45@code1.codespeak.net> Author: odie Date: Sun Jan 23 18:22:39 2005 New Revision: 8498 Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py Log: Check float to int/long conversion. Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_floatobject.py Sun Jan 23 18:22:39 2005 @@ -50,6 +50,10 @@ def test_float_int(self): assert 42.0 == float(42) + def test_int_float(self): + assert int(42.1234) == 42 + assert int(4e10) == 40000000000L + def test_float_string(self): assert 42.0 == float("42") From arigo at codespeak.net Sun Jan 23 18:23:46 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 18:23:46 +0100 (MET) Subject: [pypy-svn] r8499 - pypy/dist/pypy/objspace/std Message-ID: <20050123172346.0AFA327B45@code1.codespeak.net> Author: arigo Date: Sun Jan 23 18:23:45 2005 New Revision: 8499 Modified: pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/longobject.py Log: Fixed int(1E10), but by cheating. Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Sun Jan 23 18:23:45 2005 @@ -41,7 +41,10 @@ return W_FloatObject(space, a) def int__Float(space, w_value): - return space.newint(int(w_value.floatval)) + value = int(w_value.floatval) + if isinstance(value, long): # XXX cheating + return space.long(w_value) + return space.newint(value) def float_w__Float(space, w_float): return w_float.floatval Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Sun Jan 23 18:23:45 2005 @@ -46,6 +46,7 @@ space.wrap("long int too large to convert to float")) def long__Float(space, w_floatobj): + # XXX cheating return W_LongObject(space, long(w_floatobj.floatval)) def int_w__Long(space, w_value): From hpk at codespeak.net Sun Jan 23 18:29:10 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 23 Jan 2005 18:29:10 +0100 (MET) Subject: [pypy-svn] r8500 - pypy/extradoc/talk Message-ID: <20050123172910.9DE9427B45@code1.codespeak.net> Author: hpk Date: Sun Jan 23 18:29:10 2005 New Revision: 8500 Added: pypy/extradoc/talk/2004-pypy-eu.pdf (contents, props changed) Log: added my talk i gave at the 21C3 (2004 - Chaos communication conference) ... Added: pypy/extradoc/talk/2004-pypy-eu.pdf ============================================================================== Binary file. No diff available. From hpk at codespeak.net Sun Jan 23 18:30:32 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 23 Jan 2005 18:30:32 +0100 (MET) Subject: [pypy-svn] r8501 - pypy/extradoc/talk Message-ID: <20050123173032.2171D27B45@code1.codespeak.net> Author: hpk Date: Sun Jan 23 18:30:31 2005 New Revision: 8501 Added: pypy/extradoc/talk/2004-21C3-pypy-EU-hpk.pdf - copied unchanged from r8500, pypy/extradoc/talk/2004-pypy-eu.pdf Removed: pypy/extradoc/talk/2004-pypy-eu.pdf Log: well, gave a more telling name to this talk (if you know waht 21C3 really means) Deleted: /pypy/extradoc/talk/2004-pypy-eu.pdf ============================================================================== Binary file. No diff available. From arigo at codespeak.net Sun Jan 23 18:45:57 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 18:45:57 +0100 (MET) Subject: [pypy-svn] r8502 - pypy/dist/pypy/appspace Message-ID: <20050123174557.DA02827B45@code1.codespeak.net> Author: arigo Date: Sun Jan 23 18:45:57 2005 New Revision: 8502 Modified: pypy/dist/pypy/appspace/struct.py Log: - struct.unpack() should return a tuple. - use longs explicitely to work also with 2.3's bit-loosing '<<'. Modified: pypy/dist/pypy/appspace/struct.py ============================================================================== --- pypy/dist/pypy/appspace/struct.py (original) +++ pypy/dist/pypy/appspace/struct.py Sun Jan 23 18:45:57 2005 @@ -44,16 +44,16 @@ bytes = [ord(b) for b in data[index:index+size]] if le == 'little': bytes.reverse() - number = 0 + number = 0L for b in bytes: number = number << 8 | b - return number + return int(number) def unpack_signed_int(data,index,size,le): number = unpack_int(data,index,size,le) max = 2**(size*8) if number > 2**(size*8 - 1) - 1: - number = -1*(max - number) + number = int(-1*(max - number)) return number def unpack_float(data,index,size,le): @@ -71,7 +71,7 @@ exp = 11 prec = 52 # print bytes,size,index,len(data),data - mantissa = bytes[size-2] & (2**(15-exp)-1) + mantissa = long(bytes[size-2] & (2**(15-exp)-1)) # print mantissa for b in bytes[size-3::-1]: mantissa = mantissa << 8 | b @@ -337,10 +337,10 @@ j += format['size'] i += 1 - return result + return tuple(result) if __name__ == '__main__': print pack_float(1.23,4,'little') import struct print struct.pack('f',1.23), pack('f',1.23) - print unpack('f',pack('f',1.23)) \ No newline at end of file + print unpack('f',pack('f',1.23)) From hpk at codespeak.net Sun Jan 23 18:49:01 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 23 Jan 2005 18:49:01 +0100 (MET) Subject: [pypy-svn] r8503 - pypy/dist/Pyrex Message-ID: <20050123174901.53F1D27B45@code1.codespeak.net> Author: hpk Date: Sun Jan 23 18:49:01 2005 New Revision: 8503 Added: pypy/dist/Pyrex/conftest.py Log: convenience: don't look below Pyrex when collecting tests ... Added: pypy/dist/Pyrex/conftest.py ============================================================================== --- (empty file) +++ pypy/dist/Pyrex/conftest.py Sun Jan 23 18:49:01 2005 @@ -0,0 +1,6 @@ +import py +class Directory(py.test.collect.Directory): + def __iter__(self): + return self + def next(self): + raise StopIteration From hpk at codespeak.net Sun Jan 23 18:52:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 23 Jan 2005 18:52:17 +0100 (MET) Subject: [pypy-svn] r8504 - pypy/dist/pypy/tool Message-ID: <20050123175217.A038B27B45@code1.codespeak.net> Author: hpk Date: Sun Jan 23 18:52:17 2005 New Revision: 8504 Modified: pypy/dist/pypy/tool/pydis.py Log: fix for traceinteractive to work with new co_consts_w scheme Modified: pypy/dist/pypy/tool/pydis.py ============================================================================== --- pypy/dist/pypy/tool/pydis.py (original) +++ pypy/dist/pypy/tool/pydis.py Sun Jan 23 18:52:17 2005 @@ -44,7 +44,7 @@ s = repr(oparg).rjust(5) + " " if op in hasconst: - s += '(' + `co.co_consts[oparg]` + ')' + s += '(' + `co.co_consts_w[oparg]` + ')' elif op in hasname: s += '(' + co.co_names[oparg] + ')' elif op in hasjrel: From arigo at codespeak.net Sun Jan 23 19:03:53 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 19:03:53 +0100 (MET) Subject: [pypy-svn] r8507 - pypy/dist/pypy/module/test Message-ID: <20050123180353.40CB627B45@code1.codespeak.net> Author: arigo Date: Sun Jan 23 19:03:53 2005 New Revision: 8507 Modified: pypy/dist/pypy/module/test/test_builtin.py Log: Use pypy.tool.udir instead of tempfile.mktemp(). Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Sun Jan 23 19:03:53 2005 @@ -273,21 +273,16 @@ return w_obj def test_execfile(self): - # we need cpython's tempfile currently to test - from tempfile import mktemp - fn = mktemp() + from pypy.tool.udir import udir + fn = str(udir.join('test_execfile')) f = open(fn, 'w') print >>f, "i=42" f.close() - try: - w_execfile = self.get_builtin('execfile') - space = self.space - w_dict = space.newdict([]) - self.space.call_function(w_execfile, - space.wrap(fn), w_dict, space.w_None) - w_value = space.getitem(w_dict, space.wrap('i')) - assert self.space.eq_w(w_value, space.wrap(42)) - finally: - import os - os.remove(fn) + w_execfile = self.get_builtin('execfile') + space = self.space + w_dict = space.newdict([]) + self.space.call_function(w_execfile, + space.wrap(fn), w_dict, space.w_None) + w_value = space.getitem(w_dict, space.wrap('i')) + assert self.space.eq_w(w_value, space.wrap(42)) From arigo at codespeak.net Sun Jan 23 19:13:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 23 Jan 2005 19:13:36 +0100 (MET) Subject: [pypy-svn] r8508 - pypy/dist/pypy/appspace/test Message-ID: <20050123181336.6B1C727B45@code1.codespeak.net> Author: arigo Date: Sun Jan 23 19:13:36 2005 New Revision: 8508 Modified: pypy/dist/pypy/appspace/test/test_sio.py Log: - fix a case in which temp files were not removed. - use pypy.tool.udir instead of tempfile.mktemp(). Modified: pypy/dist/pypy/appspace/test/test_sio.py ============================================================================== --- pypy/dist/pypy/appspace/test/test_sio.py (original) +++ pypy/dist/pypy/appspace/test/test_sio.py Sun Jan 23 19:13:36 2005 @@ -2,7 +2,7 @@ import os import time -import tempfile +from pypy.tool.udir import udir from pypy.appspace import sio @@ -477,6 +477,7 @@ class TestMMapFile(TestBufferingInputStreamTests): tfn = None + Counter = 0 def teardown_method(self, method): tfn = self.tfn @@ -488,7 +489,9 @@ print "can't remove %s: %s" % (tfn, msg) def makeStream(self, tell=None, seek=None, bufsize=None, mode="r"): - self.tfn = tempfile.mktemp() + self.teardown_method(None) # for tests calling makeStream() several time + self.tfn = str(udir.join('sio%03d' % TestMMapFile.Counter)) + TestMMapFile.Counter += 1 f = open(self.tfn, "wb") f.writelines(self.packets) f.close() From arigo at codespeak.net Mon Jan 24 11:04:05 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 11:04:05 +0100 (MET) Subject: [pypy-svn] r8512 - pypy/dist/pypy/appspace/test Message-ID: <20050124100405.F3ACD27B4B@code1.codespeak.net> Author: arigo Date: Mon Jan 24 11:04:05 2005 New Revision: 8512 Modified: pypy/dist/pypy/appspace/test/__init__.py Log: Confusion. When doing 'import test' at app-level, we actually find the package 'pypy.appspace.test'... This hack "merges" that package with CPython's own 'test' package. Modified: pypy/dist/pypy/appspace/test/__init__.py ============================================================================== --- pypy/dist/pypy/appspace/test/__init__.py (original) +++ pypy/dist/pypy/appspace/test/__init__.py Mon Jan 24 11:04:05 2005 @@ -1 +1,8 @@ -# empty +# +# Confusion. When doing 'import test' at app-level, we actually +# find this package... This hack "merges" the package with +# CPython's own 'test' package. +# + +import os +__path__.append(os.path.join(os.path.dirname(os.__file__), 'test')) From tismer at codespeak.net Mon Jan 24 11:14:30 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 11:14:30 +0100 (MET) Subject: [pypy-svn] r8513 - pypy/dist/pypy/appspace Message-ID: <20050124101430.D897227B4F@code1.codespeak.net> Author: tismer Date: Mon Jan 24 11:14:30 2005 New Revision: 8513 Removed: pypy/dist/pypy/appspace/copy_reg.py Modified: pypy/dist/pypy/appspace/types.py Log: chanted types.py to make ClassType really different from type. This makes appspace/copy_reg obsolete. Deleted: /pypy/dist/pypy/appspace/copy_reg.py ============================================================================== --- /pypy/dist/pypy/appspace/copy_reg.py Mon Jan 24 11:14:30 2005 +++ (empty file) @@ -1,192 +0,0 @@ -"""Helper to provide extensibility for pickle/cPickle. - -!! This file has been copied practicaly verbatim from the CPython source. -!! See http://www.python.org/2.3.2/license.html for licensing info. - -This is only useful to add pickle support for extension types defined in -C, not for instances of user-defined classes. -""" - -from types import ClassType as _ClassType - -__all__ = ["pickle", "constructor", - "add_extension", "remove_extension", "clear_extension_cache"] - -dispatch_table = {} - -def pickle(ob_type, pickle_function, constructor_ob=None): -## if type(ob_type) is _ClassType: -## raise TypeError("copy_reg is not intended for use with classes") - - if not callable(pickle_function): - raise TypeError("reduction functions must be callable") - dispatch_table[ob_type] = pickle_function - - # The constructor_ob function is a vestige of safe for unpickling. - # There is no reason for the caller to pass it anymore. - if constructor_ob is not None: - constructor(constructor_ob) - -def constructor(object): - if not callable(object): - raise TypeError("constructors must be callable") - -# Example: provide pickling support for complex numbers. - -try: - complex -except NameError: - pass -else: - - def pickle_complex(c): - return complex, (c.real, c.imag) - - pickle(complex, pickle_complex, complex) - -# Support for pickling new-style objects - -def _reconstructor(cls, base, state): - if base is object: - obj = object.__new__(cls) - else: - obj = base.__new__(cls, state) - base.__init__(obj, state) - return obj - -_HEAPTYPE = 1<<9 - -# Python code for object.__reduce_ex__ for protocols 0 and 1 - -def _reduce_ex(self, proto): - assert proto < 2 - for base in self.__class__.__mro__: - if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: - break - else: - base = object # not really reachable - if base is object: - state = None - else: - if base is self.__class__: - raise TypeError, "can't pickle %s objects" % base.__name__ - state = base(self) - args = (self.__class__, base, state) - try: - getstate = self.__getstate__ - except AttributeError: - if getattr(self, "__slots__", None): - raise TypeError("a class that defines __slots__ without " - "defining __getstate__ cannot be pickled") - try: - dict = self.__dict__ - except AttributeError: - dict = None - else: - dict = getstate() - if dict: - return _reconstructor, args, dict - else: - return _reconstructor, args - -# Helper for __reduce_ex__ protocol 2 - -def __newobj__(cls, *args): - return cls.__new__(cls, *args) - -def _slotnames(cls): - """Return a list of slot names for a given class. - - This needs to find slots defined by the class and its bases, so we - can't simply return the __slots__ attribute. We must walk down - the Method Resolution Order and concatenate the __slots__ of each - class found there. (This assumes classes don't modify their - __slots__ attribute to misrepresent their slots after the class is - defined.) - """ - - # Get the value from a cache in the class if possible - names = cls.__dict__.get("__slotnames__") - if names is not None: - return names - - # Not cached -- calculate the value - names = [] - if not hasattr(cls, "__slots__"): - # This class has no slots - pass - else: - # Slots found -- gather slot names from all base classes - for c in cls.__mro__: - if "__slots__" in c.__dict__: - names += [name for name in c.__dict__["__slots__"] - if name not in ("__dict__", "__weakref__")] - - # Cache the outcome in the class if at all possible - try: - cls.__slotnames__ = names - except: - pass # But don't die if we can't - - return names - -# A registry of extension codes. This is an ad-hoc compression -# mechanism. Whenever a global reference to , is about -# to be pickled, the (, ) tuple is looked up here to see -# if it is a registered extension code for it. Extension codes are -# universal, so that the meaning of a pickle does not depend on -# context. (There are also some codes reserved for local use that -# don't have this restriction.) Codes are positive ints; 0 is -# reserved. - -_extension_registry = {} # key -> code -_inverted_registry = {} # code -> key -_extension_cache = {} # code -> object -# Don't ever rebind those names: cPickle grabs a reference to them when -# it's initialized, and won't see a rebinding. - -def add_extension(module, name, code): - """Register an extension code.""" - code = int(code) - if not 1 <= code <= 0x7fffffff: - raise ValueError, "code out of range" - key = (module, name) - if (_extension_registry.get(key) == code and - _inverted_registry.get(code) == key): - return # Redundant registrations are benign - if key in _extension_registry: - raise ValueError("key %s is already registered with code %s" % - (key, _extension_registry[key])) - if code in _inverted_registry: - raise ValueError("code %s is already in use for key %s" % - (code, _inverted_registry[code])) - _extension_registry[key] = code - _inverted_registry[code] = key - -def remove_extension(module, name, code): - """Unregister an extension code. For testing only.""" - key = (module, name) - if (_extension_registry.get(key) != code or - _inverted_registry.get(code) != key): - raise ValueError("key %s is not registered with code %s" % - (key, code)) - del _extension_registry[key] - del _inverted_registry[code] - if code in _extension_cache: - del _extension_cache[code] - -def clear_extension_cache(): - _extension_cache.clear() - -# Standard extension code assignments - -# Reserved ranges - -# First Last Count Purpose -# 1 127 127 Reserved for Python standard library -# 128 191 64 Reserved for Zope -# 192 239 48 Reserved for 3rd parties -# 240 255 16 Reserved for private use (will never be assigned) -# 256 Inf Inf Reserved for future assignment - -# Extension codes are assigned by the Python Software Foundation. Modified: pypy/dist/pypy/appspace/types.py ============================================================================== --- pypy/dist/pypy/appspace/types.py (original) +++ pypy/dist/pypy/appspace/types.py Mon Jan 24 11:14:30 2005 @@ -69,9 +69,14 @@ pass del g +# checking whether we can make copy_reg happy +##class _C: +## def _m(self): pass +##ClassType = type(_C) +class ClassType: pass class _C: - def _m(self): pass -ClassType = type(_C) + def _m(self):pass +## end of testing hack try: UnboundMethodType = type(_C._m) # Same as MethodType except AttributeError: From tismer at codespeak.net Mon Jan 24 11:37:43 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 11:37:43 +0100 (MET) Subject: [pypy-svn] r8514 - pypy/dist/pypy/module Message-ID: <20050124103743.1ED8927B4F@code1.codespeak.net> Author: tismer Date: Mon Jan 24 11:37:42 2005 New Revision: 8514 Modified: pypy/dist/pypy/module/sysmodule.py Log: added getfilesystemencoding to sysmodule.py . This makes the Python testing system working at all. The function is trivial and can really live in appspace. Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Mon Jan 24 11:37:42 2005 @@ -40,3 +40,17 @@ # NB. this is slightly more complicated in CPython, # see e.g. the difference with >>> print 5,; 8 print `obj` + +def getfilesystemencoding(): + """getfilesystemencoding() -> string + +Return the encoding used to convert Unicode filenames in +operating system filenames.""" + + if platform == "win32": + encoding = "mcbs" + elif platform == "darwin": + encoding = "utf-8" + else: + encoding = None + return encoding From mwh at codespeak.net Mon Jan 24 11:50:20 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Mon, 24 Jan 2005 11:50:20 +0100 (MET) Subject: [pypy-svn] r8515 - pypy/dist/pypy/annotation Message-ID: <20050124105020.C55CE27B4F@code1.codespeak.net> Author: mwh Date: Mon Jan 24 11:50:20 2005 New Revision: 8515 Modified: pypy/dist/pypy/annotation/binaryop.py Log: kill references to SomeFunction in old commented out code. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Mon Jan 24 11:50:20 2005 @@ -29,14 +29,6 @@ for opname in BINARY_OPERATIONS: missing_operation(pairtype(SomeObject, SomeObject), opname) -#class __extend__(pairtype(SomeFunction, SomeObject)): -# def union((obj1, obj2)): -# raise TypeError, "generalizing not allowed: %r AND %r" % (obj1, obj2) -# -#class __extend__(pairtype(SomeObject, SomeFunction)): -# def union((obj1, obj2)): -# raise TypeError, "generalizing not allowed: %r AND %r" % (obj2, obj1) - class __extend__(pairtype(SomeObject, SomeObject)): def union((obj1, obj2)): From mwh at codespeak.net Mon Jan 24 11:51:42 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Mon, 24 Jan 2005 11:51:42 +0100 (MET) Subject: [pypy-svn] r8516 - pypy/dist/pypy/annotation Message-ID: <20050124105142.8E67427B4F@code1.codespeak.net> Author: mwh Date: Mon Jan 24 11:51:42 2005 New Revision: 8516 Modified: pypy/dist/pypy/annotation/binaryop.py Log: More commmented out SomeFunction-mentioning code removal. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Mon Jan 24 11:51:42 2005 @@ -35,11 +35,6 @@ if obj1 == obj2: return obj1 else: - #if isinstance(obj1, SomeFunction) or \ - # isinstance(obj2, SomeFunction): - # raise TypeError, ("generalizing not allowed:" - # "%r AND %r" % (obj1, obj2)) - # result = SomeObject() # try to preserve the origin of SomeObjects if obj1 == result: From mwh at codespeak.net Mon Jan 24 12:14:43 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Mon, 24 Jan 2005 12:14:43 +0100 (MET) Subject: [pypy-svn] r8517 - in pypy/dist/pypy: annotation translator Message-ID: <20050124111443.B583227B4F@code1.codespeak.net> Author: mwh Date: Mon Jan 24 12:14:43 2005 New Revision: 8517 Modified: pypy/dist/pypy/annotation/bookkeeper.py pypy/dist/pypy/translator/annrpython.py Log: move detection and discarding of 'inappropriate' *calls up a level (from the annotator to the bookkeeper) Modified: pypy/dist/pypy/annotation/bookkeeper.py ============================================================================== --- pypy/dist/pypy/annotation/bookkeeper.py (original) +++ pypy/dist/pypy/annotation/bookkeeper.py Mon Jan 24 12:14:43 2005 @@ -9,6 +9,8 @@ from pypy.interpreter.miscutils import getthreadlocals from pypy.tool.hack import func_with_new_name from pypy.interpreter.pycode import CO_VARARGS +from pypy.interpreter.pycode import cpython_code_signature +from pypy.interpreter.argument import ArgErr class Bookkeeper: """The log of choices that have been made while analysing the operations. @@ -234,7 +236,20 @@ func = self.specialize_by_key(func, nbargs, name='%s__%d' % (func.func_name, nbargs)) - return self.annotator.recursivecall(func, self.position_key, args) + + # parse the arguments according to the function we are calling + signature = cpython_code_signature(func.func_code) + defs_s = [] + if func.func_defaults: + for x in func.func_defaults: + defs_s.append(self.immutablevalue(x)) + try: + inputcells = args.match_signature(signature, defs_s) + except ArgErr, e: + print 'IGNORED', e # hopefully temporary hack + return SomeImpossibleValue() + + return self.annotator.recursivecall(func, self.position_key, inputcells) def specialize_by_key(self, thing, key, name=None): key = thing, key Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Mon Jan 24 12:14:43 2005 @@ -8,8 +8,6 @@ from pypy.objspace.flow.model import Variable, Constant, UndefinedConstant from pypy.objspace.flow.model import SpaceOperation, FunctionGraph from pypy.objspace.flow.model import last_exception, last_exc_value -from pypy.interpreter.pycode import cpython_code_signature -from pypy.interpreter.argument import ArgErr class AnnotatorError(Exception): @@ -177,7 +175,7 @@ #___ interface for annotator.factory _______ - def recursivecall(self, func, position_key, args): + def recursivecall(self, func, position_key, inputcells): parent_fn, parent_block, parent_index = position_key graph = self.translator.getflowgraph(func, parent_fn, position_key) @@ -187,18 +185,6 @@ callpositions = self.notify.setdefault(graph.returnblock, {}) callpositions[position_key] = True - # parse the arguments according to the function we are calling - signature = cpython_code_signature(func.func_code) - defs_s = [] - if func.func_defaults: - for x in func.func_defaults: - defs_s.append(self.bookkeeper.immutablevalue(x)) - try: - inputcells = args.match_signature(signature, defs_s) - except ArgErr, e: - print 'IGNORED', e # hopefully temporary hack - return annmodel.SomeImpossibleValue() - # generalize the function's input arguments self.addpendingblock(func, graph.startblock, inputcells, position_key) From arigo at codespeak.net Mon Jan 24 12:22:20 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 12:22:20 +0100 (MET) Subject: [pypy-svn] r8518 - pypy/dist/pypy/interpreter Message-ID: <20050124112220.456C227B4F@code1.codespeak.net> Author: arigo Date: Mon Jan 24 12:22:20 2005 New Revision: 8518 Modified: pypy/dist/pypy/interpreter/miscutils.py Log: Explicitely raise ValueError on a call to Stack.top(). Modified: pypy/dist/pypy/interpreter/miscutils.py ============================================================================== --- pypy/dist/pypy/interpreter/miscutils.py (original) +++ pypy/dist/pypy/interpreter/miscutils.py Mon Jan 24 12:22:20 2005 @@ -30,6 +30,8 @@ def top(self, position=0): """'position' is 0 for the top of the stack, 1 for the item below, and so on. It must not be negative.""" + if position < 0: + raise ValueError, 'negative stack position' return self.items[~position] def depth(self): From tismer at codespeak.net Mon Jan 24 12:25:38 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 12:25:38 +0100 (MET) Subject: [pypy-svn] r8519 - pypy/dist/pypy/module Message-ID: <20050124112538.29C8D27B4F@code1.codespeak.net> Author: tismer Date: Mon Jan 24 12:25:38 2005 New Revision: 8519 Modified: pypy/dist/pypy/module/sysinterp.py Log: sys._getframe behaves nicely, now and passes the tests. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Mon Jan 24 12:25:38 2005 @@ -106,9 +106,16 @@ ## space.call_method(w_stdout, 'write', ## space.setitem(space.w_builtins, w('_'), w_x) -def _getframe(): - # XXX No Argument Accepted Yet - f = space.getexecutioncontext().framestack.items[-1] +def _getframe(w_depth=0): + depth = space.int_w(w_depth) + try: + f = space.getexecutioncontext().framestack.top(depth) + except IndexError: + raise OperationError(space.w_ValueError, + space.wrap("call stack is not deep enough")) + except ValueError: + raise OperationError(space.w_ValueError, + space.wrap("frame index must not be negative")) return space.wrap(f) def exc_info(): From mwh at codespeak.net Mon Jan 24 12:28:05 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Mon, 24 Jan 2005 12:28:05 +0100 (MET) Subject: [pypy-svn] r8520 - pypy/dist/pypy/annotation Message-ID: <20050124112805.B89F127B4F@code1.codespeak.net> Author: mwh Date: Mon Jan 24 12:28:05 2005 New Revision: 8520 Modified: pypy/dist/pypy/annotation/unaryop.py Log: Implement SomeBuiltin.call. It Seems To Work(tm) but review appreciated. SomeBuiltin.simple_call could be removed, I think, but to no great benefit. Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Mon Jan 24 12:28:05 2005 @@ -73,7 +73,7 @@ return obj.call(Arguments.fromshape(space, s_shape.const, args_s)) def call(obj, args): - #raise Exception, "cannot follow call_args%r" % (obj_and_args,) + #raise Exception, "cannot follow call_args%r" % ((obj, args),) print "*** cannot follow call(%r, %r)" % (obj, args) return SomeObject() @@ -180,6 +180,14 @@ else: return bltn.analyser(*args) + def call(bltn, args): + args, kw = args.unpack() + assert not kw, "don't call builtins with keywords arguments" + if bltn.s_self is not None: + return bltn.analyser(bltn.s_self, *args) + else: + return bltn.analyser(*args) + class __extend__(SomePBC): From tismer at codespeak.net Mon Jan 24 12:52:26 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 12:52:26 +0100 (MET) Subject: [pypy-svn] r8521 - pypy/dist/pypy/module Message-ID: <20050124115226.D130127B4F@code1.codespeak.net> Author: tismer Date: Mon Jan 24 12:52:26 2005 New Revision: 8521 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: sys.get/setrecursionlevel are implemented now. Norte that they get/set a variable, but this is not used anywhere else, yet. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Mon Jan 24 12:52:26 2005 @@ -118,6 +118,33 @@ space.wrap("frame index must not be negative")) return space.wrap(f) +# directly from the C code in ceval.c, might be moved somewhere else. + +recursion_limit = 1000 + +def setrecursionlimit(w_new_limit): + """setrecursionlimit(n) + +Set the maximum depth of the Python interpreter stack to n. This +limit prevents infinite recursion from causing an overflow of the C +stack and crashing Python. The highest possible limit is platform +dependent.""" + new_limit = space.int_w(w_new_limit) + if new_limit <= 0: + raise OperationError(space.w_ValueError, + space.wrap("recursion limit must be positive")) + global recursion_limit + recursion_limit = new_limit + +def getrecursionlimit(): + """getrecursionlimit() + +Return the current value of the recursion limit, the maximum depth +of the Python interpreter stack. This limit prevents infinite +recursion from causing an overflow of the C stack and crashing Python.""" + + return space.newint(recursion_limit) + def exc_info(): operror = space.getexecutioncontext().sys_exc_info() if operror is None: Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Mon Jan 24 12:52:26 2005 @@ -16,6 +16,7 @@ # Functions from interpreter-level from __interplevel__ import _getframe, exc_info, pypy_getudir +from __interplevel__ import _getframe, getrecursionlimit, setrecursionlimit # Dummy executable = '' From arigo at codespeak.net Mon Jan 24 13:39:54 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 13:39:54 +0100 (MET) Subject: [pypy-svn] r8523 - pypy/dist/pypy/interpreter Message-ID: <20050124123954.BCD1527B4B@code1.codespeak.net> Author: arigo Date: Mon Jan 24 13:39:54 2005 New Revision: 8523 Modified: pypy/dist/pypy/interpreter/main.py Log: No longer used. Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Mon Jan 24 13:39:54 2005 @@ -19,8 +19,6 @@ w = space.wrap w_code = compile(source, filename, cmd, 0, 0) - ec = executioncontext.ExecutionContext(space) - mainmodule = module.Module(space, space.wrap("__main__")) w_globals = mainmodule.w_dict From arigo at codespeak.net Mon Jan 24 13:52:27 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 13:52:27 +0100 (MET) Subject: [pypy-svn] r8524 - pypy/dist/pypy/objspace/std Message-ID: <20050124125227.2FB2727B4B@code1.codespeak.net> Author: arigo Date: Mon Jan 24 13:52:27 2005 New Revision: 8524 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: Re-enabled space.wrap(1j) -> instance of W_TypeObject(complex) Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Mon Jan 24 13:52:27 2005 @@ -243,12 +243,13 @@ return W_ListObject(self, wrappeditems) if isinstance(x, long): return W_LongObject(self, x) -## if isinstance(x, complex): -## # XXX is this right? YYY no, this is wrong right now (CT) -## c = self.getitem(self.w_builtins, self.wrap("complex")) -## return self.call_function(c, -## self.wrap(x.real), -## self.wrap(x.imag)) + if isinstance(x, complex): + # XXX is this right? YYY no, this is wrong right now (CT) + # ZZZ hum, seems necessary for complex literals in co_consts (AR) + c = self.getitem(self.w_builtins, self.wrap("complex")) + return self.call_function(c, + self.wrap(x.real), + self.wrap(x.imag)) if isinstance(x, BaseWrappable): w_result = x.__spacebind__(self) #print 'wrapping', x, '->', w_result From arigo at codespeak.net Mon Jan 24 14:31:33 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 14:31:33 +0100 (MET) Subject: [pypy-svn] r8525 - pypy/dist/pypy/objspace/std Message-ID: <20050124133133.A7C8127B5D@code1.codespeak.net> Author: arigo Date: Mon Jan 24 14:31:33 2005 New Revision: 8525 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: 3 lines not needed any more. Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Mon Jan 24 14:31:33 2005 @@ -290,9 +290,6 @@ def newstring(self, chars_w): try: chars = [chr(self.int_w(w_c)) for w_c in chars_w] - except TypeError: # chr(not-an-integer) - raise OperationError(self.w_TypeError, - self.wrap("an integer is required")) except ValueError: # chr(out-of-range) raise OperationError(self.w_ValueError, self.wrap("character code not in range(256)")) From arigo at codespeak.net Mon Jan 24 14:32:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 14:32:26 +0100 (MET) Subject: [pypy-svn] r8526 - in pypy/dist/pypy: interpreter module Message-ID: <20050124133226.4A10927B5D@code1.codespeak.net> Author: arigo Date: Mon Jan 24 14:32:26 2005 New Revision: 8526 Modified: pypy/dist/pypy/interpreter/error.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: Implemented sys.exc_clear(). Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Mon Jan 24 14:32:26 2005 @@ -27,6 +27,12 @@ self.application_traceback = tb self.debug_excs = [] + def clear(self, space): + # for sys.exc_clear() + self.w_type = space.w_None + self.w_value = space.w_None + self.application_traceback = None + def match(self, space, w_check_class): "Check if this application-level exception matches 'w_check_class'." return space.exception_match(self.w_type, w_check_class) Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Mon Jan 24 14:32:26 2005 @@ -153,6 +153,11 @@ return space.newtuple([operror.w_type,operror.w_value, space.wrap(operror.application_traceback)]) +def exc_clear(): + operror = space.getexecutioncontext().sys_exc_info() + if operror is not None: + operror.clear(space) + def pypy_getudir(): from pypy.tool.udir import udir return space.wrap(str(udir)) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Mon Jan 24 14:32:26 2005 @@ -15,7 +15,7 @@ from __interplevel__ import pypy_objspaceclass # Functions from interpreter-level -from __interplevel__ import _getframe, exc_info, pypy_getudir +from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir from __interplevel__ import _getframe, getrecursionlimit, setrecursionlimit # Dummy From tismer at codespeak.net Mon Jan 24 14:54:17 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 14:54:17 +0100 (MET) Subject: [pypy-svn] r8527 - pypy/dist/pypy/module Message-ID: <20050124135417.F051F27B58@code1.codespeak.net> Author: tismer Date: Mon Jan 24 14:54:17 2005 New Revision: 8527 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: implemented get/setcheckinterval Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Mon Jan 24 14:54:17 2005 @@ -145,6 +145,21 @@ return space.newint(recursion_limit) +checkinterval = 100 + +def setcheckinterval(w_interval): + """setcheckinterval(n) + +Tell the Python interpreter to check for asynchronous events every +n instructions. This also affects how often thread switches occur.""" + global checkinterval + checkinterval = space.int_w(w_interval) + +def getcheckinterval(): + """getcheckinterval() -> current check interval; see setcheckinterval().""" + return space.newint(checkinterval) + + def exc_info(): operror = space.getexecutioncontext().sys_exc_info() if operror is None: Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Mon Jan 24 14:54:17 2005 @@ -16,7 +16,8 @@ # Functions from interpreter-level from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir -from __interplevel__ import _getframe, getrecursionlimit, setrecursionlimit +from __interplevel__ import getrecursionlimit, setrecursionlimit +from __interplevel__ import getcheckinterval, setcheckinterval # Dummy executable = '' From arigo at codespeak.net Mon Jan 24 15:11:27 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 24 Jan 2005 15:11:27 +0100 (MET) Subject: [pypy-svn] r8528 - pypy/dist/pypy/interpreter Message-ID: <20050124141127.8172C27B58@code1.codespeak.net> Author: arigo Date: Mon Jan 24 15:11:27 2005 New Revision: 8528 Modified: pypy/dist/pypy/interpreter/module.py pypy/dist/pypy/interpreter/typedef.py Log: Added a method 'ModuleType.__getattr__' that handles the special attributes sys.exc_{type,value,traceback}. It also gives a nicer error message for module attributes not found. Modified: pypy/dist/pypy/interpreter/module.py ============================================================================== --- pypy/dist/pypy/interpreter/module.py (original) +++ pypy/dist/pypy/interpreter/module.py Mon Jan 24 15:11:27 2005 @@ -3,6 +3,7 @@ """ from pypy.interpreter.baseobjspace import Wrappable +from pypy.interpreter.error import OperationError class Module(Wrappable): """A module.""" @@ -34,3 +35,34 @@ space.setitem(self.w_dict, space.wrap('__name__'), w_name) if w_doc is not None: space.setitem(self.w_dict, space.wrap('__doc__'), w_doc) + + def descr_module__getattr__(self, w_attr): + space = self.space + attr = space.str_w(w_attr) + # ______ for the 'sys' module only _____ XXX generalize + if self is space.sys: + if attr == 'exc_type': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return operror.w_type + if attr == 'exc_value': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return operror.w_value + if attr == 'exc_traceback': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return space.wrap(operror.application_traceback) + # produce a nice error message that shows the name of the module + try: + name = space.str_w(self.w_name) + except OperationError: + name = '?' + msg = "'%s' module has no attribute '%s'" % (name, attr) + raise OperationError(space.w_AttributeError, space.wrap(msg)) Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Mon Jan 24 15:11:27 2005 @@ -219,6 +219,7 @@ __new__ = interp2app(Module.descr_module__new__.im_func), __init__ = interp2app(Module.descr_module__init__.im_func), __dict__ = interp_dict_descr, + __getattr__ = interp2app(Module.descr_module__getattr__.im_func), ) getset_func_doc = GetSetProperty(Function.fget_func_doc, From tismer at codespeak.net Mon Jan 24 15:19:19 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 24 Jan 2005 15:19:19 +0100 (MET) Subject: [pypy-svn] r8529 - pypy/dist/pypy/appspace Message-ID: <20050124141919.F36FF27B4A@code1.codespeak.net> Author: tismer Date: Mon Jan 24 15:19:19 2005 New Revision: 8529 Added: pypy/dist/pypy/appspace/traceback.py Log: added a slightly modified version of traceback.py . This file will vanish hopefully quickly, after CPython gets more general exception classes. Added: pypy/dist/pypy/appspace/traceback.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/traceback.py Mon Jan 24 15:19:19 2005 @@ -0,0 +1,286 @@ +"""Extract, format and print information about Python stack traces.""" + +import linecache +import sys +import types + +__all__ = ['extract_stack', 'extract_tb', 'format_exception', + 'format_exception_only', 'format_list', 'format_stack', + 'format_tb', 'print_exc', 'print_exception', 'print_last', + 'print_stack', 'print_tb', 'tb_lineno'] + +def _print(file, str='', terminator='\n'): + file.write(str+terminator) + + +def print_list(extracted_list, file=None): + """Print the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.""" + if file is None: + file = sys.stderr + for filename, lineno, name, line in extracted_list: + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + if line: + _print(file, ' %s' % line.strip()) + +def format_list(extracted_list): + """Format a list of traceback entry tuples for printing. + + Given a list of tuples as returned by extract_tb() or + extract_stack(), return a list of strings ready for printing. + Each string in the resulting list corresponds to the item with the + same index in the argument list. Each string ends in a newline; + the strings may contain internal newlines as well, for those items + whose source text line is not None. + """ + list = [] + for filename, lineno, name, line in extracted_list: + item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) + if line: + item = item + ' %s\n' % line.strip() + list.append(item) + return list + + +def print_tb(tb, limit=None, file=None): + """Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + """ + if file is None: + file = sys.stderr + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + line = linecache.getline(filename, lineno) + if line: _print(file, ' ' + line.strip()) + tb = tb.tb_next + n = n+1 + +def format_tb(tb, limit = None): + """A shorthand for 'format_list(extract_stack(f, limit)).""" + return format_list(extract_tb(tb, limit)) + +def extract_tb(tb, limit = None): + """Return list of up to limit pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If + 'limit' is omitted or None, all entries are extracted. A + pre-processed stack trace entry is a quadruple (filename, line + number, function name, text) representing the information that is + usually printed for a stack trace. The text is a string with + leading and trailing whitespace stripped; if the source is not + available it is None. + """ + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = line.strip() + else: line = None + list.append((filename, lineno, name, line)) + tb = tb.tb_next + n = n+1 + return list + + +def print_exception(etype, value, tb, limit=None, file=None): + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + """ + if file is None: + file = sys.stderr + if tb: + _print(file, 'Traceback (most recent call last):') + print_tb(tb, limit, file) + lines = format_exception_only(etype, value) + for line in lines[:-1]: + _print(file, line, ' ') + _print(file, lines[-1], '') + +def format_exception(etype, value, tb, limit = None): + """Format a stack trace and the exception information. + + The arguments have the same meaning as the corresponding arguments + to print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception(). + """ + if tb: + list = ['Traceback (most recent call last):\n'] + list = list + format_tb(tb, limit) + else: + list = [] + list = list + format_exception_only(etype, value) + return list + +def format_exception_only(etype, value): + """Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. Normally, the list contains a + single string; however, for SyntaxError exceptions, it contains + several lines that (when printed) display detailed information + about where the syntax error occurred. The message indicating + which exception occurred is the always last string in the list. + """ + list = [] + # the following line is the only change against Py 2.3.3 + # Python will change here, anyway. Drop this file, then. + if isinstance(etype, (types.ClassType, type)): + stype = etype.__name__ + else: + stype = etype + if value is None: + list.append(str(stype) + '\n') + else: + if etype is SyntaxError: + try: + msg, (filename, lineno, offset, line) = value + except: + pass + else: + if not filename: filename = "" + list.append(' File "%s", line %d\n' % + (filename, lineno)) + if line is not None: + i = 0 + while i < len(line) and line[i].isspace(): + i = i+1 + list.append(' %s\n' % line.strip()) + if offset is not None: + s = ' ' + for c in line[i:offset-1]: + if c.isspace(): + s = s + c + else: + s = s + ' ' + list.append('%s^\n' % s) + value = msg + s = _some_str(value) + if s: + list.append('%s: %s\n' % (str(stype), s)) + else: + list.append('%s\n' % str(stype)) + return list + +def _some_str(value): + try: + return str(value) + except: + return '' % type(value).__name__ + + +def print_exc(limit=None, file=None): + """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. + (In fact, it uses sys.exc_info() to retrieve the same information + in a thread-safe way.)""" + if file is None: + file = sys.stderr + try: + etype, value, tb = sys.exc_info() + print_exception(etype, value, tb, limit, file) + finally: + etype = value = tb = None + +def print_last(limit=None, file=None): + """This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.""" + if file is None: + file = sys.stderr + print_exception(sys.last_type, sys.last_value, sys.last_traceback, + limit, file) + + +def print_stack(f=None, limit=None, file=None): + """Print a stack trace from its invocation point. + + The optional 'f' argument can be used to specify an alternate + stack frame at which to start. The optional 'limit' and 'file' + arguments have the same meaning as for print_exception(). + """ + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + print_list(extract_stack(f, limit), file) + +def format_stack(f=None, limit=None): + """Shorthand for 'format_list(extract_stack(f, limit))'.""" + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + return format_list(extract_stack(f, limit)) + +def extract_stack(f=None, limit = None): + """Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The + optional 'f' and 'limit' arguments have the same meaning as for + print_stack(). Each item in the list is a quadruple (filename, + line number, function name, text), and the entries are in order + from oldest to newest stack frame. + """ + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while f is not None and (limit is None or n < limit): + lineno = f.f_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = line.strip() + else: line = None + list.append((filename, lineno, name, line)) + f = f.f_back + n = n+1 + list.reverse() + return list + +def tb_lineno(tb): + """Calculate correct line number of traceback given in tb. + + Obsolete in 2.3. + """ + return tb.tb_lineno From sanxiyn at codespeak.net Tue Jan 25 03:45:22 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 25 Jan 2005 03:45:22 +0100 (MET) Subject: [pypy-svn] r8531 - in pypy/dist/pypy: . appspace appspace/test documentation objspace/test tool tool/test translator/java/test translator/tool Message-ID: <20050125024522.7499327B58@code1.codespeak.net> Author: sanxiyn Date: Tue Jan 25 03:45:22 2005 New Revision: 8531 Modified: pypy/dist/pypy/appspace/struct.py (props changed) pypy/dist/pypy/appspace/test/conftest.py (props changed) pypy/dist/pypy/appspace/test/test_struct.py (props changed) pypy/dist/pypy/appspace/traceback.py (contents, props changed) pypy/dist/pypy/conftest.py (props changed) pypy/dist/pypy/documentation/cmodules.txt (props changed) pypy/dist/pypy/documentation/developers.txt (props changed) pypy/dist/pypy/documentation/index.txt (contents, props changed) pypy/dist/pypy/documentation/newrepolayout.txt (props changed) pypy/dist/pypy/documentation/optionaltool.txt (contents, props changed) pypy/dist/pypy/objspace/test/test_descriptor.py (props changed) pypy/dist/pypy/tool/example_pytest.py (props changed) pypy/dist/pypy/tool/test/test_conftest1.py (props changed) pypy/dist/pypy/translator/java/test/__init__.py (props changed) pypy/dist/pypy/translator/tool/graphserver.py (props changed) Log: fixeol Modified: pypy/dist/pypy/appspace/traceback.py ============================================================================== --- pypy/dist/pypy/appspace/traceback.py (original) +++ pypy/dist/pypy/appspace/traceback.py Tue Jan 25 03:45:22 2005 @@ -1,286 +1,286 @@ -"""Extract, format and print information about Python stack traces.""" - -import linecache -import sys -import types - -__all__ = ['extract_stack', 'extract_tb', 'format_exception', - 'format_exception_only', 'format_list', 'format_stack', - 'format_tb', 'print_exc', 'print_exception', 'print_last', - 'print_stack', 'print_tb', 'tb_lineno'] - -def _print(file, str='', terminator='\n'): - file.write(str+terminator) - - -def print_list(extracted_list, file=None): - """Print the list of tuples as returned by extract_tb() or - extract_stack() as a formatted stack trace to the given file.""" - if file is None: - file = sys.stderr - for filename, lineno, name, line in extracted_list: - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - if line: - _print(file, ' %s' % line.strip()) - -def format_list(extracted_list): - """Format a list of traceback entry tuples for printing. - - Given a list of tuples as returned by extract_tb() or - extract_stack(), return a list of strings ready for printing. - Each string in the resulting list corresponds to the item with the - same index in the argument list. Each string ends in a newline; - the strings may contain internal newlines as well, for those items - whose source text line is not None. - """ - list = [] - for filename, lineno, name, line in extracted_list: - item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) - if line: - item = item + ' %s\n' % line.strip() - list.append(item) - return list - - -def print_tb(tb, limit=None, file=None): - """Print up to 'limit' stack trace entries from the traceback 'tb'. - - If 'limit' is omitted or None, all entries are printed. If 'file' - is omitted or None, the output goes to sys.stderr; otherwise - 'file' should be an open file or file-like object with a write() - method. - """ - if file is None: - file = sys.stderr - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - line = linecache.getline(filename, lineno) - if line: _print(file, ' ' + line.strip()) - tb = tb.tb_next - n = n+1 - -def format_tb(tb, limit = None): - """A shorthand for 'format_list(extract_stack(f, limit)).""" - return format_list(extract_tb(tb, limit)) - -def extract_tb(tb, limit = None): - """Return list of up to limit pre-processed entries from traceback. - - This is useful for alternate formatting of stack traces. If - 'limit' is omitted or None, all entries are extracted. A - pre-processed stack trace entry is a quadruple (filename, line - number, function name, text) representing the information that is - usually printed for a stack trace. The text is a string with - leading and trailing whitespace stripped; if the source is not - available it is None. - """ - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = line.strip() - else: line = None - list.append((filename, lineno, name, line)) - tb = tb.tb_next - n = n+1 - return list - - -def print_exception(etype, value, tb, limit=None, file=None): - """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. - - This differs from print_tb() in the following ways: (1) if - traceback is not None, it prints a header "Traceback (most recent - call last):"; (2) it prints the exception type and value after the - stack trace; (3) if type is SyntaxError and value has the - appropriate format, it prints the line where the syntax error - occurred with a caret on the next line indicating the approximate - position of the error. - """ - if file is None: - file = sys.stderr - if tb: - _print(file, 'Traceback (most recent call last):') - print_tb(tb, limit, file) - lines = format_exception_only(etype, value) - for line in lines[:-1]: - _print(file, line, ' ') - _print(file, lines[-1], '') - -def format_exception(etype, value, tb, limit = None): - """Format a stack trace and the exception information. - - The arguments have the same meaning as the corresponding arguments - to print_exception(). The return value is a list of strings, each - ending in a newline and some containing internal newlines. When - these lines are concatenated and printed, exactly the same text is - printed as does print_exception(). - """ - if tb: - list = ['Traceback (most recent call last):\n'] - list = list + format_tb(tb, limit) - else: - list = [] - list = list + format_exception_only(etype, value) - return list - -def format_exception_only(etype, value): - """Format the exception part of a traceback. - - The arguments are the exception type and value such as given by - sys.last_type and sys.last_value. The return value is a list of - strings, each ending in a newline. Normally, the list contains a - single string; however, for SyntaxError exceptions, it contains - several lines that (when printed) display detailed information - about where the syntax error occurred. The message indicating - which exception occurred is the always last string in the list. - """ - list = [] - # the following line is the only change against Py 2.3.3 - # Python will change here, anyway. Drop this file, then. - if isinstance(etype, (types.ClassType, type)): - stype = etype.__name__ - else: - stype = etype - if value is None: - list.append(str(stype) + '\n') - else: - if etype is SyntaxError: - try: - msg, (filename, lineno, offset, line) = value - except: - pass - else: - if not filename: filename = "" - list.append(' File "%s", line %d\n' % - (filename, lineno)) - if line is not None: - i = 0 - while i < len(line) and line[i].isspace(): - i = i+1 - list.append(' %s\n' % line.strip()) - if offset is not None: - s = ' ' - for c in line[i:offset-1]: - if c.isspace(): - s = s + c - else: - s = s + ' ' - list.append('%s^\n' % s) - value = msg - s = _some_str(value) - if s: - list.append('%s: %s\n' % (str(stype), s)) - else: - list.append('%s\n' % str(stype)) - return list - -def _some_str(value): - try: - return str(value) - except: - return '' % type(value).__name__ - - -def print_exc(limit=None, file=None): - """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. - (In fact, it uses sys.exc_info() to retrieve the same information - in a thread-safe way.)""" - if file is None: - file = sys.stderr - try: - etype, value, tb = sys.exc_info() - print_exception(etype, value, tb, limit, file) - finally: - etype = value = tb = None - -def print_last(limit=None, file=None): - """This is a shorthand for 'print_exception(sys.last_type, - sys.last_value, sys.last_traceback, limit, file)'.""" - if file is None: - file = sys.stderr - print_exception(sys.last_type, sys.last_value, sys.last_traceback, - limit, file) - - -def print_stack(f=None, limit=None, file=None): - """Print a stack trace from its invocation point. - - The optional 'f' argument can be used to specify an alternate - stack frame at which to start. The optional 'limit' and 'file' - arguments have the same meaning as for print_exception(). - """ - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - print_list(extract_stack(f, limit), file) - -def format_stack(f=None, limit=None): - """Shorthand for 'format_list(extract_stack(f, limit))'.""" - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - return format_list(extract_stack(f, limit)) - -def extract_stack(f=None, limit = None): - """Extract the raw traceback from the current stack frame. - - The return value has the same format as for extract_tb(). The - optional 'f' and 'limit' arguments have the same meaning as for - print_stack(). Each item in the list is a quadruple (filename, - line number, function name, text), and the entries are in order - from oldest to newest stack frame. - """ - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while f is not None and (limit is None or n < limit): - lineno = f.f_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = line.strip() - else: line = None - list.append((filename, lineno, name, line)) - f = f.f_back - n = n+1 - list.reverse() - return list - -def tb_lineno(tb): - """Calculate correct line number of traceback given in tb. - - Obsolete in 2.3. - """ - return tb.tb_lineno +"""Extract, format and print information about Python stack traces.""" + +import linecache +import sys +import types + +__all__ = ['extract_stack', 'extract_tb', 'format_exception', + 'format_exception_only', 'format_list', 'format_stack', + 'format_tb', 'print_exc', 'print_exception', 'print_last', + 'print_stack', 'print_tb', 'tb_lineno'] + +def _print(file, str='', terminator='\n'): + file.write(str+terminator) + + +def print_list(extracted_list, file=None): + """Print the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.""" + if file is None: + file = sys.stderr + for filename, lineno, name, line in extracted_list: + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + if line: + _print(file, ' %s' % line.strip()) + +def format_list(extracted_list): + """Format a list of traceback entry tuples for printing. + + Given a list of tuples as returned by extract_tb() or + extract_stack(), return a list of strings ready for printing. + Each string in the resulting list corresponds to the item with the + same index in the argument list. Each string ends in a newline; + the strings may contain internal newlines as well, for those items + whose source text line is not None. + """ + list = [] + for filename, lineno, name, line in extracted_list: + item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) + if line: + item = item + ' %s\n' % line.strip() + list.append(item) + return list + + +def print_tb(tb, limit=None, file=None): + """Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + """ + if file is None: + file = sys.stderr + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + line = linecache.getline(filename, lineno) + if line: _print(file, ' ' + line.strip()) + tb = tb.tb_next + n = n+1 + +def format_tb(tb, limit = None): + """A shorthand for 'format_list(extract_stack(f, limit)).""" + return format_list(extract_tb(tb, limit)) + +def extract_tb(tb, limit = None): + """Return list of up to limit pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If + 'limit' is omitted or None, all entries are extracted. A + pre-processed stack trace entry is a quadruple (filename, line + number, function name, text) representing the information that is + usually printed for a stack trace. The text is a string with + leading and trailing whitespace stripped; if the source is not + available it is None. + """ + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = line.strip() + else: line = None + list.append((filename, lineno, name, line)) + tb = tb.tb_next + n = n+1 + return list + + +def print_exception(etype, value, tb, limit=None, file=None): + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + """ + if file is None: + file = sys.stderr + if tb: + _print(file, 'Traceback (most recent call last):') + print_tb(tb, limit, file) + lines = format_exception_only(etype, value) + for line in lines[:-1]: + _print(file, line, ' ') + _print(file, lines[-1], '') + +def format_exception(etype, value, tb, limit = None): + """Format a stack trace and the exception information. + + The arguments have the same meaning as the corresponding arguments + to print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception(). + """ + if tb: + list = ['Traceback (most recent call last):\n'] + list = list + format_tb(tb, limit) + else: + list = [] + list = list + format_exception_only(etype, value) + return list + +def format_exception_only(etype, value): + """Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. Normally, the list contains a + single string; however, for SyntaxError exceptions, it contains + several lines that (when printed) display detailed information + about where the syntax error occurred. The message indicating + which exception occurred is the always last string in the list. + """ + list = [] + # the following line is the only change against Py 2.3.3 + # Python will change here, anyway. Drop this file, then. + if isinstance(etype, (types.ClassType, type)): + stype = etype.__name__ + else: + stype = etype + if value is None: + list.append(str(stype) + '\n') + else: + if etype is SyntaxError: + try: + msg, (filename, lineno, offset, line) = value + except: + pass + else: + if not filename: filename = "" + list.append(' File "%s", line %d\n' % + (filename, lineno)) + if line is not None: + i = 0 + while i < len(line) and line[i].isspace(): + i = i+1 + list.append(' %s\n' % line.strip()) + if offset is not None: + s = ' ' + for c in line[i:offset-1]: + if c.isspace(): + s = s + c + else: + s = s + ' ' + list.append('%s^\n' % s) + value = msg + s = _some_str(value) + if s: + list.append('%s: %s\n' % (str(stype), s)) + else: + list.append('%s\n' % str(stype)) + return list + +def _some_str(value): + try: + return str(value) + except: + return '' % type(value).__name__ + + +def print_exc(limit=None, file=None): + """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. + (In fact, it uses sys.exc_info() to retrieve the same information + in a thread-safe way.)""" + if file is None: + file = sys.stderr + try: + etype, value, tb = sys.exc_info() + print_exception(etype, value, tb, limit, file) + finally: + etype = value = tb = None + +def print_last(limit=None, file=None): + """This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.""" + if file is None: + file = sys.stderr + print_exception(sys.last_type, sys.last_value, sys.last_traceback, + limit, file) + + +def print_stack(f=None, limit=None, file=None): + """Print a stack trace from its invocation point. + + The optional 'f' argument can be used to specify an alternate + stack frame at which to start. The optional 'limit' and 'file' + arguments have the same meaning as for print_exception(). + """ + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + print_list(extract_stack(f, limit), file) + +def format_stack(f=None, limit=None): + """Shorthand for 'format_list(extract_stack(f, limit))'.""" + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + return format_list(extract_stack(f, limit)) + +def extract_stack(f=None, limit = None): + """Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The + optional 'f' and 'limit' arguments have the same meaning as for + print_stack(). Each item in the list is a quadruple (filename, + line number, function name, text), and the entries are in order + from oldest to newest stack frame. + """ + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while f is not None and (limit is None or n < limit): + lineno = f.f_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = line.strip() + else: line = None + list.append((filename, lineno, name, line)) + f = f.f_back + n = n+1 + list.reverse() + return list + +def tb_lineno(tb): + """Calculate correct line number of traceback given in tb. + + Obsolete in 2.3. + """ + return tb.tb_lineno Modified: pypy/dist/pypy/documentation/index.txt ============================================================================== --- pypy/dist/pypy/documentation/index.txt (original) +++ pypy/dist/pypy/documentation/index.txt Tue Jan 25 03:45:22 2005 @@ -1,88 +1,88 @@ -================================================= -PyPy - a Python_ implementation written in Python -================================================= - -recently-modified_ - -.. _Python: http://www.python.org/dev/doc/maint24/ref/ref.html - -Here are some good entry points into PyPy's world: - - * architecture_: - a technical overview of PyPy's current architecture - - * howtopypy_: - provides some hands-on instructions for getting started, - including a two-liner to run PyPy on your computer. - - -Before doing pypy coding, you might also take a look at these -developer-specific instructions: - - * coding-style_: - covers pypy coding conventions - - * optionaltool_: - there are some optional tools we use for pypy. - - * wrapping_: - a description of the crucial distinction between application-level and - interpreter-level objects (without understanding this you might - have difficulties understanding PyPy's source code). - - * oscon2003-paper_: - presentation to OSCON on what pypy is about and why you should care - - * testdesign_: - pypy is a test-driven development project. Read here to find out - more about how we're doing testing. - -Further reading / related projects ----------------------------------- - -* An interesting thread on an HP tech report that may be proof the pypy is feasible_ . (We already knew that...) - -* An interesting thread on why VHLL rock_ . (We already knew that too.) - -* A thread on Python in Scheme_ . - -* An intriguting project, FlashMob_ - creating an adhoc supercomputer. - -* A discussion on Python and lisp_ support - -* An interesting repository_ of papers by Xerox Parc members, with quite a few issues more or less relevant to PyPy. - -* A thread on the gnu lightning_ project."GNU lightning is a library that generates assembly language code at run-time; it is very fast, making it ideal for Just-In-Time compilers, and it abstracts over the target CPU, as it exposes to the clients a standardized RISC instruction set inspired by the MIPS and SPARC chips." - -* A project to create a Low Level Virtual Machine (LLVM_) and a PyPy-LLVM_ discussion, and conversation_ between PyPy and LLVM. - -* A thread discussing the xhelix_ python C extension implementing Helix encryption and authentication, which may be interesting to use as a pypy performance test at some point. - -* A paper for PyCon 2004: "IronPython_ is a new implementation of the Python language targeting the Common Language Runtime (CLR). It compiles python programs into bytecode (IL) that will run on either Microsoft's .NET or the Open Source Mono platform. IronPython includes an interactive interpreter and transparent on-the-fly compilation of source files just like standard Python. In addition, IronPython supports static compilation of Python code to produce static executables (.exe's) that can be run directly or static libraries (.dll's) that can be called from other CLR languages." - -* A comparison of Python and Pliant_ , an OS written in a python-like language. - - -.. _architecture: http://codespeak.net/pypy/index.cgi?doc/architecture.html -.. _oscon2003-paper: http://codespeak.net/pypy/index.cgi?doc/oscon2003-paper.html -.. _howtopypy: http://codespeak.net/pypy/index.cgi?doc/howtopypy.html -.. _readme: http://codespeak.net/pypy/index.cgi?doc/readme.html -.. _wrapping: http://codespeak.net/pypy/index.cgi?doc/wrapping.html -.. _coding-style: http://codespeak.net/pypy/index.cgi?doc/coding-style.html -.. _howtosvn: http://codespeak.net/pypy/index.cgi?doc/howtosvn.html -.. _optionaltool: http://codespeak.net/pypy/index.cgi?doc/optionaltool.html -.. _testdesign: http://codespeak.net/pypy/index.cgi?doc/testdesign.html -.. _feasible: http://codespeak.net/pipermail/pypy-dev/2004q2/001289.html -.. _rock: http://codespeak.net/pipermail/pypy-dev/2004q1/001255.html -.. _Scheme: http://codespeak.net/pipermail/pypy-dev/2004q1/001256.html -.. _FlashMob: http://www.flashmobcomputing.org/ -.. _lisp: http://codespeak.net/pipermail/pypy-dev/2003q4/001048.html -.. _repository: http://www2.parc.com/csl/groups/sda/publications.shtml -.. _lightning: http://codespeak.net/pipermail/pypy-dev/2003q4/001051.html -.. _LLVM: http://llvm.cs.uiuc.edu/ -.. _PyPy-LLVM: http://codespeak.net/pipermail/pypy-dev/2003q4/001115.html -.. _conversation: http://codespeak.net/pipermail/pypy-dev/2003q4/001119.html -.. _xhelix: http://codespeak.net/pipermail/pypy-dev/2003q4/001129.html -.. _IronPython: http://www.python.org/pycon/dc2004/papers/9/ -.. _pliant: http://pliant.cx -.. _recently-modified: http://codespeak.net/pypy/index.cgi?doc/recent +================================================= +PyPy - a Python_ implementation written in Python +================================================= + +recently-modified_ + +.. _Python: http://www.python.org/dev/doc/maint24/ref/ref.html + +Here are some good entry points into PyPy's world: + + * architecture_: + a technical overview of PyPy's current architecture + + * howtopypy_: + provides some hands-on instructions for getting started, + including a two-liner to run PyPy on your computer. + + +Before doing pypy coding, you might also take a look at these +developer-specific instructions: + + * coding-style_: + covers pypy coding conventions + + * optionaltool_: + there are some optional tools we use for pypy. + + * wrapping_: + a description of the crucial distinction between application-level and + interpreter-level objects (without understanding this you might + have difficulties understanding PyPy's source code). + + * oscon2003-paper_: + presentation to OSCON on what pypy is about and why you should care + + * testdesign_: + pypy is a test-driven development project. Read here to find out + more about how we're doing testing. + +Further reading / related projects +---------------------------------- + +* An interesting thread on an HP tech report that may be proof the pypy is feasible_ . (We already knew that...) + +* An interesting thread on why VHLL rock_ . (We already knew that too.) + +* A thread on Python in Scheme_ . + +* An intriguting project, FlashMob_ - creating an adhoc supercomputer. + +* A discussion on Python and lisp_ support + +* An interesting repository_ of papers by Xerox Parc members, with quite a few issues more or less relevant to PyPy. + +* A thread on the gnu lightning_ project."GNU lightning is a library that generates assembly language code at run-time; it is very fast, making it ideal for Just-In-Time compilers, and it abstracts over the target CPU, as it exposes to the clients a standardized RISC instruction set inspired by the MIPS and SPARC chips." + +* A project to create a Low Level Virtual Machine (LLVM_) and a PyPy-LLVM_ discussion, and conversation_ between PyPy and LLVM. + +* A thread discussing the xhelix_ python C extension implementing Helix encryption and authentication, which may be interesting to use as a pypy performance test at some point. + +* A paper for PyCon 2004: "IronPython_ is a new implementation of the Python language targeting the Common Language Runtime (CLR). It compiles python programs into bytecode (IL) that will run on either Microsoft's .NET or the Open Source Mono platform. IronPython includes an interactive interpreter and transparent on-the-fly compilation of source files just like standard Python. In addition, IronPython supports static compilation of Python code to produce static executables (.exe's) that can be run directly or static libraries (.dll's) that can be called from other CLR languages." + +* A comparison of Python and Pliant_ , an OS written in a python-like language. + + +.. _architecture: http://codespeak.net/pypy/index.cgi?doc/architecture.html +.. _oscon2003-paper: http://codespeak.net/pypy/index.cgi?doc/oscon2003-paper.html +.. _howtopypy: http://codespeak.net/pypy/index.cgi?doc/howtopypy.html +.. _readme: http://codespeak.net/pypy/index.cgi?doc/readme.html +.. _wrapping: http://codespeak.net/pypy/index.cgi?doc/wrapping.html +.. _coding-style: http://codespeak.net/pypy/index.cgi?doc/coding-style.html +.. _howtosvn: http://codespeak.net/pypy/index.cgi?doc/howtosvn.html +.. _optionaltool: http://codespeak.net/pypy/index.cgi?doc/optionaltool.html +.. _testdesign: http://codespeak.net/pypy/index.cgi?doc/testdesign.html +.. _feasible: http://codespeak.net/pipermail/pypy-dev/2004q2/001289.html +.. _rock: http://codespeak.net/pipermail/pypy-dev/2004q1/001255.html +.. _Scheme: http://codespeak.net/pipermail/pypy-dev/2004q1/001256.html +.. _FlashMob: http://www.flashmobcomputing.org/ +.. _lisp: http://codespeak.net/pipermail/pypy-dev/2003q4/001048.html +.. _repository: http://www2.parc.com/csl/groups/sda/publications.shtml +.. _lightning: http://codespeak.net/pipermail/pypy-dev/2003q4/001051.html +.. _LLVM: http://llvm.cs.uiuc.edu/ +.. _PyPy-LLVM: http://codespeak.net/pipermail/pypy-dev/2003q4/001115.html +.. _conversation: http://codespeak.net/pipermail/pypy-dev/2003q4/001119.html +.. _xhelix: http://codespeak.net/pipermail/pypy-dev/2003q4/001129.html +.. _IronPython: http://www.python.org/pycon/dc2004/papers/9/ +.. _pliant: http://pliant.cx +.. _recently-modified: http://codespeak.net/pypy/index.cgi?doc/recent Modified: pypy/dist/pypy/documentation/optionaltool.txt ============================================================================== --- pypy/dist/pypy/documentation/optionaltool.txt (original) +++ pypy/dist/pypy/documentation/optionaltool.txt Tue Jan 25 03:45:22 2005 @@ -1,33 +1,33 @@ -Optional Tools for running (and hacking) PyPy -============================================= - -In addition to the latest version of svn and Python, we use some optional -tools to install for working on pypy. They are not required to run all the -tests or to get an interactive PyPy prompt but they help to understand and -debug PyPy. - -Recommended tools: ------------------- - -* graphviz:: - - (used for visualizing the control-flow) - http://www.research.att.com/sw/tools/graphviz/download.html_ - -* pygame:: - - (to visualize control flow and annotation analysis of python programs) - http://www.pygame.org/download.shtml_ - - - on MAC OSX, TRY THIS:: - Alex will reconstruct the process for us - -Optional tools: ---------------- - -* CLISP:: - - Optional (if you want to work on generating lisp code from pypy) - http://clisp.cons.org/_ - - +Optional Tools for running (and hacking) PyPy +============================================= + +In addition to the latest version of svn and Python, we use some optional +tools to install for working on pypy. They are not required to run all the +tests or to get an interactive PyPy prompt but they help to understand and +debug PyPy. + +Recommended tools: +------------------ + +* graphviz:: + + (used for visualizing the control-flow) + http://www.research.att.com/sw/tools/graphviz/download.html_ + +* pygame:: + + (to visualize control flow and annotation analysis of python programs) + http://www.pygame.org/download.shtml_ + + - on MAC OSX, TRY THIS:: + Alex will reconstruct the process for us + +Optional tools: +--------------- + +* CLISP:: + + Optional (if you want to work on generating lisp code from pypy) + http://clisp.cons.org/_ + + From sanxiyn at codespeak.net Tue Jan 25 03:53:43 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 25 Jan 2005 03:53:43 +0100 (MET) Subject: [pypy-svn] r8532 - pypy/dist/pypy/appspace Message-ID: <20050125025343.387E427B58@code1.codespeak.net> Author: sanxiyn Date: Tue Jan 25 03:53:43 2005 New Revision: 8532 Added: pypy/dist/pypy/appspace/warnings.py Log: Import from Python 2.3.4 Added: pypy/dist/pypy/appspace/warnings.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/warnings.py Tue Jan 25 03:53:43 2005 @@ -0,0 +1,254 @@ +"""Python part of the warnings subsystem.""" + +# Note: function level imports should *not* be used +# in this module as it may cause import lock deadlock. +# See bug 683658. +import sys, types +import linecache + +__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", + "resetwarnings"] + +# filters contains a sequence of filter 5-tuples +# The components of the 5-tuple are: +# - an action: error, ignore, always, default, module, or once +# - a compiled regex that must match the warning message +# - a class representing the warning category +# - a compiled regex that must match the module that is being warned +# - a line number for the line being warning, or 0 to mean any line +# If either if the compiled regexs are None, match anything. +filters = [] +defaultaction = "default" +onceregistry = {} + +def warn(message, category=None, stacklevel=1): + """Issue a warning, or maybe ignore it or raise an exception.""" + # Check if message is already a Warning object + if isinstance(message, Warning): + category = message.__class__ + # Check category argument + if category is None: + category = UserWarning + assert issubclass(category, Warning) + # Get context information + try: + caller = sys._getframe(stacklevel) + except ValueError: + globals = sys.__dict__ + lineno = 1 + else: + globals = caller.f_globals + lineno = caller.f_lineno + if '__name__' in globals: + module = globals['__name__'] + else: + module = "" + filename = globals.get('__file__') + if filename: + fnl = filename.lower() + if fnl.endswith(".pyc") or fnl.endswith(".pyo"): + filename = filename[:-1] + else: + if module == "__main__": + filename = sys.argv[0] + if not filename: + filename = module + registry = globals.setdefault("__warningregistry__", {}) + warn_explicit(message, category, filename, lineno, module, registry) + +def warn_explicit(message, category, filename, lineno, + module=None, registry=None): + if module is None: + module = filename + if module[-3:].lower() == ".py": + module = module[:-3] # XXX What about leading pathname? + if registry is None: + registry = {} + if isinstance(message, Warning): + text = str(message) + category = message.__class__ + else: + text = message + message = category(message) + key = (text, category, lineno) + # Quick test for common case + if registry.get(key): + return + # Search the filters + for item in filters: + action, msg, cat, mod, ln = item + if ((msg is None or msg.match(text)) and + issubclass(category, cat) and + (msg is None or mod.match(module)) and + (ln == 0 or lineno == ln)): + break + else: + action = defaultaction + # Early exit actions + if action == "ignore": + registry[key] = 1 + return + if action == "error": + raise message + # Other actions + if action == "once": + registry[key] = 1 + oncekey = (text, category) + if onceregistry.get(oncekey): + return + onceregistry[oncekey] = 1 + elif action == "always": + pass + elif action == "module": + registry[key] = 1 + altkey = (text, category, 0) + if registry.get(altkey): + return + registry[altkey] = 1 + elif action == "default": + registry[key] = 1 + else: + # Unrecognized actions are errors + raise RuntimeError( + "Unrecognized action (%s) in warnings.filters:\n %s" % + (`action`, str(item))) + # Print message and context + showwarning(message, category, filename, lineno) + +def showwarning(message, category, filename, lineno, file=None): + """Hook to write a warning to a file; replace if you like.""" + if file is None: + file = sys.stderr + try: + file.write(formatwarning(message, category, filename, lineno)) + except IOError: + pass # the file (probably stderr) is invalid - this warning gets lost. + +def formatwarning(message, category, filename, lineno): + """Function to format a warning the standard way.""" + s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) + line = linecache.getline(filename, lineno).strip() + if line: + s = s + " " + line + "\n" + return s + +def filterwarnings(action, message="", category=Warning, module="", lineno=0, + append=0): + """Insert an entry into the list of warnings filters (at the front). + + Use assertions to check that all arguments have the right type.""" + import re + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %s" % `action` + assert isinstance(message, basestring), "message must be a string" + assert isinstance(category, types.ClassType), "category must be a class" + assert issubclass(category, Warning), "category must be a Warning subclass" + assert isinstance(module, basestring), "module must be a string" + assert isinstance(lineno, int) and lineno >= 0, \ + "lineno must be an int >= 0" + item = (action, re.compile(message, re.I), category, + re.compile(module), lineno) + if append: + filters.append(item) + else: + filters.insert(0, item) + +def simplefilter(action, category=Warning, lineno=0, append=0): + """Insert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. + """ + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %s" % `action` + assert isinstance(lineno, int) and lineno >= 0, \ + "lineno must be an int >= 0" + item = (action, None, category, None, lineno) + if append: + filters.append(item) + else: + filters.insert(0, item) + +def resetwarnings(): + """Clear the list of warning filters, so that no filters are active.""" + filters[:] = [] + +class _OptionError(Exception): + """Exception used by option processing helpers.""" + pass + +# Helper to process -W options passed via sys.warnoptions +def _processoptions(args): + for arg in args: + try: + _setoption(arg) + except _OptionError, msg: + print >>sys.stderr, "Invalid -W option ignored:", msg + +# Helper for _processoptions() +def _setoption(arg): + import re + parts = arg.split(':') + if len(parts) > 5: + raise _OptionError("too many fields (max 5): %s" % `arg`) + while len(parts) < 5: + parts.append('') + action, message, category, module, lineno = [s.strip() + for s in parts] + action = _getaction(action) + message = re.escape(message) + category = _getcategory(category) + module = re.escape(module) + if module: + module = module + '$' + if lineno: + try: + lineno = int(lineno) + if lineno < 0: + raise ValueError + except (ValueError, OverflowError): + raise _OptionError("invalid lineno %s" % `lineno`) + else: + lineno = 0 + filterwarnings(action, message, category, module, lineno) + +# Helper for _setoption() +def _getaction(action): + if not action: + return "default" + if action == "all": return "always" # Alias + for a in ['default', 'always', 'ignore', 'module', 'once', 'error']: + if a.startswith(action): + return a + raise _OptionError("invalid action: %s" % `action`) + +# Helper for _setoption() +def _getcategory(category): + import re + if not category: + return Warning + if re.match("^[a-zA-Z0-9_]+$", category): + try: + cat = eval(category) + except NameError: + raise _OptionError("unknown warning category: %s" % `category`) + else: + i = category.rfind(".") + module = category[:i] + klass = category[i+1:] + try: + m = __import__(module, None, None, [klass]) + except ImportError: + raise _OptionError("invalid module name: %s" % `module`) + try: + cat = getattr(m, klass) + except AttributeError: + raise _OptionError("unknown warning category: %s" % `category`) + if (not isinstance(cat, types.ClassType) or + not issubclass(cat, Warning)): + raise _OptionError("invalid warning category: %s" % `category`) + return cat + +# Module initialization +_processoptions(sys.warnoptions) +simplefilter("ignore", category=OverflowWarning, append=1) +simplefilter("ignore", category=PendingDeprecationWarning, append=1) From sanxiyn at codespeak.net Tue Jan 25 03:57:26 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 25 Jan 2005 03:57:26 +0100 (MET) Subject: [pypy-svn] r8533 - pypy/dist/pypy/appspace Message-ID: <20050125025726.1116727B58@code1.codespeak.net> Author: sanxiyn Date: Tue Jan 25 03:57:25 2005 New Revision: 8533 Modified: pypy/dist/pypy/appspace/warnings.py (contents, props changed) Log: Remove harmful checks against types.ClassType Modified: pypy/dist/pypy/appspace/warnings.py ============================================================================== --- pypy/dist/pypy/appspace/warnings.py (original) +++ pypy/dist/pypy/appspace/warnings.py Tue Jan 25 03:57:25 2005 @@ -141,7 +141,7 @@ assert action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %s" % `action` assert isinstance(message, basestring), "message must be a string" - assert isinstance(category, types.ClassType), "category must be a class" + #assert isinstance(category, types.ClassType), "category must be a class" assert issubclass(category, Warning), "category must be a Warning subclass" assert isinstance(module, basestring), "module must be a string" assert isinstance(lineno, int) and lineno >= 0, \ @@ -243,8 +243,7 @@ cat = getattr(m, klass) except AttributeError: raise _OptionError("unknown warning category: %s" % `category`) - if (not isinstance(cat, types.ClassType) or - not issubclass(cat, Warning)): + if not issubclass(cat, Warning): # or not isinstance(cat, types.ClassType) raise _OptionError("invalid warning category: %s" % `category`) return cat From sanxiyn at codespeak.net Tue Jan 25 05:30:03 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 25 Jan 2005 05:30:03 +0100 (MET) Subject: [pypy-svn] r8534 - pypy/dist/pypy/module Message-ID: <20050125043003.A616927B58@code1.codespeak.net> Author: sanxiyn Date: Tue Jan 25 05:30:03 2005 New Revision: 8534 Modified: pypy/dist/pypy/module/sysmodule.py Log: typo: mcbs -> mbcs Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Tue Jan 25 05:30:03 2005 @@ -50,7 +50,7 @@ operating system filenames.""" if platform == "win32": - encoding = "mcbs" + encoding = "mbcs" elif platform == "darwin": encoding = "utf-8" else: From tismer at codespeak.net Tue Jan 25 10:05:17 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 25 Jan 2005 10:05:17 +0100 (MET) Subject: [pypy-svn] r8535 - pypy/dist/pypy/appspace/test/patched Message-ID: <20050125090517.7F71327B75@code1.codespeak.net> Author: tismer Date: Tue Jan 25 10:05:17 2005 New Revision: 8535 Added: pypy/dist/pypy/appspace/test/patched/ pypy/dist/pypy/appspace/test/patched/test_sys.py Log: added a patched folder to appspace/test where all the standard-tests are stored which need to be changed. For instance, getrefcount is really a problem. Added: pypy/dist/pypy/appspace/test/patched/test_sys.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/test/patched/test_sys.py Tue Jan 25 10:05:17 2005 @@ -0,0 +1,255 @@ +# -*- coding: iso-8859-1 -*- +import unittest, test.test_support +import sys, cStringIO + +class SysModuleTest(unittest.TestCase): + + def test_original_displayhook(self): + import __builtin__ + savestdout = sys.stdout + out = cStringIO.StringIO() + sys.stdout = out + + dh = sys.__displayhook__ + + self.assertRaises(TypeError, dh) + if hasattr(__builtin__, "_"): + del __builtin__._ + + dh(None) + self.assertEqual(out.getvalue(), "") + self.assert_(not hasattr(__builtin__, "_")) + dh(42) + self.assertEqual(out.getvalue(), "42\n") + self.assertEqual(__builtin__._, 42) + + del sys.stdout + self.assertRaises(RuntimeError, dh, 42) + + sys.stdout = savestdout + + def test_lost_displayhook(self): + olddisplayhook = sys.displayhook + del sys.displayhook + code = compile("42", "", "single") + self.assertRaises(RuntimeError, eval, code) + sys.displayhook = olddisplayhook + + def test_custom_displayhook(self): + olddisplayhook = sys.displayhook + def baddisplayhook(obj): + raise ValueError + sys.displayhook = baddisplayhook + code = compile("42", "", "single") + self.assertRaises(ValueError, eval, code) + sys.displayhook = olddisplayhook + + def test_original_excepthook(self): + savestderr = sys.stderr + err = cStringIO.StringIO() + sys.stderr = err + + eh = sys.__excepthook__ + + self.assertRaises(TypeError, eh) + try: + raise ValueError(42) + except ValueError, exc: + eh(*sys.exc_info()) + + sys.stderr = savestderr + self.assert_(err.getvalue().endswith("ValueError: 42\n")) + + # FIXME: testing the code for a lost or replaced excepthook in + # Python/pythonrun.c::PyErr_PrintEx() is tricky. + + def test_exc_clear(self): + self.assertRaises(TypeError, sys.exc_clear, 42) + + # Verify that exc_info is present and matches exc, then clear it, and + # check that it worked. + def clear_check(exc): + typ, value, traceback = sys.exc_info() + self.assert_(typ is not None) + self.assert_(value is exc) + self.assert_(traceback is not None) + + sys.exc_clear() + + typ, value, traceback = sys.exc_info() + self.assert_(typ is None) + self.assert_(value is None) + self.assert_(traceback is None) + + def clear(): + try: + raise ValueError, 42 + except ValueError, exc: + clear_check(exc) + + # Raise an exception and check that it can be cleared + clear() + + # Verify that a frame currently handling an exception is + # unaffected by calling exc_clear in a nested frame. + try: + raise ValueError, 13 + except ValueError, exc: + typ1, value1, traceback1 = sys.exc_info() + clear() + typ2, value2, traceback2 = sys.exc_info() + + self.assert_(typ1 is typ2) + self.assert_(value1 is exc) + self.assert_(value1 is value2) + self.assert_(traceback1 is traceback2) + + # Check that an exception can be cleared outside of an except block + clear_check(exc) + + def test_exit(self): + self.assertRaises(TypeError, sys.exit, 42, 42) + + # call without argument + try: + sys.exit(0) + except SystemExit, exc: + self.assertEquals(exc.code, 0) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with tuple argument with one entry + # entry will be unpacked + try: + sys.exit(42) + except SystemExit, exc: + self.assertEquals(exc.code, 42) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with integer argument + try: + sys.exit((42,)) + except SystemExit, exc: + self.assertEquals(exc.code, 42) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with string argument + try: + sys.exit("exit") + except SystemExit, exc: + self.assertEquals(exc.code, "exit") + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with tuple argument with two entries + try: + sys.exit((17, 23)) + except SystemExit, exc: + self.assertEquals(exc.code, (17, 23)) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + def test_getdefaultencoding(self): + if test.test_support.have_unicode: + self.assertRaises(TypeError, sys.getdefaultencoding, 42) + # can't check more than the type, as the user might have changed it + self.assert_(isinstance(sys.getdefaultencoding(), str)) + + # testing sys.settrace() is done in test_trace.py + # testing sys.setprofile() is done in test_profile.py + + def test_setcheckinterval(self): + self.assertRaises(TypeError, sys.setcheckinterval) + orig = sys.getcheckinterval() + for n in 0, 100, 120, orig: # orig last to restore starting state + sys.setcheckinterval(n) + self.assertEquals(sys.getcheckinterval(), n) + + def test_recursionlimit(self): + self.assertRaises(TypeError, sys.getrecursionlimit, 42) + oldlimit = sys.getrecursionlimit() + self.assertRaises(TypeError, sys.setrecursionlimit) + self.assertRaises(ValueError, sys.setrecursionlimit, -42) + sys.setrecursionlimit(10000) + self.assertEqual(sys.getrecursionlimit(), 10000) + sys.setrecursionlimit(oldlimit) + + def test_getwindowsversion(self): + if hasattr(sys, "getwindowsversion"): + v = sys.getwindowsversion() + self.assert_(isinstance(v, tuple)) + self.assertEqual(len(v), 5) + self.assert_(isinstance(v[0], int)) + self.assert_(isinstance(v[1], int)) + self.assert_(isinstance(v[2], int)) + self.assert_(isinstance(v[3], int)) + self.assert_(isinstance(v[4], str)) + + def test_dlopenflags(self): + if hasattr(sys, "setdlopenflags"): + self.assert_(hasattr(sys, "getdlopenflags")) + self.assertRaises(TypeError, sys.getdlopenflags, 42) + oldflags = sys.getdlopenflags() + self.assertRaises(TypeError, sys.setdlopenflags) + sys.setdlopenflags(oldflags+1) + self.assertEqual(sys.getdlopenflags(), oldflags+1) + sys.setdlopenflags(oldflags) + + def test_refcount(self): + self.assertRaises(TypeError, sys.getrefcount) + c = sys.getrefcount(None) + n = None + self.assertEqual(sys.getrefcount(None), c+1) + del n + self.assertEqual(sys.getrefcount(None), c) + if hasattr(sys, "gettotalrefcount"): + self.assert_(isinstance(sys.gettotalrefcount(), int)) + + def test_getframe(self): + self.assertRaises(TypeError, sys._getframe, 42, 42) + self.assertRaises(ValueError, sys._getframe, 2000000000) + self.assert_( + SysModuleTest.test_getframe.im_func.func_code \ + is sys._getframe().f_code + ) + + def test_attributes(self): + self.assert_(isinstance(sys.api_version, int)) + self.assert_(isinstance(sys.argv, list)) + self.assert_(sys.byteorder in ("little", "big")) + self.assert_(isinstance(sys.builtin_module_names, tuple)) + self.assert_(isinstance(sys.copyright, basestring)) + self.assert_(isinstance(sys.exec_prefix, basestring)) + self.assert_(isinstance(sys.executable, basestring)) + self.assert_(isinstance(sys.hexversion, int)) + self.assert_(isinstance(sys.maxint, int)) + self.assert_(isinstance(sys.maxunicode, int)) + self.assert_(isinstance(sys.platform, basestring)) + self.assert_(isinstance(sys.prefix, basestring)) + self.assert_(isinstance(sys.version, basestring)) + vi = sys.version_info + self.assert_(isinstance(vi, tuple)) + self.assertEqual(len(vi), 5) + self.assert_(isinstance(vi[0], int)) + self.assert_(isinstance(vi[1], int)) + self.assert_(isinstance(vi[2], int)) + self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) + self.assert_(isinstance(vi[4], int)) + +def test_main(): + test.test_support.run_unittest(SysModuleTest) + +if __name__ == "__main__": + test_main() From ac at codespeak.net Tue Jan 25 10:20:24 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 10:20:24 +0100 (MET) Subject: [pypy-svn] r8536 - pypy/dist/pypy/appspace/test/patched Message-ID: <20050125092024.5E5E427B75@code1.codespeak.net> Author: ac Date: Tue Jan 25 10:20:24 2005 New Revision: 8536 Modified: pypy/dist/pypy/appspace/test/patched/test_sys.py (contents, props changed) Log: Fix lineendings. Modified: pypy/dist/pypy/appspace/test/patched/test_sys.py ============================================================================== --- pypy/dist/pypy/appspace/test/patched/test_sys.py (original) +++ pypy/dist/pypy/appspace/test/patched/test_sys.py Tue Jan 25 10:20:24 2005 @@ -1,255 +1,255 @@ -# -*- coding: iso-8859-1 -*- -import unittest, test.test_support -import sys, cStringIO - -class SysModuleTest(unittest.TestCase): - - def test_original_displayhook(self): - import __builtin__ - savestdout = sys.stdout - out = cStringIO.StringIO() - sys.stdout = out - - dh = sys.__displayhook__ - - self.assertRaises(TypeError, dh) - if hasattr(__builtin__, "_"): - del __builtin__._ - - dh(None) - self.assertEqual(out.getvalue(), "") - self.assert_(not hasattr(__builtin__, "_")) - dh(42) - self.assertEqual(out.getvalue(), "42\n") - self.assertEqual(__builtin__._, 42) - - del sys.stdout - self.assertRaises(RuntimeError, dh, 42) - - sys.stdout = savestdout - - def test_lost_displayhook(self): - olddisplayhook = sys.displayhook - del sys.displayhook - code = compile("42", "", "single") - self.assertRaises(RuntimeError, eval, code) - sys.displayhook = olddisplayhook - - def test_custom_displayhook(self): - olddisplayhook = sys.displayhook - def baddisplayhook(obj): - raise ValueError - sys.displayhook = baddisplayhook - code = compile("42", "", "single") - self.assertRaises(ValueError, eval, code) - sys.displayhook = olddisplayhook - - def test_original_excepthook(self): - savestderr = sys.stderr - err = cStringIO.StringIO() - sys.stderr = err - - eh = sys.__excepthook__ - - self.assertRaises(TypeError, eh) - try: - raise ValueError(42) - except ValueError, exc: - eh(*sys.exc_info()) - - sys.stderr = savestderr - self.assert_(err.getvalue().endswith("ValueError: 42\n")) - - # FIXME: testing the code for a lost or replaced excepthook in - # Python/pythonrun.c::PyErr_PrintEx() is tricky. - - def test_exc_clear(self): - self.assertRaises(TypeError, sys.exc_clear, 42) - - # Verify that exc_info is present and matches exc, then clear it, and - # check that it worked. - def clear_check(exc): - typ, value, traceback = sys.exc_info() - self.assert_(typ is not None) - self.assert_(value is exc) - self.assert_(traceback is not None) - - sys.exc_clear() - - typ, value, traceback = sys.exc_info() - self.assert_(typ is None) - self.assert_(value is None) - self.assert_(traceback is None) - - def clear(): - try: - raise ValueError, 42 - except ValueError, exc: - clear_check(exc) - - # Raise an exception and check that it can be cleared - clear() - - # Verify that a frame currently handling an exception is - # unaffected by calling exc_clear in a nested frame. - try: - raise ValueError, 13 - except ValueError, exc: - typ1, value1, traceback1 = sys.exc_info() - clear() - typ2, value2, traceback2 = sys.exc_info() - - self.assert_(typ1 is typ2) - self.assert_(value1 is exc) - self.assert_(value1 is value2) - self.assert_(traceback1 is traceback2) - - # Check that an exception can be cleared outside of an except block - clear_check(exc) - - def test_exit(self): - self.assertRaises(TypeError, sys.exit, 42, 42) - - # call without argument - try: - sys.exit(0) - except SystemExit, exc: - self.assertEquals(exc.code, 0) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with tuple argument with one entry - # entry will be unpacked - try: - sys.exit(42) - except SystemExit, exc: - self.assertEquals(exc.code, 42) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with integer argument - try: - sys.exit((42,)) - except SystemExit, exc: - self.assertEquals(exc.code, 42) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with string argument - try: - sys.exit("exit") - except SystemExit, exc: - self.assertEquals(exc.code, "exit") - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with tuple argument with two entries - try: - sys.exit((17, 23)) - except SystemExit, exc: - self.assertEquals(exc.code, (17, 23)) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - def test_getdefaultencoding(self): - if test.test_support.have_unicode: - self.assertRaises(TypeError, sys.getdefaultencoding, 42) - # can't check more than the type, as the user might have changed it - self.assert_(isinstance(sys.getdefaultencoding(), str)) - - # testing sys.settrace() is done in test_trace.py - # testing sys.setprofile() is done in test_profile.py - - def test_setcheckinterval(self): - self.assertRaises(TypeError, sys.setcheckinterval) - orig = sys.getcheckinterval() - for n in 0, 100, 120, orig: # orig last to restore starting state - sys.setcheckinterval(n) - self.assertEquals(sys.getcheckinterval(), n) - - def test_recursionlimit(self): - self.assertRaises(TypeError, sys.getrecursionlimit, 42) - oldlimit = sys.getrecursionlimit() - self.assertRaises(TypeError, sys.setrecursionlimit) - self.assertRaises(ValueError, sys.setrecursionlimit, -42) - sys.setrecursionlimit(10000) - self.assertEqual(sys.getrecursionlimit(), 10000) - sys.setrecursionlimit(oldlimit) - - def test_getwindowsversion(self): - if hasattr(sys, "getwindowsversion"): - v = sys.getwindowsversion() - self.assert_(isinstance(v, tuple)) - self.assertEqual(len(v), 5) - self.assert_(isinstance(v[0], int)) - self.assert_(isinstance(v[1], int)) - self.assert_(isinstance(v[2], int)) - self.assert_(isinstance(v[3], int)) - self.assert_(isinstance(v[4], str)) - - def test_dlopenflags(self): - if hasattr(sys, "setdlopenflags"): - self.assert_(hasattr(sys, "getdlopenflags")) - self.assertRaises(TypeError, sys.getdlopenflags, 42) - oldflags = sys.getdlopenflags() - self.assertRaises(TypeError, sys.setdlopenflags) - sys.setdlopenflags(oldflags+1) - self.assertEqual(sys.getdlopenflags(), oldflags+1) - sys.setdlopenflags(oldflags) - - def test_refcount(self): - self.assertRaises(TypeError, sys.getrefcount) - c = sys.getrefcount(None) - n = None - self.assertEqual(sys.getrefcount(None), c+1) - del n - self.assertEqual(sys.getrefcount(None), c) - if hasattr(sys, "gettotalrefcount"): - self.assert_(isinstance(sys.gettotalrefcount(), int)) - - def test_getframe(self): - self.assertRaises(TypeError, sys._getframe, 42, 42) - self.assertRaises(ValueError, sys._getframe, 2000000000) - self.assert_( - SysModuleTest.test_getframe.im_func.func_code \ - is sys._getframe().f_code - ) - - def test_attributes(self): - self.assert_(isinstance(sys.api_version, int)) - self.assert_(isinstance(sys.argv, list)) - self.assert_(sys.byteorder in ("little", "big")) - self.assert_(isinstance(sys.builtin_module_names, tuple)) - self.assert_(isinstance(sys.copyright, basestring)) - self.assert_(isinstance(sys.exec_prefix, basestring)) - self.assert_(isinstance(sys.executable, basestring)) - self.assert_(isinstance(sys.hexversion, int)) - self.assert_(isinstance(sys.maxint, int)) - self.assert_(isinstance(sys.maxunicode, int)) - self.assert_(isinstance(sys.platform, basestring)) - self.assert_(isinstance(sys.prefix, basestring)) - self.assert_(isinstance(sys.version, basestring)) - vi = sys.version_info - self.assert_(isinstance(vi, tuple)) - self.assertEqual(len(vi), 5) - self.assert_(isinstance(vi[0], int)) - self.assert_(isinstance(vi[1], int)) - self.assert_(isinstance(vi[2], int)) - self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) - self.assert_(isinstance(vi[4], int)) - -def test_main(): - test.test_support.run_unittest(SysModuleTest) - -if __name__ == "__main__": - test_main() +# -*- coding: iso-8859-1 -*- +import unittest, test.test_support +import sys, cStringIO + +class SysModuleTest(unittest.TestCase): + + def test_original_displayhook(self): + import __builtin__ + savestdout = sys.stdout + out = cStringIO.StringIO() + sys.stdout = out + + dh = sys.__displayhook__ + + self.assertRaises(TypeError, dh) + if hasattr(__builtin__, "_"): + del __builtin__._ + + dh(None) + self.assertEqual(out.getvalue(), "") + self.assert_(not hasattr(__builtin__, "_")) + dh(42) + self.assertEqual(out.getvalue(), "42\n") + self.assertEqual(__builtin__._, 42) + + del sys.stdout + self.assertRaises(RuntimeError, dh, 42) + + sys.stdout = savestdout + + def test_lost_displayhook(self): + olddisplayhook = sys.displayhook + del sys.displayhook + code = compile("42", "", "single") + self.assertRaises(RuntimeError, eval, code) + sys.displayhook = olddisplayhook + + def test_custom_displayhook(self): + olddisplayhook = sys.displayhook + def baddisplayhook(obj): + raise ValueError + sys.displayhook = baddisplayhook + code = compile("42", "", "single") + self.assertRaises(ValueError, eval, code) + sys.displayhook = olddisplayhook + + def test_original_excepthook(self): + savestderr = sys.stderr + err = cStringIO.StringIO() + sys.stderr = err + + eh = sys.__excepthook__ + + self.assertRaises(TypeError, eh) + try: + raise ValueError(42) + except ValueError, exc: + eh(*sys.exc_info()) + + sys.stderr = savestderr + self.assert_(err.getvalue().endswith("ValueError: 42\n")) + + # FIXME: testing the code for a lost or replaced excepthook in + # Python/pythonrun.c::PyErr_PrintEx() is tricky. + + def test_exc_clear(self): + self.assertRaises(TypeError, sys.exc_clear, 42) + + # Verify that exc_info is present and matches exc, then clear it, and + # check that it worked. + def clear_check(exc): + typ, value, traceback = sys.exc_info() + self.assert_(typ is not None) + self.assert_(value is exc) + self.assert_(traceback is not None) + + sys.exc_clear() + + typ, value, traceback = sys.exc_info() + self.assert_(typ is None) + self.assert_(value is None) + self.assert_(traceback is None) + + def clear(): + try: + raise ValueError, 42 + except ValueError, exc: + clear_check(exc) + + # Raise an exception and check that it can be cleared + clear() + + # Verify that a frame currently handling an exception is + # unaffected by calling exc_clear in a nested frame. + try: + raise ValueError, 13 + except ValueError, exc: + typ1, value1, traceback1 = sys.exc_info() + clear() + typ2, value2, traceback2 = sys.exc_info() + + self.assert_(typ1 is typ2) + self.assert_(value1 is exc) + self.assert_(value1 is value2) + self.assert_(traceback1 is traceback2) + + # Check that an exception can be cleared outside of an except block + clear_check(exc) + + def test_exit(self): + self.assertRaises(TypeError, sys.exit, 42, 42) + + # call without argument + try: + sys.exit(0) + except SystemExit, exc: + self.assertEquals(exc.code, 0) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with tuple argument with one entry + # entry will be unpacked + try: + sys.exit(42) + except SystemExit, exc: + self.assertEquals(exc.code, 42) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with integer argument + try: + sys.exit((42,)) + except SystemExit, exc: + self.assertEquals(exc.code, 42) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with string argument + try: + sys.exit("exit") + except SystemExit, exc: + self.assertEquals(exc.code, "exit") + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + # call with tuple argument with two entries + try: + sys.exit((17, 23)) + except SystemExit, exc: + self.assertEquals(exc.code, (17, 23)) + except: + self.fail("wrong exception") + else: + self.fail("no exception") + + def test_getdefaultencoding(self): + if test.test_support.have_unicode: + self.assertRaises(TypeError, sys.getdefaultencoding, 42) + # can't check more than the type, as the user might have changed it + self.assert_(isinstance(sys.getdefaultencoding(), str)) + + # testing sys.settrace() is done in test_trace.py + # testing sys.setprofile() is done in test_profile.py + + def test_setcheckinterval(self): + self.assertRaises(TypeError, sys.setcheckinterval) + orig = sys.getcheckinterval() + for n in 0, 100, 120, orig: # orig last to restore starting state + sys.setcheckinterval(n) + self.assertEquals(sys.getcheckinterval(), n) + + def test_recursionlimit(self): + self.assertRaises(TypeError, sys.getrecursionlimit, 42) + oldlimit = sys.getrecursionlimit() + self.assertRaises(TypeError, sys.setrecursionlimit) + self.assertRaises(ValueError, sys.setrecursionlimit, -42) + sys.setrecursionlimit(10000) + self.assertEqual(sys.getrecursionlimit(), 10000) + sys.setrecursionlimit(oldlimit) + + def test_getwindowsversion(self): + if hasattr(sys, "getwindowsversion"): + v = sys.getwindowsversion() + self.assert_(isinstance(v, tuple)) + self.assertEqual(len(v), 5) + self.assert_(isinstance(v[0], int)) + self.assert_(isinstance(v[1], int)) + self.assert_(isinstance(v[2], int)) + self.assert_(isinstance(v[3], int)) + self.assert_(isinstance(v[4], str)) + + def test_dlopenflags(self): + if hasattr(sys, "setdlopenflags"): + self.assert_(hasattr(sys, "getdlopenflags")) + self.assertRaises(TypeError, sys.getdlopenflags, 42) + oldflags = sys.getdlopenflags() + self.assertRaises(TypeError, sys.setdlopenflags) + sys.setdlopenflags(oldflags+1) + self.assertEqual(sys.getdlopenflags(), oldflags+1) + sys.setdlopenflags(oldflags) + + def test_refcount(self): + self.assertRaises(TypeError, sys.getrefcount) + c = sys.getrefcount(None) + n = None + self.assertEqual(sys.getrefcount(None), c+1) + del n + self.assertEqual(sys.getrefcount(None), c) + if hasattr(sys, "gettotalrefcount"): + self.assert_(isinstance(sys.gettotalrefcount(), int)) + + def test_getframe(self): + self.assertRaises(TypeError, sys._getframe, 42, 42) + self.assertRaises(ValueError, sys._getframe, 2000000000) + self.assert_( + SysModuleTest.test_getframe.im_func.func_code \ + is sys._getframe().f_code + ) + + def test_attributes(self): + self.assert_(isinstance(sys.api_version, int)) + self.assert_(isinstance(sys.argv, list)) + self.assert_(sys.byteorder in ("little", "big")) + self.assert_(isinstance(sys.builtin_module_names, tuple)) + self.assert_(isinstance(sys.copyright, basestring)) + self.assert_(isinstance(sys.exec_prefix, basestring)) + self.assert_(isinstance(sys.executable, basestring)) + self.assert_(isinstance(sys.hexversion, int)) + self.assert_(isinstance(sys.maxint, int)) + self.assert_(isinstance(sys.maxunicode, int)) + self.assert_(isinstance(sys.platform, basestring)) + self.assert_(isinstance(sys.prefix, basestring)) + self.assert_(isinstance(sys.version, basestring)) + vi = sys.version_info + self.assert_(isinstance(vi, tuple)) + self.assertEqual(len(vi), 5) + self.assert_(isinstance(vi[0], int)) + self.assert_(isinstance(vi[1], int)) + self.assert_(isinstance(vi[2], int)) + self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) + self.assert_(isinstance(vi[4], int)) + +def test_main(): + test.test_support.run_unittest(SysModuleTest) + +if __name__ == "__main__": + test_main() From tismer at codespeak.net Tue Jan 25 10:23:09 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 25 Jan 2005 10:23:09 +0100 (MET) Subject: [pypy-svn] r8537 - pypy/dist/pypy/module Message-ID: <20050125092309.62B9D27B75@code1.codespeak.net> Author: tismer Date: Tue Jan 25 10:23:09 2005 New Revision: 8537 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: moved global variables.Well, not really, they are just accessed via space.sys in the code that modifies globals. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 10:23:09 2005 @@ -120,6 +120,11 @@ # directly from the C code in ceval.c, might be moved somewhere else. +# this variable is living here, but we +# access it this way, later: +# space.sys.recursion_limit = 1000 +# note that we cannot do it *here* because +# space.sys does not exist, yet. recursion_limit = 1000 def setrecursionlimit(w_new_limit): @@ -133,8 +138,9 @@ if new_limit <= 0: raise OperationError(space.w_ValueError, space.wrap("recursion limit must be positive")) - global recursion_limit - recursion_limit = new_limit + # global recursion_limit + # we need to do it without writing globals. + space.sys.recursion_limit = new_limit def getrecursionlimit(): """getrecursionlimit() @@ -152,8 +158,8 @@ Tell the Python interpreter to check for asynchronous events every n instructions. This also affects how often thread switches occur.""" - global checkinterval - checkinterval = space.int_w(w_interval) + + space.sys.checkinterval = space.int_w(w_interval) def getcheckinterval(): """getcheckinterval() -> current check interval; see setcheckinterval().""" Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Tue Jan 25 10:23:09 2005 @@ -33,6 +33,8 @@ from traceback import print_exception print_exception(exctype, value, traceback) +__excepthook__ = excepthook # this is exactly like in CPython + def exit(exitcode=0): raise SystemExit(exitcode) @@ -43,6 +45,8 @@ # see e.g. the difference with >>> print 5,; 8 print `obj` +__displayhook__ = displayhook # this is exactly like in CPython + def getfilesystemencoding(): """getfilesystemencoding() -> string From ac at codespeak.net Tue Jan 25 10:27:55 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 10:27:55 +0100 (MET) Subject: [pypy-svn] r8538 - pypy/dist/pypy/appspace/test/patched Message-ID: <20050125092755.EBEC427B75@code1.codespeak.net> Author: ac Date: Tue Jan 25 10:27:55 2005 New Revision: 8538 Modified: pypy/dist/pypy/appspace/test/patched/test_sys.py Log: Fix test on sys.getrefcount Modified: pypy/dist/pypy/appspace/test/patched/test_sys.py ============================================================================== --- pypy/dist/pypy/appspace/test/patched/test_sys.py (original) +++ pypy/dist/pypy/appspace/test/patched/test_sys.py Tue Jan 25 10:27:55 2005 @@ -208,12 +208,13 @@ sys.setdlopenflags(oldflags) def test_refcount(self): - self.assertRaises(TypeError, sys.getrefcount) - c = sys.getrefcount(None) - n = None - self.assertEqual(sys.getrefcount(None), c+1) - del n - self.assertEqual(sys.getrefcount(None), c) + if hasattr(sys, 'getrefcount'): + self.assertRaises(TypeError, sys.getrefcount) + c = sys.getrefcount(None) + n = None + self.assertEqual(sys.getrefcount(None), c+1) + del n + self.assertEqual(sys.getrefcount(None), c) if hasattr(sys, "gettotalrefcount"): self.assert_(isinstance(sys.gettotalrefcount(), int)) From sanxiyn at codespeak.net Tue Jan 25 10:41:34 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 25 Jan 2005 10:41:34 +0100 (MET) Subject: [pypy-svn] r8539 - pypy/dist/pypy/module Message-ID: <20050125094134.7957327B75@code1.codespeak.net> Author: sanxiyn Date: Tue Jan 25 10:41:34 2005 New Revision: 8539 Modified: pypy/dist/pypy/module/sysinterp.py Log: borrow array module Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 10:41:34 2005 @@ -36,7 +36,7 @@ # The following built-in modules are not written in PyPy, so we # steal them from Python. for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', - 'itertools', 'math', '_codecs', + 'itertools', 'math', '_codecs', 'array', '_random', '_sre', 'time', '_socket', 'errno', 'marshal', 'binascii', 'parser']: if fn not in builtin_modules: From jacek at codespeak.net Tue Jan 25 11:09:50 2005 From: jacek at codespeak.net (jacek at codespeak.net) Date: Tue, 25 Jan 2005 11:09:50 +0100 (MET) Subject: [pypy-svn] r8540 - pypy/dist/pypy/module/test Message-ID: <20050125100950.77DBA27B75@code1.codespeak.net> Author: jacek Date: Tue Jan 25 11:09:50 2005 New Revision: 8540 Modified: pypy/dist/pypy/module/test/test_sysmodule.py Log: Added ported tests for sys module. Test taken from python 2.4 Modified: pypy/dist/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/dist/pypy/module/test/test_sysmodule.py (original) +++ pypy/dist/pypy/module/test/test_sysmodule.py Tue Jan 25 11:09:50 2005 @@ -1,4 +1,13 @@ +# -*- coding: iso-8859-1 -*- import autopath +from py.test import raises +from pypy.interpreter.gateway import app2interp_temp + +def app_init_globals_via_builtins_hack(): + import __builtin__ as b + import cStringIO, sys + b.cStringIO = cStringIO + b.sys = sys class TestSysTests: def setup_method(self,method): @@ -85,3 +94,257 @@ assert isinstance(val, etype) else: raise AssertionError, "ZeroDivisionError not caught" + + + + + +class AppTestSysModulePortedFromCPython: + + def setup_class(cls): + app2interp_temp(app_init_globals_via_builtins_hack)(cls.space) + + def test_original_displayhook(self): + import __builtin__ + savestdout = sys.stdout + out = cStringIO.StringIO() + sys.stdout = out + + dh = sys.__displayhook__ + + raises(TypeError, dh) + if hasattr(__builtin__, "_"): + del __builtin__._ + + dh(None) + assert out.getvalue() == "" + assert not hasattr(__builtin__, "_") + dh(42) + assert out.getvalue() == "42\n" + assert __builtin__._ == 42 + + del sys.stdout + raises(RuntimeError, dh, 42) + + sys.stdout = savestdout + + def test_lost_displayhook(self): + olddisplayhook = sys.displayhook + del sys.displayhook + code = compile("42", "", "single") + raises(RuntimeError, eval, code) + sys.displayhook = olddisplayhook + + def test_custom_displayhook(self): + olddisplayhook = sys.displayhook + def baddisplayhook(obj): + raise ValueError + sys.displayhook = baddisplayhook + code = compile("42", "", "single") + raises(ValueError, eval, code) + sys.displayhook = olddisplayhook + + def test_original_excepthook(self): + import cStringIO + savestderr = sys.stderr + err = cStringIO.StringIO() + sys.stderr = err + + eh = sys.__excepthook__ + + raises(TypeError, eh) + try: + raise ValueError(42) + except ValueError, exc: + eh(*sys.exc_info()) + + sys.stderr = savestderr + assert err.getvalue().endswith("ValueError: 42\n") + + # FIXME: testing the code for a lost or replaced excepthook in + # Python/pythonrun.c::PyErr_PrintEx() is tricky. + + def test_exc_clear(self): + raises(TypeError, sys.exc_clear, 42) + + # Verify that exc_info is present and matches exc, then clear it, and + # check that it worked. + def clear_check(exc): + typ, value, traceback = sys.exc_info() + assert typ is not None + assert value is exc + assert traceback is not None + + sys.exc_clear() + + typ, value, traceback = sys.exc_info() + assert typ is None + assert value is None + assert traceback is None + + def clear(): + try: + raise ValueError, 42 + except ValueError, exc: + clear_check(exc) + + # Raise an exception and check that it can be cleared + clear() + + # Verify that a frame currently handling an exception is + # unaffected by calling exc_clear in a nested frame. + try: + raise ValueError, 13 + except ValueError, exc: + typ1, value1, traceback1 = sys.exc_info() + clear() + typ2, value2, traceback2 = sys.exc_info() + + assert typ1 is typ2 + assert value1 is exc + assert value1 is value2 + assert traceback1 is traceback2 + + # Check that an exception can be cleared outside of an except block + clear_check(exc) + + def test_exit(self): + raises(TypeError, sys.exit, 42, 42) + + # call without argument + try: + sys.exit(0) + except SystemExit, exc: + assert exc.code == 0 + except: + raise AssertionError, "wrong exception" + else: + raise AssertionError, "no exception" + + # call with tuple argument with one entry + # entry will be unpacked + try: + sys.exit(42) + except SystemExit, exc: + assert exc.code == 42 + except: + raise AssertionError, "wrong exception" + else: + raise AssertionError, "no exception" + + # call with integer argument + try: + sys.exit((42,)) + except SystemExit, exc: + assert exc.code == 42 + except: + raise AssertionError, "wrong exception" + else: + raise AssertionError, "no exception" + + # call with string argument + try: + sys.exit("exit") + except SystemExit, exc: + assert exc.code == "exit" + except: + raise AssertionError, "wrong exception" + else: + raise AssertionError, "no exception" + + # call with tuple argument with two entries + try: + sys.exit((17, 23)) + except SystemExit, exc: + assert exc.code == (17, 23) + except: + raise AssertionError, "wrong exception" + else: + raise AssertionError, "no exception" + + def test_getdefaultencoding(self): + raises(TypeError, sys.getdefaultencoding, 42) + # can't check more than the type, as the user might have changed it + assert isinstance(sys.getdefaultencoding(), str) + + # testing sys.settrace() is done in test_trace.py + # testing sys.setprofile() is done in test_profile.py + + def test_setcheckinterval(self): + raises(TypeError, sys.setcheckinterval) + orig = sys.getcheckinterval() + for n in 0, 100, 120, orig: # orig last to restore starting state + sys.setcheckinterval(n) + assert sys.getcheckinterval() == n + + def test_recursionlimit(self): + raises(TypeError, sys.getrecursionlimit, 42) + oldlimit = sys.getrecursionlimit() + raises(TypeError, sys.setrecursionlimit) + raises(ValueError, sys.setrecursionlimit, -42) + sys.setrecursionlimit(10000) + assert sys.getrecursionlimit() == 10000 + sys.setrecursionlimit(oldlimit) + + def test_getwindowsversion(self): + if hasattr(sys, "getwindowsversion"): + v = sys.getwindowsversion() + assert isinstance(v, tuple) + assert len(v) == 5 + assert isinstance(v[0], int) + assert isinstance(v[1], int) + assert isinstance(v[2], int) + assert isinstance(v[3], int) + assert isinstance(v[4], str) + + def test_dlopenflags(self): + if hasattr(sys, "setdlopenflags"): + assert hasattr(sys, "getdlopenflags") + raises(TypeError, sys.getdlopenflags, 42) + oldflags = sys.getdlopenflags() + raises(TypeError, sys.setdlopenflags) + sys.setdlopenflags(oldflags+1) + assert sys.getdlopenflags() == oldflags+1 + sys.setdlopenflags(oldflags) + + def test_refcount(self): + raises(TypeError, sys.getrefcount) + c = sys.getrefcount(None) + n = None + assert sys.getrefcount(None) == c+1 + del n + assert sys.getrefcount(None) == c + if hasattr(sys, "gettotalrefcount"): + assert isinstance(sys.gettotalrefcount(), int) + + def test_getframe(self): + raises(TypeError, sys._getframe, 42, 42) + raises(ValueError, sys._getframe, 2000000000) + assert sys._getframe().f_code.co_name == 'test_getframe' + #assert ( + # TestSysModule.test_getframe.im_func.func_code \ + # is sys._getframe().f_code + #) + + def test_attributes(self): + assert isinstance(sys.api_version, int) + assert isinstance(sys.argv, list) + assert sys.byteorder in ("little", "big") + assert isinstance(sys.builtin_module_names, tuple) + assert isinstance(sys.copyright, basestring) + assert isinstance(sys.exec_prefix, basestring) + assert isinstance(sys.executable, basestring) + assert isinstance(sys.hexversion, int) + assert isinstance(sys.maxint, int) + assert isinstance(sys.maxunicode, int) + assert isinstance(sys.platform, basestring) + assert isinstance(sys.prefix, basestring) + assert isinstance(sys.version, basestring) + vi = sys.version_info + assert isinstance(vi, tuple) + assert len(vi) == 5 + assert isinstance(vi[0], int) + assert isinstance(vi[1], int) + assert isinstance(vi[2], int) + assert vi[3] in ("alpha", "beta", "candidate", "final") + assert isinstance(vi[4], int) From pedronis at codespeak.net Tue Jan 25 11:37:20 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 25 Jan 2005 11:37:20 +0100 (MET) Subject: [pypy-svn] r8541 - pypy/dist/pypy/module Message-ID: <20050125103720.E8B7B27B75@code1.codespeak.net> Author: pedronis Date: Tue Jan 25 11:37:20 2005 New Revision: 8541 Modified: pypy/dist/pypy/module/sysinterp.py Log: pypy_getudir is not RPython Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 11:37:20 2005 @@ -180,5 +180,6 @@ operror.clear(space) def pypy_getudir(): + """NOT_RPYTHON""" from pypy.tool.udir import udir return space.wrap(str(udir)) From tismer at codespeak.net Tue Jan 25 11:40:12 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 25 Jan 2005 11:40:12 +0100 (MET) Subject: [pypy-svn] r8542 - pypy/dist/pypy/appspace Message-ID: <20050125104012.435F427B84@code1.codespeak.net> Author: tismer Date: Tue Jan 25 11:40:12 2005 New Revision: 8542 Modified: pypy/dist/pypy/appspace/exceptions.py Log: temporary auto-generated exceptions.py file. This will be enhanced wit a few auto-generated commends and some slots to be filled in by hand. Later, this might be turned into an early importable interp-level-module. Modified: pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/exceptions.py (original) +++ pypy/dist/pypy/appspace/exceptions.py Tue Jan 25 11:40:12 2005 @@ -1,43 +1,204 @@ -ArithmeticError = ArithmeticError -AssertionError = AssertionError -AttributeError = AttributeError -DeprecationWarning = DeprecationWarning -EOFError = EOFError -EnvironmentError = EnvironmentError -Exception = Exception -FloatingPointError = FloatingPointError -FutureWarning = FutureWarning -IOError = IOError -ImportError = ImportError -IndentationError = IndentationError -IndexError = IndexError -KeyError = KeyError -KeyboardInterrupt = KeyboardInterrupt -LookupError = LookupError -MemoryError = MemoryError -NameError = NameError -NotImplementedError = NotImplementedError -OSError = OSError -OverflowError = OverflowError -OverflowWarning = OverflowWarning -PendingDeprecationWarning = PendingDeprecationWarning -ReferenceError = ReferenceError -RuntimeError = RuntimeError -RuntimeWarning = RuntimeWarning -StandardError = StandardError -StopIteration = StopIteration -SyntaxError = SyntaxError -SyntaxWarning = SyntaxWarning -SystemError = SystemError -SystemExit = SystemExit -TabError = TabError -TypeError = TypeError -UnboundLocalError = UnboundLocalError -UnicodeDecodeError = UnicodeDecodeError -UnicodeEncodeError = UnicodeEncodeError -UnicodeError = UnicodeError -UnicodeTranslateError = UnicodeTranslateError -UserWarning = UserWarning -ValueError = ValueError -Warning = Warning -ZeroDivisionError = ZeroDivisionError +class Exception: + """Common base class for all exceptions.""" + + # auto-generated code, please check carefully! + def __getitem__(self, idx): + return self.args[idx] + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement Exception.__str__ + # instantiation of Exception works with 13119 solutions + +class StandardError(Exception): + """Base class for all standard Python exceptions.""" + +class ValueError(StandardError): + """Inappropriate argument value (of correct type).""" + +class ImportError(StandardError): + """Import can't find module, or can't find name in module.""" + +class RuntimeError(StandardError): + """Unspecified run-time error.""" + +class UnicodeError(ValueError): + """Unicode related error.""" + +class UnicodeTranslateError(UnicodeError): + """Unicode translation error.""" + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement UnicodeTranslateError.__str__ + # instantiation of UnicodeTranslateError works with 1 solutions + +class LookupError(StandardError): + """Base class for lookup errors.""" + +class KeyError(LookupError): + """Mapping key not found.""" + + # auto-generated code, please check carefully! + # please implement KeyError.__str__ + # instantiation of KeyError works with 13119 solutions + +class Warning(Exception): + """Base class for warning categories.""" + +class SyntaxWarning(Warning): + """Base class for warnings about dubious syntax.""" + +class StopIteration(Exception): + """Signal the end from iterator.next().""" + +class PendingDeprecationWarning(Warning): + """Base class for warnings about features which will be deprecated in the future.""" + +class EnvironmentError(StandardError): + """Base class for I/O related errors.""" + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement EnvironmentError.__str__ + # instantiation of EnvironmentError works with 13119 solutions + +class OSError(EnvironmentError): + """OS system call failed.""" + +class DeprecationWarning(Warning): + """Base class for warnings about deprecated features.""" + +class UnicodeEncodeError(UnicodeError): + """Unicode encoding error.""" + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement UnicodeEncodeError.__str__ + # instantiation of UnicodeEncodeError works with 1 solutions + +class ArithmeticError(StandardError): + """Base class for arithmetic errors.""" + +class FloatingPointError(ArithmeticError): + """Floating point operation failed.""" + +class ReferenceError(StandardError): + """Weak ref proxy used after referent went away.""" + +class NameError(StandardError): + """Name not found globally.""" + +class OverflowWarning(Warning): + """Base class for warnings about numeric overflow.""" + +class IOError(EnvironmentError): + """I/O operation failed.""" + +class SyntaxError(StandardError): + """Invalid syntax.""" + filename = None + lineno = None + msg = '' + offset = None + print_file_and_line = None + text = None + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement SyntaxError.__str__ + # instantiation of SyntaxError works with 13116 solutions + +class FutureWarning(Warning): + """Base class for warnings about constructs that will change semantically in the future.""" + +class SystemExit(Exception): + """Request to exit from the interpreter.""" + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + +class EOFError(StandardError): + """Read beyond end of file.""" + +class IndentationError(SyntaxError): + """Improper indentation.""" + +class TabError(IndentationError): + """Improper mixture of spaces and tabs.""" + +class ZeroDivisionError(ArithmeticError): + """Second argument to a division or modulo operation was zero.""" + +class SystemError(StandardError): + """Internal error in the Python interpreter. + +Please report this to the Python maintainer, along with the traceback, +the Python version, and the hardware/OS platform and version.""" + +class AssertionError(StandardError): + """Assertion failed.""" + +class UnicodeDecodeError(UnicodeError): + """Unicode decoding error.""" + + # auto-generated code, please check carefully! + def __init__(self, *args): + pass + + # auto-generated code, please check carefully! + # please implement UnicodeDecodeError.__str__ + # instantiation of UnicodeDecodeError works with 1 solutions + +class TypeError(StandardError): + """Inappropriate argument type.""" + +class IndexError(LookupError): + """Sequence index out of range.""" + +class RuntimeWarning(Warning): + """Base class for warnings about dubious runtime behavior.""" + +class KeyboardInterrupt(StandardError): + """Program interrupted by user.""" + +class UserWarning(Warning): + """Base class for warnings generated by user code.""" + +class TaskletExit(SystemExit): + """Request to exit from a tasklet.""" + +class MemoryError(StandardError): + """Out of memory.""" + +class UnboundLocalError(NameError): + """Local name referenced but not bound to a value.""" + +class NotImplementedError(RuntimeError): + """Method or function hasn't been implemented yet.""" + +class AttributeError(StandardError): + """Attribute not found.""" + +class OverflowError(ArithmeticError): + """Result too large to be represented.""" + +class WindowsError(OSError): + """MS-Windows OS system call failed.""" + From ac at codespeak.net Tue Jan 25 11:46:05 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 11:46:05 +0100 (MET) Subject: [pypy-svn] r8543 - in pypy/dist/pypy/module: . test Message-ID: <20050125104605.D134227B84@code1.codespeak.net> Author: ac Date: Tue Jan 25 11:46:05 2005 New Revision: 8543 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py pypy/dist/pypy/module/test/test_sysmodule.py Log: Added api_version, copyright, exec_prefix and maxunicode to sys module. Skip test of getrefcount Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 11:46:05 2005 @@ -71,6 +71,7 @@ w_platform = space.wrap(cpy_sys.platform) w_maxint = space.wrap(cpy_sys.maxint) w_byteorder = space.wrap(cpy_sys.byteorder) +w_maxunicode = space.wrap(cpy_sys.maxunicode) w_stdin = space.wrap(cpy_sys.stdin) w_stdout = space.wrap(cpy_sys.stdout) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Tue Jan 25 11:46:05 2005 @@ -8,6 +8,7 @@ from __interplevel__ import initialpath as path from __interplevel__ import modules, argv from __interplevel__ import warnoptions, builtin_module_names +from __interplevel__ import maxunicode # Objects from interpreter-level from __interplevel__ import stdin, stdout, stderr, maxint @@ -20,6 +21,9 @@ from __interplevel__ import getcheckinterval, setcheckinterval # Dummy +api_version = 0 +copyright = '' +exec_prefix = '' executable = '' prefix = '' version = '2.3a0 (pypy build)' @@ -28,6 +32,7 @@ ps1 = '>>>> ' ps2 = '.... ' + # XXX not called by the core yet def excepthook(exctype, value, traceback): from traceback import print_exception Modified: pypy/dist/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/dist/pypy/module/test/test_sysmodule.py (original) +++ pypy/dist/pypy/module/test/test_sysmodule.py Tue Jan 25 11:46:05 2005 @@ -308,6 +308,9 @@ sys.setdlopenflags(oldflags) def test_refcount(self): + if not hasattr(sys, "getrefcount"): + skip('Reference counting is not implemented.') + raises(TypeError, sys.getrefcount) c = sys.getrefcount(None) n = None From tismer at codespeak.net Tue Jan 25 11:47:37 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 25 Jan 2005 11:47:37 +0100 (MET) Subject: [pypy-svn] r8544 - pypy/dist/pypy/appspace Message-ID: <20050125104737.E07E927B84@code1.codespeak.net> Author: tismer Date: Tue Jan 25 11:47:37 2005 New Revision: 8544 Modified: pypy/dist/pypy/appspace/exceptions.py Log: some basic stuff, temporary Modified: pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/exceptions.py (original) +++ pypy/dist/pypy/appspace/exceptions.py Tue Jan 25 11:47:37 2005 @@ -1,3 +1,7 @@ +# XXX +# This file is almost auto-generated now and yet +# not ableto adopt changes by hand. Please don't edit now. + class Exception: """Common base class for all exceptions.""" @@ -7,7 +11,7 @@ # auto-generated code, please check carefully! def __init__(self, *args): - pass + self.args = args # auto-generated code, please check carefully! # please implement Exception.__str__ @@ -32,9 +36,9 @@ """Unicode translation error.""" # auto-generated code, please check carefully! - def __init__(self, *args): - pass - + ##def __init__(self, *args): + ## pass + ## completely wrong # auto-generated code, please check carefully! # please implement UnicodeTranslateError.__str__ # instantiation of UnicodeTranslateError works with 1 solutions @@ -65,9 +69,9 @@ """Base class for I/O related errors.""" # auto-generated code, please check carefully! - def __init__(self, *args): - pass - + ##def __init__(self, *args): + ## pass + ## completely wrong # auto-generated code, please check carefully! # please implement EnvironmentError.__str__ # instantiation of EnvironmentError works with 13119 solutions @@ -82,9 +86,9 @@ """Unicode encoding error.""" # auto-generated code, please check carefully! - def __init__(self, *args): - pass - + ##def __init__(self, *args): + ## pass + ## completely wrong # auto-generated code, please check carefully! # please implement UnicodeEncodeError.__str__ # instantiation of UnicodeEncodeError works with 1 solutions @@ -117,9 +121,9 @@ text = None # auto-generated code, please check carefully! - def __init__(self, *args): - pass - + ##def __init__(self, *args): + ## pass + ## completely wrong # auto-generated code, please check carefully! # please implement SyntaxError.__str__ # instantiation of SyntaxError works with 13116 solutions @@ -132,7 +136,13 @@ # auto-generated code, please check carefully! def __init__(self, *args): - pass + self.args = args + if len(args) == 0: + self.code = None + elif len(args) == 1: + self.code = args[0] + else: + self.code = args class EOFError(StandardError): """Read beyond end of file.""" @@ -159,9 +169,9 @@ """Unicode decoding error.""" # auto-generated code, please check carefully! - def __init__(self, *args): - pass - + ##def __init__(self, *args): + ## pass + ## completely wrong # auto-generated code, please check carefully! # please implement UnicodeDecodeError.__str__ # instantiation of UnicodeDecodeError works with 1 solutions From ludal at codespeak.net Tue Jan 25 11:49:02 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 11:49:02 +0100 (MET) Subject: [pypy-svn] r8545 - pypy/dist/pypy/interpreter/test Message-ID: <20050125104902.4430A27B84@code1.codespeak.net> Author: ludal Date: Tue Jan 25 11:49:02 2005 New Revision: 8545 Modified: pypy/dist/pypy/interpreter/test/test_code.py Log: * removed unnecessary imports Modified: pypy/dist/pypy/interpreter/test/test_code.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_code.py (original) +++ pypy/dist/pypy/interpreter/test/test_code.py Tue Jan 25 11:49:02 2005 @@ -1,7 +1,4 @@ -import autopath -import unittest - class AppTestCodeIntrospection: From ludal at codespeak.net Tue Jan 25 11:56:10 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 11:56:10 +0100 (MET) Subject: [pypy-svn] r8546 - in pypy/dist/pypy: interpreter interpreter/test module Message-ID: <20050125105610.4336D27B84@code1.codespeak.net> Author: ludal Date: Tue Jan 25 11:56:10 2005 New Revision: 8546 Added: pypy/dist/pypy/interpreter/test/test_py.py Modified: pypy/dist/pypy/interpreter/py.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: * added sys.execprefix, sys.prefix, sys.executable to sysinterp.py * fixed handling of argv - options passed after -c 'xxx' - argv[0] in the case where no arguments are passed to py.py Modified: pypy/dist/pypy/interpreter/py.py ============================================================================== --- pypy/dist/pypy/interpreter/py.py (original) +++ pypy/dist/pypy/interpreter/py.py Tue Jan 25 11:56:10 2005 @@ -19,7 +19,11 @@ options.append(make_option( '-i', action="store_true", dest="interactive", help="inspect interactively after running script")) - + + options.append(make_option( + '-O', action="store_true", dest="optimize", + help="dummy optimization flag for compatibility with C Python")) + def command_callback(option, opt, value, parser): parser.values.command = parser.rargs[:] parser.rargs[:] = [] @@ -39,8 +43,9 @@ space = option.objspace() go_interactive = Options.interactive banner = '' + space.setitem(space.sys.w_dict,space.wrap('executable'),space.wrap(argv[0])) if Options.command: - args = ['-c'] + args = ['-c'] + Options.command[1:] for arg in args: space.call_method(space.sys.w_argv, 'append', space.wrap(arg)) if Options.command: @@ -54,6 +59,7 @@ except error.PyPyError, pypyerr: pypyerr.operationerr.print_detailed_traceback(pypyerr.space) else: + space.call_method(space.sys.w_argv, 'append', space.wrap('')) go_interactive = 1 banner = None if go_interactive: Added: pypy/dist/pypy/interpreter/test/test_py.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/interpreter/test/test_py.py Tue Jan 25 11:56:10 2005 @@ -0,0 +1,57 @@ + +import pypy.interpreter.py +from pypy.tool.udir import udir +import py +import sys + +pypath = str(py.path.local(pypy.interpreter.py.__file__).new(basename='py.py')) + +def test_executable(): + """Ensures sys.executable points to the py.py script""" + # TODO : watch out for spaces/special chars in pypath + output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.executable' ''' % pypath ) + assert output.splitlines()[-1] == pypath + +def test_prefix(): + """Make sure py.py sys.prefix and exec_prefix are the same as C Python's""" + output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.prefix' ''' % pypath ) + assert output.splitlines()[-1] == sys.prefix + output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.exec_prefix' ''' % pypath ) + assert output.splitlines()[-1] == sys.exec_prefix + +def test_argv_command(): + """Some tests on argv""" + # test 1 : no arguments + output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.argv' ''' % pypath ) + assert output.splitlines()[-1] == str(['-c']) + + # test 2 : some arguments after + output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.argv' hello''' % pypath ) + assert output.splitlines()[-1] == str(['-c','hello']) + + # test 3 : additionnal pypy parameters + output = py.process.cmdexec( '''"%s" -O -c 'import sys;print sys.argv' hello''' % pypath ) + assert output.splitlines()[-1] == str(['-c','hello']) + +SCRIPT_1 = """ +import sys +print sys.argv +""" +def test_scripts(): + tmpfilepath = str(udir.join("test_py_script.py")) + tmpfile = file( tmpfilepath, "w" ) + tmpfile.write(SCRIPT_1) + tmpfile.close() + + # test 1 : no arguments + output = py.process.cmdexec( '''"%s" "%s" ''' % (pypath,tmpfilepath) ) + assert output.splitlines()[-1] == str([tmpfilepath]) + + # test 2 : some arguments after + output = py.process.cmdexec( '''"%s" "%s" hello''' % (pypath,tmpfilepath) ) + assert output.splitlines()[-1] == str([tmpfilepath,'hello']) + + # test 3 : additionnal pypy parameters + output = py.process.cmdexec( '''"%s" -O "%s" hello''' % (pypath,tmpfilepath) ) + assert output.splitlines()[-1] == str([tmpfilepath,'hello']) + Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 11:56:10 2005 @@ -71,8 +71,9 @@ w_platform = space.wrap(cpy_sys.platform) w_maxint = space.wrap(cpy_sys.maxint) w_byteorder = space.wrap(cpy_sys.byteorder) +w_exec_prefix = space.wrap(cpy_sys.exec_prefix) +w_prefix = space.wrap(cpy_sys.prefix) w_maxunicode = space.wrap(cpy_sys.maxunicode) - w_stdin = space.wrap(cpy_sys.stdin) w_stdout = space.wrap(cpy_sys.stdout) w_stderr = space.wrap(cpy_sys.stderr) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Tue Jan 25 11:56:10 2005 @@ -14,6 +14,7 @@ from __interplevel__ import stdin, stdout, stderr, maxint from __interplevel__ import platform, byteorder from __interplevel__ import pypy_objspaceclass +from __interplevel__ import exec_prefix, prefix # Functions from interpreter-level from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir @@ -21,11 +22,9 @@ from __interplevel__ import getcheckinterval, setcheckinterval # Dummy +executable = 'py.py' api_version = 0 copyright = '' -exec_prefix = '' -executable = '' -prefix = '' version = '2.3a0 (pypy build)' version_info = (2, 3, 0, 'alpha', 0) hexversion = 0x020300a0 From ac at codespeak.net Tue Jan 25 12:07:00 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 12:07:00 +0100 (MET) Subject: [pypy-svn] r8547 - pypy/dist/pypy/module Message-ID: <20050125110700.E8F6027B84@code1.codespeak.net> Author: ac Date: Tue Jan 25 12:07:00 2005 New Revision: 8547 Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: Add defaultencoding() to sys module. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Tue Jan 25 12:07:00 2005 @@ -185,3 +185,7 @@ """NOT_RPYTHON""" from pypy.tool.udir import udir return space.wrap(str(udir)) + +def getdefaultencoding(): + """getdefaultencoding() -> return the default encoding used for UNICODE""" + return space.wrap(cpy_sys.getdefaultencoding()) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Tue Jan 25 12:07:00 2005 @@ -20,6 +20,7 @@ from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir from __interplevel__ import getrecursionlimit, setrecursionlimit from __interplevel__ import getcheckinterval, setcheckinterval +from __interplevel__ import getdefaultencoding # Dummy executable = 'py.py' From mwh at codespeak.net Tue Jan 25 12:09:31 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 12:09:31 +0100 (MET) Subject: [pypy-svn] r8548 - pypy/dist/pypy/annotation Message-ID: <20050125110931.A37F127B84@code1.codespeak.net> Author: mwh Date: Tue Jan 25 12:09:31 2005 New Revision: 8548 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/annotation/model.py Log: Some special handling of SomePBC(None) in union methods. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Tue Jan 25 12:09:31 2005 @@ -24,7 +24,7 @@ 'getitem', 'setitem', 'inplace_add', 'inplace_sub', 'lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_', - 'union']) + 'union', 'issubtype']) for opname in BINARY_OPERATIONS: missing_operation(pairtype(SomeObject, SomeObject), opname) @@ -286,6 +286,8 @@ class __extend__(pairtype(SomeInstance, SomePBC)): def union((ins, pbc)): + if pbc.isNone(): + return ins classdef = ins.classdef.superdef_containing(pbc.knowntype) if classdef is None: # print warning? Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Tue Jan 25 12:09:31 2005 @@ -185,8 +185,13 @@ prebuiltinstances = prebuiltinstances.copy() self.prebuiltinstances = prebuiltinstances self.simplify() - self.knowntype = reduce(commonbase, - [new_or_old_class(x) for x in prebuiltinstances]) + if self.isNone(): + self.knowntype = type(None) + else: + self.knowntype = reduce(commonbase, + [new_or_old_class(x) + for x in prebuiltinstances + if x is not None]) if prebuiltinstances.values() == [True]: # hack for the convenience of direct callers to SomePBC(): # only if there is a single object in prebuiltinstances and @@ -202,6 +207,9 @@ if isinstance(x.im_self, classdef.cls): del self.prebuiltinstances[x] + def isNone(self): + return self.prebuiltinstances == {None:True} + def fmt_prebuiltinstances(self, pbis): if hasattr(self, 'const'): return None From mwh at codespeak.net Tue Jan 25 12:16:16 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 12:16:16 +0100 (MET) Subject: [pypy-svn] r8549 - pypy/dist/pypy/annotation Message-ID: <20050125111616.866DA27B84@code1.codespeak.net> Author: mwh Date: Tue Jan 25 12:16:16 2005 New Revision: 8549 Modified: pypy/dist/pypy/annotation/model.py Log: Whitespace bigotry. Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Tue Jan 25 12:16:16 2005 @@ -174,6 +174,7 @@ else: return type(c) + class SomePBC(SomeObject): """Stands for a global user instance, built prior to the analysis, or a set of such instances.""" @@ -222,6 +223,7 @@ else: return kt.__name__ + class SomeBuiltin(SomeObject): "Stands for a built-in function or method with special-cased analysis." knowntype = BuiltinFunctionType # == BuiltinMethodType From mwh at codespeak.net Tue Jan 25 12:31:20 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 12:31:20 +0100 (MET) Subject: [pypy-svn] r8550 - in pypy/dist/pypy: annotation translator translator/test Message-ID: <20050125113120.69C9D27B84@code1.codespeak.net> Author: mwh Date: Tue Jan 25 12:31:20 2005 New Revision: 8550 Modified: pypy/dist/pypy/annotation/model.py pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: Begin annotation of slices: - add SomeSlice class - create them from newslice operations - test (bit icky, please rewrite if you know a better way!) Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Tue Jan 25 12:31:20 2005 @@ -129,6 +129,14 @@ self.s_item = s_item # general enough for any element +class SomeSlice(SomeObject): + knowntype = slice + def __init__(self, start, stop, step): + self.start = start + self.stop = stop + self.step = step + + class SomeTuple(SomeObject): "Stands for a tuple of known length." knowntype = tuple Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Tue Jan 25 12:31:20 2005 @@ -378,6 +378,9 @@ factory = self.bookkeeper.getfactory(DictFactory) return factory.create() + def consider_op_newslice(self, start, stop, step): + return annmodel.SomeSlice(start, stop, step) + class CannotSimplify(Exception): pass Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 12:31:20 2005 @@ -655,3 +655,6 @@ return x else: return apbc + +def simple_slice(x): + return x[:10] Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 12:31:20 2005 @@ -381,6 +381,17 @@ s_meth = s_example.getattr(iv(methname)) assert isinstance(s_constmeth, annmodel.SomeBuiltin) + def test_simple_slicing0(self): + a = RPythonAnnotator() + s = a.build_types(snippet.simple_slice, [list]) + g = a.translator.getflowgraph(snippet.simple_slice) + for thing in flatten(g): + if isinstance(thing, Block): + for op in thing.operations: + if op.opname == "newslice": + assert isinstance(a.binding(op.result), + annmodel.SomeSlice) + def g(n): return [0,1,2,n] From mwh at codespeak.net Tue Jan 25 12:45:16 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 12:45:16 +0100 (MET) Subject: [pypy-svn] r8551 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125114516.9AE2427B84@code1.codespeak.net> Author: mwh Date: Tue Jan 25 12:45:16 2005 New Revision: 8551 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/translator/test/test_annrpython.py Log: Finish annotation of slicing for lists + test. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Tue Jan 25 12:45:16 2005 @@ -7,7 +7,7 @@ from pypy.annotation.model import SomeString, SomeChar, SomeList, SomeDict from pypy.annotation.model import SomeTuple, SomeImpossibleValue from pypy.annotation.model import SomeInstance, SomeBuiltin, SomeIterator -from pypy.annotation.model import SomePBC +from pypy.annotation.model import SomePBC, SomeSlice from pypy.annotation.model import unionof, set, setunion, missing_operation from pypy.annotation.factory import generalize from pypy.annotation.bookkeeper import getbookkeeper @@ -223,6 +223,12 @@ generalize(lst1.factories, s_value) +class __extend__(pairtype(SomeList, SomeSlice)): + + def getitem((lst, slic)): + return SomeList(lst.factories, lst.s_item) + + class __extend__(pairtype(SomeString, SomeInteger)): def getitem((str1, int2)): Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 12:45:16 2005 @@ -392,6 +392,10 @@ assert isinstance(a.binding(op.result), annmodel.SomeSlice) + def test_simple_slicing(self): + a = RPythonAnnotator() + s = a.build_types(snippet.simple_slice, [list]) + assert isinstance(s, annmodel.SomeList) def g(n): return [0,1,2,n] From tismer at codespeak.net Tue Jan 25 13:04:30 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 25 Jan 2005 13:04:30 +0100 (MET) Subject: [pypy-svn] r8552 - pypy/dist/pypy/interpreter Message-ID: <20050125120430.8F1B227B6E@code1.codespeak.net> Author: tismer Date: Tue Jan 25 13:04:30 2005 New Revision: 8552 Modified: pypy/dist/pypy/interpreter/generator.py Log: fixed a bug in GeneratorIterator. It was not stopping the frame after the first StopIteration. Modified: pypy/dist/pypy/interpreter/generator.py ============================================================================== --- pypy/dist/pypy/interpreter/generator.py (original) +++ pypy/dist/pypy/interpreter/generator.py Tue Jan 25 13:04:30 2005 @@ -58,6 +58,7 @@ try: return self.frame.resume() except OperationError, e: + self.frame.exhausted = True if e.match(self.space, self.space.w_StopIteration): raise OperationError(space.w_StopIteration, space.w_None) else: From jacek at codespeak.net Tue Jan 25 13:05:48 2005 From: jacek at codespeak.net (jacek at codespeak.net) Date: Tue, 25 Jan 2005 13:05:48 +0100 (MET) Subject: [pypy-svn] r8553 - in pypy/dist/pypy/objspace: . std/test Message-ID: <20050125120548.F142927B6E@code1.codespeak.net> Author: jacek Date: Tue Jan 25 13:05:48 2005 New Revision: 8553 Modified: pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/test/test_intobject.py Log: Checking that the value returned by __int__ methods is of an acceptable type Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Jan 25 13:05:48 2005 @@ -155,6 +155,20 @@ return space.get_and_call_function(w_descr, w_obj) # XXX PyObject_Str() checks that the result is a string + def int(space, w_obj): + w_impl = space.lookup(w_obj, '__int__') + if w_impl is None: + raise OperationError(space.w_TypeError, + space.wrap("operand does not support unary %s" % symbol)) + w_result = space.get_and_call_function(w_impl, w_obj) + + if space.is_true(space.isinstance(w_result, space.w_int)) or \ + space.is_true(space.isinstance(w_result, space.w_long)): + return w_result + w_typename = space.getattr(space.type(w_result), space.wrap('__name__')) + w_msg = space.mod(space.wrap("__int__ returned non-int (%s)"), w_typename) + raise OperationError(space.w_TypeError, w_msg) + def repr(space, w_obj): w_descr = space.lookup(w_obj, '__repr__') return space.get_and_call_function(w_descr, w_obj) Modified: pypy/dist/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_intobject.py Tue Jan 25 13:05:48 2005 @@ -333,3 +333,8 @@ assert isinstance(j("100",2),j) raises(OverflowError,j,10000000000) raises(OverflowError,j,"10000000000") + + def test_special_int_method(self): + class a: + def __int__(self): return None + raises(TypeError, int, a()) From mwh at codespeak.net Tue Jan 25 13:10:28 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 13:10:28 +0100 (MET) Subject: [pypy-svn] r8554 - pypy/dist/pypy/documentation Message-ID: <20050125121028.77A9927B7B@code1.codespeak.net> Author: mwh Date: Tue Jan 25 13:10:28 2005 New Revision: 8554 Modified: pypy/dist/pypy/documentation/annotation.txt Log: Not flagrant out-of-date-ness. Modified: pypy/dist/pypy/documentation/annotation.txt ============================================================================== --- pypy/dist/pypy/documentation/annotation.txt (original) +++ pypy/dist/pypy/documentation/annotation.txt Tue Jan 25 13:10:28 2005 @@ -7,6 +7,9 @@ but before these graphs are translated into low-level code (e.g. C/Lisp/Pyrex). +**THIS IS OUT OF DATE** (not to mention insane!) + +I guess we should document the new world sometime.. An example: the factorial ------------------------- From ludal at codespeak.net Tue Jan 25 13:39:45 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 13:39:45 +0100 (MET) Subject: [pypy-svn] r8557 - pypy/dist/pypy/module Message-ID: <20050125123945.A2EEF27B5F@code1.codespeak.net> Author: ludal Date: Tue Jan 25 13:39:45 2005 New Revision: 8557 Modified: pypy/dist/pypy/module/__builtin__module.py Log: * make complex.__coerce__ returns NotImplemented - modifies all operators accordingly - change cmp so that it compares identity first, then equality, then ... Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Jan 25 13:39:45 2005 @@ -287,10 +287,12 @@ def cmp(x, y): """return 0 when x == y, -1 when x < y and 1 when x > y """ - if x < y: - return -1 - elif x == y: + if x is y: + return 0 + if x == y: return 0 + elif x < y: + return -1 else: return 1 @@ -694,7 +696,10 @@ def __add__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result real = self.real + other.real imag = self.imag + other.imag return complex(real, imag) @@ -702,17 +707,26 @@ __radd__ = __add__ def __sub__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result real = self.real - other.real imag = self.imag - other.imag return complex(real, imag) def __rsub__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return other.__sub__(self) def __mul__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result real = self.real*other.real - self.imag*other.imag imag = self.real*other.imag + self.imag*other.real return complex(real, imag) @@ -720,7 +734,10 @@ __rmul__ = __mul__ def __div__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result if abs(other.real) >= abs(other.imag): # divide tops and bottom by other.real try: @@ -741,30 +758,48 @@ return complex(real, imag) def __rdiv__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return other.__div__(self) def __floordiv__(self, other): - div, mod = self.__divmod__(other) + result = self.__divmod__(other) + if result is NotImplemented: + return result + div, mod = result return div def __rfloordiv__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return other.__floordiv__(self) __truediv__ = __div__ __rtruediv__ = __rdiv__ def __mod__(self, other): - div, mod = self.__divmod__(other) + result = self.__divmod__(other) + if result is NotImplemented: + return result + div, mod = result return mod def __rmod__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return other.__mod__(self) def __divmod__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result import warnings, math warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) @@ -779,7 +814,12 @@ def __pow__(self, other, mod=None): - a, b = self.__coerce__(other) + if mod is not None: + raise ValueError("complex modulo") + result = self.__coerce__(other) + if result is NotImplemented: + return result + a, b = result import math if b.real == 0. and b.imag == 0.: @@ -800,12 +840,13 @@ imag = len*math.sin(phase) result = complex(real, imag) - if mod is not None: - result %= mod return result def __rpow__(self, other, mod=None): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return other.__pow__(self, mod) def __neg__(self): @@ -831,18 +872,23 @@ return self, other if isinstance(other, (int, long, float)): return self, complex(other) - raise TypeError, "number %r coercion failed" % (type(other),) - + return NotImplemented def conjugate(self): return complex(self.real, -self.imag) def __eq__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return self.real == other.real and self.imag == other.imag def __ne__(self, other): - self, other = self.__coerce__(other) + result = self.__coerce__(other) + if result is NotImplemented: + return result + self, other = result return self.real != other.real or self.imag != other.imag From adim at codespeak.net Tue Jan 25 14:27:13 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 14:27:13 +0100 (MET) Subject: [pypy-svn] r8558 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125132713.6260027B5F@code1.codespeak.net> Author: adim Date: Tue Jan 25 14:27:13 2005 New Revision: 8558 Modified: pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: added iter builtin (and tests for dict and list) implemented SomeDict.iter Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Tue Jan 25 14:27:13 2005 @@ -107,6 +107,9 @@ return s_iterable return SomeObject() +def builtin_iter(s_obj): + return s_obj.iter() + def builtin_type(s_obj, *moreargs): if moreargs: raise Exception, 'type() called with more than one argument' Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 14:27:13 2005 @@ -108,6 +108,10 @@ def iter(lst): return SomeIterator(lst.s_item) +class __extend__(SomeDict): + def iter(dct): + return SomeIterator(dct.s_key) + class __extend__(SomeString): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 14:27:13 2005 @@ -658,3 +658,6 @@ def simple_slice(x): return x[:10] + +def simple_iter(x): + return iter(x) Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 14:27:13 2005 @@ -397,6 +397,19 @@ s = a.build_types(snippet.simple_slice, [list]) assert isinstance(s, annmodel.SomeList) + + def test_simple_iter_list(self): + a = RPythonAnnotator() + s = a.build_types(snippet.simple_iter, [list]) + assert isinstance(s, annmodel.SomeIterator) + + def test_simple_iter_dict(self): + a = RPythonAnnotator() + t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) + s = a.build_types(snippet.simple_iter, [t]) + assert isinstance(s, annmodel.SomeIterator) + + def g(n): return [0,1,2,n] From adim at codespeak.net Tue Jan 25 14:48:05 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 14:48:05 +0100 (MET) Subject: [pypy-svn] r8559 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125134805.4441327B5F@code1.codespeak.net> Author: adim Date: Tue Jan 25 14:48:05 2005 New Revision: 8559 Modified: pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: SomeDict.copy() + test Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 14:48:05 2005 @@ -112,7 +112,9 @@ def iter(dct): return SomeIterator(dct.s_key) - + def method_copy(dct): + return SomeDict(dct.factories, dct.s_key, dct.s_value) + class __extend__(SomeString): def method_join(str, s_list): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 14:48:05 2005 @@ -661,3 +661,6 @@ def simple_iter(x): return iter(x) + +def dict_copy(d): + return d.copy() Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 14:48:05 2005 @@ -409,6 +409,14 @@ s = a.build_types(snippet.simple_iter, [t]) assert isinstance(s, annmodel.SomeIterator) + def test_dict_copy(self): + a = RPythonAnnotator() + t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) + s = a.build_types(snippet.dict_copy, [t]) + assert isinstance(s, annmodel.SomeDict) + assert isinstance(s.s_key, annmodel.SomeInteger) + assert isinstance(s.s_value, annmodel.SomeInteger) + def g(n): return [0,1,2,n] From arigo at codespeak.net Tue Jan 25 14:56:55 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 25 Jan 2005 14:56:55 +0100 (MET) Subject: [pypy-svn] r8560 - pypy/dist/pypy/objspace/std Message-ID: <20050125135655.8C98E27B60@code1.codespeak.net> Author: arigo Date: Tue Jan 25 14:56:55 2005 New Revision: 8560 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: Hum. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Tue Jan 25 14:56:55 2005 @@ -148,7 +148,7 @@ def pow__Long_Long_Long(space, w_long1, w_long2, w_long3): x = w_long1.longval y = w_long2.longval - z = w_long2.longval + z = w_long3.longval t = pow(x, y, z) return W_LongObject(space, t) From adim at codespeak.net Tue Jan 25 15:00:27 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 15:00:27 +0100 (MET) Subject: [pypy-svn] r8561 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125140027.8390C27B6E@code1.codespeak.net> Author: adim Date: Tue Jan 25 15:00:27 2005 New Revision: 8561 Modified: pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: SomeDict.update + tests also, converted a few tabs inadvertantly introduced in the earlier checkins. Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 15:00:27 2005 @@ -11,7 +11,7 @@ from pypy.annotation.model import SomeInstance, SomeBuiltin from pypy.annotation.model import SomeIterator, SomePBC, new_or_old_class from pypy.annotation.model import unionof, set, setunion, missing_operation -from pypy.annotation.factory import BlockedInference +from pypy.annotation.factory import BlockedInference, generalize from pypy.annotation.bookkeeper import getbookkeeper from pypy.annotation.classdef import isclassdef @@ -110,10 +110,13 @@ class __extend__(SomeDict): def iter(dct): - return SomeIterator(dct.s_key) + return SomeIterator(dct.s_key) def method_copy(dct): - return SomeDict(dct.factories, dct.s_key, dct.s_value) + return SomeDict(dct.factories, dct.s_key, dct.s_value) + + def method_update(dct1, dct2): + generalize(dct1.factories, dct2.s_key, dct2.s_value) class __extend__(SomeString): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 15:00:27 2005 @@ -664,3 +664,8 @@ def dict_copy(d): return d.copy() + +def dict_update(x): + d = {x:x} + d.update({1:2}) + return d Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 15:00:27 2005 @@ -402,20 +402,33 @@ a = RPythonAnnotator() s = a.build_types(snippet.simple_iter, [list]) assert isinstance(s, annmodel.SomeIterator) - + def test_simple_iter_dict(self): a = RPythonAnnotator() - t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) + t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) s = a.build_types(snippet.simple_iter, [t]) assert isinstance(s, annmodel.SomeIterator) - + def test_dict_copy(self): a = RPythonAnnotator() - t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) + t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) s = a.build_types(snippet.dict_copy, [t]) - assert isinstance(s, annmodel.SomeDict) - assert isinstance(s.s_key, annmodel.SomeInteger) - assert isinstance(s.s_value, annmodel.SomeInteger) + assert isinstance(s, annmodel.SomeDict) + assert isinstance(s.s_key, annmodel.SomeInteger) + assert isinstance(s.s_value, annmodel.SomeInteger) + + def test_dict_update(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_update, [int]) + assert isinstance(s, annmodel.SomeDict) + assert isinstance(s.s_key, annmodel.SomeInteger) + assert isinstance(s.s_value, annmodel.SomeInteger) + + a = RPythonAnnotator() + s = a.build_types(snippet.dict_update, [str]) + assert isinstance(s, annmodel.SomeDict) + assert not isinstance(s.s_key, annmodel.SomeString) + assert not isinstance(s.s_value, annmodel.SomeString) def g(n): From ac at codespeak.net Tue Jan 25 15:04:05 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 15:04:05 +0100 (MET) Subject: [pypy-svn] r8562 - pypy/dist/pypy/objspace/std Message-ID: <20050125140405.E817927B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 15:04:05 2005 New Revision: 8562 Modified: pypy/dist/pypy/objspace/std/iterobject.py Log: Fix sequencs iteration Modified: pypy/dist/pypy/objspace/std/iterobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/iterobject.py (original) +++ pypy/dist/pypy/objspace/std/iterobject.py Tue Jan 25 15:04:05 2005 @@ -15,7 +15,6 @@ w_self.w_seq = w_seq w_self.index = index - registerimplementation(W_SeqIterObject) @@ -23,9 +22,12 @@ return w_seqiter def next__SeqIter(space, w_seqiter): + if w_seqiter.w_seq is None: + raise OperationError(space.w_StopIteration, space.w_None) try: w_item = space.getitem(w_seqiter.w_seq, space.wrap(w_seqiter.index)) except OperationError, e: + w_seqiter.w_seq = None if not e.match(space, space.w_IndexError): raise raise OperationError(space.w_StopIteration, space.w_None) From hpk at codespeak.net Tue Jan 25 15:16:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 25 Jan 2005 15:16:17 +0100 (MET) Subject: [pypy-svn] r8563 - in pypy/dist/pypy/objspace: . std/test test Message-ID: <20050125141617.4871327B6E@code1.codespeak.net> Author: hpk Date: Tue Jan 25 15:16:17 2005 New Revision: 8563 Modified: pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/test/test_floatobject.py pypy/dist/pypy/objspace/std/test/test_intobject.py pypy/dist/pypy/objspace/test/test_descriptor.py Log: (jacek, holger) - added stricter implementations for space.int/float/long/str/oct/hex/repr by means of funny string-templating (nobody really wants to code all this manually, right?) - added a couple of tests although we were a bit unsure of where to best put them. Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Jan 25 15:16:17 2005 @@ -150,30 +150,6 @@ return space.is_true(w_res) return True - def str(space, w_obj): - w_descr = space.lookup(w_obj, '__str__') - return space.get_and_call_function(w_descr, w_obj) - # XXX PyObject_Str() checks that the result is a string - - def int(space, w_obj): - w_impl = space.lookup(w_obj, '__int__') - if w_impl is None: - raise OperationError(space.w_TypeError, - space.wrap("operand does not support unary %s" % symbol)) - w_result = space.get_and_call_function(w_impl, w_obj) - - if space.is_true(space.isinstance(w_result, space.w_int)) or \ - space.is_true(space.isinstance(w_result, space.w_long)): - return w_result - w_typename = space.getattr(space.type(w_result), space.wrap('__name__')) - w_msg = space.mod(space.wrap("__int__ returned non-int (%s)"), w_typename) - raise OperationError(space.w_TypeError, w_msg) - - def repr(space, w_obj): - w_descr = space.lookup(w_obj, '__repr__') - return space.get_and_call_function(w_descr, w_obj) - # XXX PyObject_Repr() probably checks that the result is a string - def iter(space, w_obj): w_descr = space.lookup(w_obj, '__iter__') if w_descr is None: @@ -402,9 +378,44 @@ space.wrap("operand does not support unary %s" % symbol)) return space.get_and_call_function(w_impl, w_obj) return func_with_new_name(unaryop_impl, 'unaryop_%s_impl'%specialname.strip('_')) - -# add regular methods +# the following seven operations are really better to generate with +# string-templating (and maybe we should consider this for +# more of the above manually-coded operations as well) + +for targetname, specialname, checkerspec in [ + ('int', '__int__', ("space.w_int", "space.w_long")), + ('long', '__long__', ("space.w_int", "space.w_long")), + ('float', '__float__', ("space.w_float",)), + ('str', '__str__', ("space.w_str",)), + ('repr', '__repr__', ("space.w_str",)), + ('oct', '__oct__', ("space.w_str",)), + ('hex', '__hex__', ("space.w_str",))]: + + l = ["space.is_true(space.isinstance(w_result, %s))" % x + for x in checkerspec] + checker = " or ".join(l) + exec """ +def %(targetname)s(space, w_obj): + w_impl = space.lookup(w_obj, %(specialname)r) + if w_impl is None: + raise OperationError(space.w_TypeError, + space.wrap("operand does not support unary %(targetname)s")) + w_result = space.get_and_call_function(w_impl, w_obj) + + if %(checker)s: + return w_result + typename = space.str_w(space.getattr(space.type(w_result), + space.wrap('__name__'))) + msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) + raise OperationError(space.w_TypeError, space.wrap(msg)) +assert not hasattr(DescrOperation, %(targetname)r) +DescrOperation.%(targetname)s = %(targetname)s +del %(targetname)s +""" % locals() + + +# add default operation implementations for all still missing ops for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: if not hasattr(DescrOperation, _name): Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_floatobject.py Tue Jan 25 15:16:17 2005 @@ -75,3 +75,16 @@ assert 22.2 == round(22.222222, 1) assert 20.0 == round(22.22222, -1) assert 0.0 == round(22.22222, -2) + + def test_special_float_method(self): + class a: + def __float__(self): + self.ar = True + return None + inst = a() + raises(TypeError, float, inst) + assert inst.ar + + class b: + pass + raises(TypeError, float, b()) Modified: pypy/dist/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_intobject.py Tue Jan 25 15:16:17 2005 @@ -334,7 +334,28 @@ raises(OverflowError,j,10000000000) raises(OverflowError,j,"10000000000") - def test_special_int_method(self): + def test_special_int(self): class a: - def __int__(self): return None - raises(TypeError, int, a()) + def __int__(self): + self.ar = True + return None + inst = a() + raises(TypeError, int, inst) + assert inst.ar == True + + class b: + pass + raises(TypeError, int, b()) + + def test_special_long(self): + class a: + def __long__(self): + self.ar = True + return None + inst = a() + raises(TypeError, long, inst) + assert inst.ar == True + + class b: + pass + raises(TypeError, int, b()) Modified: pypy/dist/pypy/objspace/test/test_descriptor.py ============================================================================== --- pypy/dist/pypy/objspace/test/test_descriptor.py (original) +++ pypy/dist/pypy/objspace/test/test_descriptor.py Tue Jan 25 15:16:17 2005 @@ -23,3 +23,22 @@ assert sys.stdin.softspace == 0 raises(TypeError, delattr, sys.stdin, 'softspace') raises(TypeError, file.softspace.__delete__, sys.stdin) + + def test_special_methods_returning_strings(self): + class A: + seen = [] + def __str__(self): + self.seen.append(1) + def __repr__(self): + self.seen.append(2) + def __oct__(self): + self.seen.append(3) + def __hex__(self): + self.seen.append(4) + + inst = A() + raises(TypeError, str, inst) + raises(TypeError, repr, inst) + raises(TypeError, oct, inst) + raises(TypeError, hex, inst) + assert A.seen == [1,2,3,4] From arigo at codespeak.net Tue Jan 25 15:29:03 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 25 Jan 2005 15:29:03 +0100 (MET) Subject: [pypy-svn] r8564 - pypy/dist/pypy/appspace Message-ID: <20050125142903.78D8827B6E@code1.codespeak.net> Author: arigo Date: Tue Jan 25 15:29:03 2005 New Revision: 8564 Modified: pypy/dist/pypy/appspace/operator.py Log: Fixed the operator module. Modified: pypy/dist/pypy/appspace/operator.py ============================================================================== --- pypy/dist/pypy/appspace/operator.py (original) +++ pypy/dist/pypy/appspace/operator.py Tue Jan 25 15:29:03 2005 @@ -1,6 +1,8 @@ +import __builtin__ + def abs(obj,): 'abs(a) -- Same as abs(a).' - return abs(obj) + return __builtin__.abs(obj) __abs__ = abs def add(obj1, obj2): 'add(a, b) -- Same as a + b.' @@ -12,14 +14,18 @@ __and__ = and_ def concat(obj1, obj2): 'concat(a, b) -- Same as a + b, for a and b sequences.' - return obj1 + obj2 # XXX + return obj1 + obj2 # XXX should we be stricter? def contains(obj1,obj2): 'contains(a, b) -- Same as b in a (note reversed operands).' return obj2 in obj1 __contains__ = contains def countOf(a,b): 'countOf(a, b) -- Return the number of times b occurs in a.' - raise NotImplementedError + count = 0 + for x in a: + if x == b: + count += 1 + return count def delitem(obj, key): 'delitem(a, b) -- Same as del a[b].' del obj[key] @@ -58,7 +64,12 @@ __gt__ = gt def indexOf(a, b): 'indexOf(a, b) -- Return the first index of b in a.' - raise NotImplementedError + index = 0 + for x in a: + if x == b: + return index + index += 1 + raise ValueError, 'sequence.index(x): x not in sequence' def inv(obj,): 'inv(a) -- Same as ~a.' return ~obj @@ -70,15 +81,18 @@ def isCallable(obj,): 'isCallable(a) -- Same as callable(a).' return callable(obj) + +# XXX the following is approximative def isMappingType(obj,): 'isMappingType(a) -- Return True if a has a mapping type, False otherwise.' - return hasattr(obj, '__getitem__') # Xxx only close + return hasattr(obj, '__getitem__') and hasattr(obj, 'keys') def isNumberType(obj,): 'isNumberType(a) -- Return True if a has a numeric type, False otherwise.' return hasattr(obj, '__int__') or hasattr(obj, '__float__') def isSequenceType(obj,): 'isSequenceType(a) -- Return True if a has a sequence type, False otherwise.' - return hasattr(obj, '__getitem__') # Xxx only close + return hasattr(obj, '__getitem__') + def is_(a, b): 'is_(a, b) -- Same as a is b.' return a is b @@ -111,7 +125,7 @@ __ne__ = ne def neg(obj,): 'neg(a) -- Same as -a.' - return -a + return -obj __neg__ = neg def not_(obj,): 'not_(a) -- Same as not a.' @@ -130,14 +144,19 @@ __pow__ = pow def repeat(obj, num): 'repeat(a, b) -- Return a * b, where a is a sequence, and b is an integer.' - return obj * num + if not isinstance(num, (int, long)): + raise TypeError, 'an integer is required' + return obj * num # XXX should we be stricter? def rshift(a, b): 'rshift(a, b) -- Same as a >> b.' return a >> b __rshift__ = rshift def sequenceIncludes(a, b): 'sequenceIncludes(a, b) -- Same as b in a (note reversed operands; deprecated).' - raise NotImplementedError + for x in a: + if x == b: + return True + return False def setitem(obj, key, value): 'setitem(a, b, c) -- Same as a[b] = c.' obj[key] = value @@ -150,9 +169,12 @@ 'sub(a, b) -- Same as a - b.' return a - b __sub__ = sub + +exec """from __future__ import division def truediv(a, b): 'truediv(a, b) -- Same as a / b when __future__.division is in effect.' return a / b +""" __truediv__ = truediv def truth(a,): 'truth(a) -- Return True if a is true, False otherwise.' From arigo at codespeak.net Tue Jan 25 15:31:45 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 25 Jan 2005 15:31:45 +0100 (MET) Subject: [pypy-svn] r8565 - pypy/dist/pypy/objspace/std Message-ID: <20050125143145.A1B1327B6E@code1.codespeak.net> Author: arigo Date: Tue Jan 25 15:31:45 2005 New Revision: 8565 Modified: pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/intobject.py pypy/dist/pypy/objspace/std/longobject.py Log: Populate the truediv multimethod. Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Tue Jan 25 15:31:45 2005 @@ -175,6 +175,8 @@ # no overflow return W_FloatObject(space, z) +truediv__Float_Float = div__Float_Float + def floordiv__Float_Float(space, w_float1, w_float2): x = w_float1.floatval y = w_float2.floatval Modified: pypy/dist/pypy/objspace/std/intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/intobject.py (original) +++ pypy/dist/pypy/objspace/std/intobject.py Tue Jan 25 15:31:45 2005 @@ -211,14 +211,16 @@ m = x % y return space.wrap((z,m)) +old_style_div = 1 / 2 == 1 // 2 def div__Int_Int(space, w_int1, w_int2): # Select the proper div - if 1 / 2 == 1 // 2: + if old_style_div: return _floordiv(space, w_int1, w_int2) else: return _truediv(space, w_int1, w_int2) floordiv__Int_Int = _floordiv +truediv__Int_Int = _truediv # helper for pow() def _impl_int_int_pow(space, iv, iw, iz=None): Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Tue Jan 25 15:31:45 2005 @@ -107,6 +107,8 @@ z = x / y return W_LongObject(space, z) +truediv__Long_Long = div__Long_Long + def floordiv__Long_Long(space, w_long1, w_long2): x = w_long1.longval y = w_long2.longval From arigo at codespeak.net Tue Jan 25 15:32:02 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 25 Jan 2005 15:32:02 +0100 (MET) Subject: [pypy-svn] r8566 - pypy/dist/pypy/appspace/test/patched Message-ID: <20050125143202.ECAE327B6E@code1.codespeak.net> Author: arigo Date: Tue Jan 25 15:32:02 2005 New Revision: 8566 Modified: pypy/dist/pypy/appspace/test/patched/ (props changed) Log: fixeol. From adim at codespeak.net Tue Jan 25 15:44:32 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 15:44:32 +0100 (MET) Subject: [pypy-svn] r8567 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125144432.7B23427B6E@code1.codespeak.net> Author: adim Date: Tue Jan 25 15:44:32 2005 New Revision: 8567 Modified: pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: SomeDict.keys() + tests Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 15:44:32 2005 @@ -11,7 +11,7 @@ from pypy.annotation.model import SomeInstance, SomeBuiltin from pypy.annotation.model import SomeIterator, SomePBC, new_or_old_class from pypy.annotation.model import unionof, set, setunion, missing_operation -from pypy.annotation.factory import BlockedInference, generalize +from pypy.annotation.factory import BlockedInference, generalize, ListFactory from pypy.annotation.bookkeeper import getbookkeeper from pypy.annotation.classdef import isclassdef @@ -117,7 +117,12 @@ def method_update(dct1, dct2): generalize(dct1.factories, dct2.s_key, dct2.s_value) - + + def method_keys(dct): + factory = getbookkeeper().getfactory(ListFactory) + factory.generalize(dct.s_key) + return factory.create() + class __extend__(SomeString): def method_join(str, s_list): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 15:44:32 2005 @@ -669,3 +669,14 @@ d = {x:x} d.update({1:2}) return d + +def dict_keys(): + d = {"a" : 1} + return d.keys() + +def dict_keys2(): + d = {"a" : 1} + keys = d.keys() + d[1] = 12 + return keys + Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 15:44:32 2005 @@ -423,13 +423,27 @@ assert isinstance(s, annmodel.SomeDict) assert isinstance(s.s_key, annmodel.SomeInteger) assert isinstance(s.s_value, annmodel.SomeInteger) - + a = RPythonAnnotator() s = a.build_types(snippet.dict_update, [str]) assert isinstance(s, annmodel.SomeDict) assert not isinstance(s.s_key, annmodel.SomeString) assert not isinstance(s.s_value, annmodel.SomeString) + def test_dict_keys(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_keys, []) + assert isinstance(s, annmodel.SomeList) + assert isinstance(s.s_item, annmodel.SomeString) + + def test_dict_keys2(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_keys2, []) + assert isinstance(s, annmodel.SomeList) + assert not isinstance(s.s_item, annmodel.SomeString) + + + def g(n): return [0,1,2,n] From mwh at codespeak.net Tue Jan 25 15:47:17 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 15:47:17 +0100 (MET) Subject: [pypy-svn] r8568 - pypy/dist/pypy/objspace/flow Message-ID: <20050125144717.8ADD027B6E@code1.codespeak.net> Author: mwh Date: Tue Jan 25 15:47:17 2005 New Revision: 8568 Modified: pypy/dist/pypy/objspace/flow/model.py Log: name some Variables. Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Tue Jan 25 15:47:17 2005 @@ -15,8 +15,8 @@ self.returnblock.operations = () self.returnblock.exits = () # block corresponding to exception results - self.exceptblock = Block([Variable(), # exception class - Variable()]) # exception value + self.exceptblock = Block([Variable('etype'), # exception class + Variable('evalue')]) # exception value self.exceptblock.operations = () self.exceptblock.exits = () From mwh at codespeak.net Tue Jan 25 15:51:43 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 15:51:43 +0100 (MET) Subject: [pypy-svn] r8569 - pypy/dist/pypy/annotation Message-ID: <20050125145143.5D24B27B6E@code1.codespeak.net> Author: mwh Date: Tue Jan 25 15:51:43 2005 New Revision: 8569 Modified: pypy/dist/pypy/annotation/builtin.py Log: builtin_repr Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Tue Jan 25 15:51:43 2005 @@ -120,6 +120,9 @@ def builtin_str(s_obj): return SomeString() +def builtin_repr(s_obj): + return SomeString() + def builtin_list(s_iterable): factory = getbookkeeper().getfactory(ListFactory) s_iter = s_iterable.iter() From adim at codespeak.net Tue Jan 25 15:54:05 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 15:54:05 +0100 (MET) Subject: [pypy-svn] r8570 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125145405.D219827B6E@code1.codespeak.net> Author: adim Date: Tue Jan 25 15:54:05 2005 New Revision: 8570 Modified: pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: added values() operation on SomeDict (+ tests) Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 15:54:05 2005 @@ -122,6 +122,12 @@ factory = getbookkeeper().getfactory(ListFactory) factory.generalize(dct.s_key) return factory.create() + + def method_values(dct): + factory = getbookkeeper().getfactory(ListFactory) + factory.generalize(dct.s_value) + return factory.create() + class __extend__(SomeString): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 15:54:05 2005 @@ -680,3 +680,13 @@ d[1] = 12 return keys +def dict_values(): + d = {"a" : "a"} + return d.values() + +def dict_values2(): + d = {"a" : "a"} + values = d.values() + d[1] = 12 + return values + Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 15:54:05 2005 @@ -442,6 +442,17 @@ assert isinstance(s, annmodel.SomeList) assert not isinstance(s.s_item, annmodel.SomeString) + def test_dict_values(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_values, []) + assert isinstance(s, annmodel.SomeList) + assert isinstance(s.s_item, annmodel.SomeString) + + def test_dict_values2(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_values2, []) + assert isinstance(s, annmodel.SomeList) + assert not isinstance(s.s_item, annmodel.SomeString) From adim at codespeak.net Tue Jan 25 16:04:37 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 25 Jan 2005 16:04:37 +0100 (MET) Subject: [pypy-svn] r8571 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050125150437.7654227B6E@code1.codespeak.net> Author: adim Date: Tue Jan 25 16:04:37 2005 New Revision: 8571 Modified: pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: added SomeDict.items() operation (+ tests) Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Tue Jan 25 16:04:37 2005 @@ -128,6 +128,12 @@ factory.generalize(dct.s_value) return factory.create() + def method_items(dct): + factory = getbookkeeper().getfactory(ListFactory) + factory.generalize(SomeTuple((dct.s_key, dct.s_value))) + return factory.create() + + class __extend__(SomeString): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Jan 25 16:04:37 2005 @@ -690,3 +690,7 @@ d[1] = 12 return values +def dict_items(): + d = {'a' : 1} + return d.items() + Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Tue Jan 25 16:04:37 2005 @@ -453,7 +453,16 @@ s = a.build_types(snippet.dict_values2, []) assert isinstance(s, annmodel.SomeList) assert not isinstance(s.s_item, annmodel.SomeString) - + + def test_dict_items(self): + a = RPythonAnnotator() + s = a.build_types(snippet.dict_items, []) + assert isinstance(s, annmodel.SomeList) + assert isinstance(s.s_item, annmodel.SomeTuple) + s_key, s_value = s.s_item.items + assert isinstance(s_key, annmodel.SomeString) + assert isinstance(s_value, annmodel.SomeInteger) + def g(n): From mwh at codespeak.net Tue Jan 25 16:22:42 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 16:22:42 +0100 (MET) Subject: [pypy-svn] r8572 - pypy/dist/pypy/interpreter Message-ID: <20050125152242.632AE27B6E@code1.codespeak.net> Author: mwh Date: Tue Jan 25 16:22:42 2005 New Revision: 8572 Modified: pypy/dist/pypy/interpreter/argument.py Log: Check in my 'help the annotator' hack for except e, ArgErr: Modified: pypy/dist/pypy/interpreter/argument.py ============================================================================== --- pypy/dist/pypy/interpreter/argument.py (original) +++ pypy/dist/pypy/interpreter/argument.py Tue Jan 25 16:22:42 2005 @@ -121,6 +121,9 @@ try: return self.match_signature(signature, defaults_w) except ArgErr, e: + # XXX this hack is necessary because the annotator is + # dumb! -- mwh 2005-01-25 + assert isinstance(e, ArgErr) raise OperationError(space.w_TypeError, space.wrap(e.getmsg(self, fnname))) From ludal at codespeak.net Tue Jan 25 17:14:25 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 17:14:25 +0100 (MET) Subject: [pypy-svn] r8573 - pypy/dist/pypy/objspace/std Message-ID: <20050125161425.2202927B6E@code1.codespeak.net> Author: ludal Date: Tue Jan 25 17:14:24 2005 New Revision: 8573 Modified: pypy/dist/pypy/objspace/std/intobject.py Log: * fix small bug : hex(0) returned 0 instead of 0x0 Modified: pypy/dist/pypy/objspace/std/intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/intobject.py (original) +++ pypy/dist/pypy/objspace/std/intobject.py Tue Jan 25 17:14:24 2005 @@ -435,10 +435,7 @@ # "a signed string in Python 2.4 and up") < 0) # return NULL; pass - if x == 0: - ret = "0" - else: - ret = "0x%lx" % x + ret = "0x%lx" % x return space.wrap(ret) register_all(vars()) From arigo at codespeak.net Tue Jan 25 17:19:37 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 25 Jan 2005 17:19:37 +0100 (MET) Subject: [pypy-svn] r8574 - pypy/dist/pypy/objspace/std/test Message-ID: <20050125161937.C153227B6E@code1.codespeak.net> Author: arigo Date: Tue Jan 25 17:19:37 2005 New Revision: 8574 Modified: pypy/dist/pypy/objspace/std/test/test_stringformat.py Log: A test that failed before Ludovic's fix in intobject.py. Modified: pypy/dist/pypy/objspace/std/test/test_stringformat.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_stringformat.py (original) +++ pypy/dist/pypy/objspace/std/test/test_stringformat.py Tue Jan 25 17:19:37 2005 @@ -69,6 +69,7 @@ assert '23' == '%d' % 23 assert '17' == '%x' % 23 assert '0x17' == '%#x' % 23 + assert '0x0' == '%#x' % 0 assert '23' == '%s' % 23 assert '23' == '%r' % 23 From ac at codespeak.net Tue Jan 25 17:24:43 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 17:24:43 +0100 (MET) Subject: [pypy-svn] r8575 - pypy/dist/pypy/objspace/test Message-ID: <20050125162443.C966227B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 17:24:43 2005 New Revision: 8575 Modified: pypy/dist/pypy/objspace/test/test_descriptor.py Log: file does no longer have a property softspace that can be used for testing. Modified: pypy/dist/pypy/objspace/test/test_descriptor.py ============================================================================== --- pypy/dist/pypy/objspace/test/test_descriptor.py (original) +++ pypy/dist/pypy/objspace/test/test_descriptor.py Tue Jan 25 17:24:43 2005 @@ -1,5 +1,5 @@ import autopath - + class AppTest_Descriptor: def test_non_data_descr(self): @@ -14,15 +14,23 @@ assert x.f() == 42 def test_member(self): - import sys - assert sys.stdin.softspace == 0 - assert file.softspace.__get__(sys.stdin) == 0 - sys.stdin.softspace = 1 - assert sys.stdin.softspace == 1 - file.softspace.__set__(sys.stdin, 0) - assert sys.stdin.softspace == 0 - raises(TypeError, delattr, sys.stdin, 'softspace') - raises(TypeError, file.softspace.__delete__, sys.stdin) + class X(object): + def __init__(self): + self._v = 0 + def get_v(self): + return self._v + def set_v(self, v): + self._v = v + v = property(get_v, set_v) + x = X() + assert x.v == 0 + assert X.v.__get__(x) == 0 + x.v = 1 + assert x.v == 1 + X.v.__set__(x, 0) + assert x.v == 0 + raises(AttributeError delattr, x, 'v') + raises(AttributeError, X.v.__delete__, x) def test_special_methods_returning_strings(self): class A: From ac at codespeak.net Tue Jan 25 17:29:10 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 17:29:10 +0100 (MET) Subject: [pypy-svn] r8576 - pypy/dist/pypy/objspace/test Message-ID: <20050125162910.72A8F27B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 17:29:10 2005 New Revision: 8576 Modified: pypy/dist/pypy/objspace/test/test_descriptor.py Log: Oops! typo. Modified: pypy/dist/pypy/objspace/test/test_descriptor.py ============================================================================== --- pypy/dist/pypy/objspace/test/test_descriptor.py (original) +++ pypy/dist/pypy/objspace/test/test_descriptor.py Tue Jan 25 17:29:10 2005 @@ -29,7 +29,7 @@ assert x.v == 1 X.v.__set__(x, 0) assert x.v == 0 - raises(AttributeError delattr, x, 'v') + raises(AttributeError, delattr, x, 'v') raises(AttributeError, X.v.__delete__, x) def test_special_methods_returning_strings(self): From ac at codespeak.net Tue Jan 25 17:29:42 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 17:29:42 +0100 (MET) Subject: [pypy-svn] r8577 - in pypy/dist/pypy: appspace module Message-ID: <20050125162942.3AA4E27B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 17:29:42 2005 New Revision: 8577 Modified: pypy/dist/pypy/appspace/_file.py pypy/dist/pypy/appspace/sio.py pypy/dist/pypy/module/__builtin__module.py Log: Use the appspace _file.file as the __builtin__.file Modified: pypy/dist/pypy/appspace/_file.py ============================================================================== --- pypy/dist/pypy/appspace/_file.py (original) +++ pypy/dist/pypy/appspace/_file.py Tue Jan 25 17:29:42 2005 @@ -4,6 +4,8 @@ """An implementation of file objects in Python. it relies on Guido's sio.py implementation. """ + + def __init__(self, name, mode='r', bufsize=None): self.reading = False self.writing = False @@ -51,7 +53,6 @@ if bufsize > 2: "Read and write buffered stream." self.fd = sio.BufferingInputOutputStream(self.fd, bufsize) - return self.fd def __getattr__(self, attr): """ Modified: pypy/dist/pypy/appspace/sio.py ============================================================================== --- pypy/dist/pypy/appspace/sio.py (original) +++ pypy/dist/pypy/appspace/sio.py Tue Jan 25 17:29:42 2005 @@ -33,7 +33,6 @@ """ import os -import mmap class Stream(object): "All streams except the base ones need to inherit from this class." @@ -465,6 +464,7 @@ """Standard I/O basis stream using mmap.""" def __init__(self, filename, mode="r"): + import mmap self.filename = filename self.mode = mode if mode == "r": @@ -515,6 +515,7 @@ return self.read() def read(self, n=-1): + import mmap if n >= 0: aim = self.pos + n else: @@ -534,6 +535,7 @@ return self def readline(self): + import mmap hit = self.mm.find("\n", self.pos) + 1 if hit: data = self.mm[self.pos:hit] @@ -554,6 +556,7 @@ return data def next(self): + import mmap hit = self.mm.find("\n", self.pos) + 1 if hit: data = self.mm[self.pos:hit] Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Jan 25 17:29:42 2005 @@ -927,3 +927,6 @@ class buffer: def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" + +from _file import file_ as file +open = file From hpk at codespeak.net Tue Jan 25 17:43:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 25 Jan 2005 17:43:08 +0100 (MET) Subject: [pypy-svn] r8578 - in pypy/dist/pypy/objspace: . std test Message-ID: <20050125164308.39F3227B6E@code1.codespeak.net> Author: hpk Date: Tue Jan 25 17:43:08 2005 New Revision: 8578 Modified: pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/objecttype.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/test/test_descriptor.py Log: (Jacek and holger) - after some discussion with Samuele we decided that new style classes should be stricter with respect to __hash__ operations: in CPython only old-style classes would raise TypeError("unhashable object") on code like: class A: def __eq__(self, other): pass hash(A()) and that was specifically tested in test_class.py However, in PyPy which so far only has new style classes we didn't do this although it's probably a good idea. Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Jan 25 17:43:08 2005 @@ -228,6 +228,20 @@ if space.is_true(space.eq(w_next, w_item)): return space.w_True + def hash(space, w_obj): + w_hash = space.lookup(w_obj, '__hash__') + if w_hash is None: + if space.lookup(w_obj, '__eq__') is not None or \ + space.lookup(w_obj, '__cmp__') is not None: + raise OperationError(space.w_TypeError, + space.wrap("unhashable type")) + return space.id(w_obj) + w_result = space.get_and_call_function(w_hash, w_obj) + if space.is_true(space.isinstance(w_result, space.w_int)): + return w_result + else: + raise OperationError(space.w_TypeError, + space.wrap("__hash__() should return an int")) # xxx round, ord Modified: pypy/dist/pypy/objspace/std/objecttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/objecttype.py (original) +++ pypy/dist/pypy/objspace/std/objecttype.py Tue Jan 25 17:43:08 2005 @@ -14,11 +14,6 @@ def descr__str__(space, w_obj): return space.repr(w_obj) -def descr__hash__(space, w_obj): - # XXX detect non-hashable instances (the ones overriding comparison only) - # XXX ids could be long - return space.id(w_obj) - def descr__class__(space, w_obj): return space.type(w_obj) @@ -49,7 +44,6 @@ __delattr__ = gateway.interp2app(Object.descr__delattr__.im_func), __str__ = gateway.interp2app(descr__str__), __repr__ = gateway.interp2app(descr__repr__), - __hash__ = gateway.interp2app(descr__hash__), __class__ = GetSetProperty(descr__class__), __new__ = newmethod(descr__new__), __init__ = gateway.interp2app(descr__init__), Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Tue Jan 25 17:43:08 2005 @@ -364,21 +364,6 @@ else: return DescrOperation.is_true(self, w_obj) - def hash(space, w_obj): - w = space.wrap - eq = '__eq__' - ne = '__ne__' - hash_s = '__hash__' - - for w_t in space.type(w_obj).mro_w: - d = w_t.dict_w - if hash_s in d: - w_descr = d[hash_s] - return space.get_and_call_function(w_descr, w_obj) - if eq in d: - raise OperationError(space.w_TypeError, w("unhashable type")) - return space.id(w_obj) - # add all regular multimethods to StdObjSpace for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: if not hasattr(StdObjSpace.MM, _name): Modified: pypy/dist/pypy/objspace/test/test_descriptor.py ============================================================================== --- pypy/dist/pypy/objspace/test/test_descriptor.py (original) +++ pypy/dist/pypy/objspace/test/test_descriptor.py Tue Jan 25 17:43:08 2005 @@ -50,3 +50,26 @@ raises(TypeError, oct, inst) raises(TypeError, hex, inst) assert A.seen == [1,2,3,4] + +class TestDesciprtorOnStd: + objspacename = 'std' + def test_hash(self): + class A: + pass + hash(A()) + class B: + def __eq__(self, other): pass + raises(TypeError, hash, B()) + class C: + def __cmp__(self, other): pass + raises(TypeError, "hash(C())") + + class D: + def __hash__(self): + return 23L + raises(TypeError, hash, D()) + + class E: + def __hash__(self): + return "something" + raises(TypeError, hash, E()) From ac at codespeak.net Tue Jan 25 17:49:07 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 17:49:07 +0100 (MET) Subject: [pypy-svn] r8579 - pypy/dist/pypy/module Message-ID: <20050125164907.7C24127B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 17:49:07 2005 New Revision: 8579 Modified: pypy/dist/pypy/module/__builtin__module.py Log: the appspace _file.file can not currently replace __builtin__.file Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Jan 25 17:49:07 2005 @@ -928,5 +928,3 @@ def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" -from _file import file_ as file -open = file From ac at codespeak.net Tue Jan 25 17:59:55 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 25 Jan 2005 17:59:55 +0100 (MET) Subject: [pypy-svn] r8580 - pypy/dist/pypy/appspace Message-ID: <20050125165955.105D327B6E@code1.codespeak.net> Author: ac Date: Tue Jan 25 17:59:54 2005 New Revision: 8580 Modified: pypy/dist/pypy/appspace/_file.py Log: Fix _file.file_.close(). Modified: pypy/dist/pypy/appspace/_file.py ============================================================================== --- pypy/dist/pypy/appspace/_file.py (original) +++ pypy/dist/pypy/appspace/_file.py Tue Jan 25 17:59:54 2005 @@ -54,6 +54,13 @@ "Read and write buffered stream." self.fd = sio.BufferingInputOutputStream(self.fd, bufsize) + def close(self): + """ + Close the file + """ + self._closed = True + getattr(self.fd, 'close', lambda: None)() + def __getattr__(self, attr): """ Handle the readonly attributes and then delegate the other @@ -64,8 +71,6 @@ return self.__dict__[attr] elif attr in ['mode', 'name', 'closed', 'encoding']: return self.__dict__['_' + attr] - elif attr == 'close': - self._closed = True return getattr(self.fd, attr) From ludal at codespeak.net Tue Jan 25 18:09:17 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 18:09:17 +0100 (MET) Subject: [pypy-svn] r8581 - pypy/dist/pypy/appspace Message-ID: <20050125170917.A469F27B60@code1.codespeak.net> Author: ludal Date: Tue Jan 25 18:09:17 2005 New Revision: 8581 Modified: pypy/dist/pypy/appspace/_formatting.py Log: * fix small bugs preventing CPython's test_format.py to pass properly Modified: pypy/dist/pypy/appspace/_formatting.py ============================================================================== --- pypy/dist/pypy/appspace/_formatting.py (original) +++ pypy/dist/pypy/appspace/_formatting.py Tue Jan 25 18:09:17 2005 @@ -127,22 +127,22 @@ sign = '' return v, sign - def numeric_postprocess(self, r, sign): + def numeric_postprocess(self, r, sign,prefix=""): assert self.char in 'iduoxXeEfFgG' padchar = ' ' if self.flags.f_zero: padchar = '0' if self.width is not None: - p = self.width - len(r) - len(sign) + p = self.width - len(r) - len(sign) -len(prefix) if self.flags.f_ljust: - r = sign + r + ' '*p + r = sign + prefix + r + ' '*p else: if self.flags.f_zero: - r = sign+padchar*p + r + r = sign+prefix+padchar*p + r else: - r = padchar*p + sign + r + r = padchar*p + sign + prefix + r else: - r = sign + r + r = sign + prefix + r return r def format(self): @@ -175,7 +175,7 @@ try: inter = value.__int__ except AttributeError: - raise TypeError, "an integer argument is required" + raise TypeError, "int argument required" return inter() @@ -183,7 +183,7 @@ try: floater = value.__float__ except AttributeError: - raise TypeError, "a float argument is required" + raise TypeError, "float argument required" return floater() @@ -267,13 +267,19 @@ def format(self): v, sign = self.numeric_preprocess(maybe_int(self.value)) r = hex(v)[2:] + if r[-1]=="L": + # workaround weird behavior of CPython's hex + r = r[:-1].lower() if self.prec is not None and len(r) < self.prec: r = '0'*(self.prec - len(r)) + r if self.flags.f_alt: - r = '0x' + r + prefix = '0x' + else: + prefix = '' if self.char == 'X': r = r.upper() - return self.numeric_postprocess(r, sign) + prefix = prefix.upper() + return self.numeric_postprocess(r, sign, prefix) class OctFormatter(Formatter): @@ -281,7 +287,9 @@ def format(self): v, sign = self.numeric_preprocess(maybe_int(self.value)) r = oct(v) - if not self.flags.f_alt: + if r[-1] == "L": + r = r[:-1] + if v and not self.flags.f_alt: r = r[1:] if self.prec is not None and len(r) < self.prec: r = '0'*(self.prec - len(r)) + r @@ -376,8 +384,8 @@ f = format_registry[t[0]] except KeyError: raise ValueError("unsupported format character " - "'%s' (%x) at index %d" - %(t[0], ord(t[0]), fmtiter.i)) + "'%s' (0x%x) at index %d" + %(t[0], ord(t[0]), fmtiter.i-1)) # Trying to translate this using the flow space. # Currently, star args give a problem there, # so let's be explicit about the args: From ludal at codespeak.net Tue Jan 25 18:13:24 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 18:13:24 +0100 (MET) Subject: [pypy-svn] r8582 - pypy/dist/pypy/objspace/std Message-ID: <20050125171324.A5DAD27B60@code1.codespeak.net> Author: ludal Date: Tue Jan 25 18:13:24 2005 New Revision: 8582 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: * handle overflow in string multiplication * handle str.[rl]?strip(None) Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Tue Jan 25 18:13:24 2005 @@ -536,12 +536,8 @@ def _strip(space, w_self, w_chars, left, right): "internal function called by str_xstrip methods" u_self = w_self._value - assert isinstance(w_chars,W_StringObject) u_chars = w_chars._value - if u_self == None or u_chars == None: - return w_self - lpos = 0 rpos = len(u_self) @@ -551,23 +547,48 @@ lpos += 1 if right: - while rpos > 0 and u_self[rpos - 1] in u_chars: + while rpos > lpos and u_self[rpos - 1] in u_chars: rpos -= 1 return space.wrap(u_self[lpos:rpos]) +def _strip_none(space, w_self, left, right): + "internal function called by str_xstrip methods" + u_self = w_self._value + + lpos = 0 + rpos = len(u_self) + + if left: + #print "while %d < %d and -%s- in -%s-:"%(lpos, rpos, u_self[lpos],w_chars) + while lpos < rpos and u_self[lpos].isspace(): + lpos += 1 + + if right: + while rpos > lpos and u_self[rpos - 1].isspace(): + rpos -= 1 + + return space.wrap(u_self[lpos:rpos]) def str_strip__String_String(space, w_self, w_chars): return _strip(space, w_self, w_chars, left=1, right=1) +def str_strip__String_None(space, w_self, w_chars): + return _strip_none(space, w_self, left=1, right=1) def str_rstrip__String_String(space, w_self, w_chars): return _strip(space, w_self, w_chars, left=0, right=1) +def str_rstrip__String_None(space, w_self, w_chars): + return _strip_none(space, w_self, left=0, right=1) + def str_lstrip__String_String(space, w_self, w_chars): return _strip(space, w_self, w_chars, left=1, right=0) - + +def str_lstrip__String_None(space, w_self, w_chars): + return _strip_none(space, w_self, left=1, right=0) + def str_center__String_Int(space, w_self, w_arg): u_self = w_self._value @@ -890,8 +911,13 @@ def mul__String_Int(space, w_str, w_mul): input = w_str._value mul = space.int_w(w_mul) - - buffer = [' '] * (mul*len(input)) + if mul < 0: + return space.wrap("") + input_len = len(input) + try: + buffer = [' '] * (mul*input_len) + except (MemoryError,OverflowError): + raise OperationError( space.w_OverflowError, space.wrap("repeated string is too long: %d %d" % (input_len,mul) )) pos = 0 for i in range(mul): From ludal at codespeak.net Tue Jan 25 18:15:26 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 18:15:26 +0100 (MET) Subject: [pypy-svn] r8583 - pypy/dist/pypy/objspace/std Message-ID: <20050125171526.BBB0F27B60@code1.codespeak.net> Author: ludal Date: Tue Jan 25 18:15:26 2005 New Revision: 8583 Modified: pypy/dist/pypy/objspace/std/unicodeobject.py Log: * adds ne,le,ge,gt operators to faked unicode objects * adds str.strip(unicode) here to avoid references to unicode objects in stringobject.py Modified: pypy/dist/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/dist/pypy/objspace/std/unicodeobject.py Tue Jan 25 18:15:26 2005 @@ -17,12 +17,37 @@ except: wrap_exception(space) +def ne__Unicode_ANY(space, w_uni, w_other): + try: + return space.newbool(space.unwrap(w_uni) != space.unwrap(w_other)) + except: + wrap_exception(space) + + def lt__Unicode_ANY(space, w_uni, w_other): try: return space.newbool(space.unwrap(w_uni) < space.unwrap(w_other)) except: wrap_exception(space) +def gt__Unicode_ANY(space, w_uni, w_other): + try: + return space.newbool(space.unwrap(w_uni) > space.unwrap(w_other)) + except: + wrap_exception(space) + +def le__Unicode_ANY(space, w_uni, w_other): + try: + return space.newbool(space.unwrap(w_uni) <= space.unwrap(w_other)) + except: + wrap_exception(space) + +def ge__Unicode_ANY(space, w_uni, w_other): + try: + return space.newbool(space.unwrap(w_uni) >= space.unwrap(w_other)) + except: + wrap_exception(space) + def ord__Unicode(space, w_uni): try: return space.wrap(ord(w_uni.val)) @@ -38,4 +63,18 @@ def contains__Unicode_Unicode(space, w_left, w_right): return space.wrap(space.unwrap(w_right) in space.unwrap(w_left)) -register_all(vars()) +# str.strip(unicode) needs to convert self to unicode and call unicode.strip +def str_strip__String_Unicode(space, w_self, w_chars ): + self = w_self._value + return space.wrap( unicode(self).strip( space.unwrap(w_chars) ) ) +def str_lstrip__String_Unicode(space, w_self, w_chars ): + self = w_self._value + return space.wrap( unicode(self).lstrip( space.unwrap(w_chars) ) ) +def str_rstrip__String_Unicode(space, w_self, w_chars ): + self = w_self._value + return space.wrap( unicode(self).rstrip( space.unwrap(w_chars) ) ) +# we use the following magic to register strip_string_unicode as a String multimethod +import stringtype + + +register_all(vars(), stringtype) From ludal at codespeak.net Tue Jan 25 18:16:19 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Tue, 25 Jan 2005 18:16:19 +0100 (MET) Subject: [pypy-svn] r8584 - pypy/dist/pypy/objspace/std Message-ID: <20050125171619.2075327B60@code1.codespeak.net> Author: ludal Date: Tue Jan 25 18:16:18 2005 New Revision: 8584 Modified: pypy/dist/pypy/objspace/std/stringtype.py Log: * fix default parameters for strip, lstrip, rstrip Modified: pypy/dist/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringtype.py (original) +++ pypy/dist/pypy/objspace/std/stringtype.py Tue Jan 25 18:16:18 2005 @@ -25,9 +25,9 @@ str_rindex = MultiMethod('rindex', 4, defaults=(0, maxint)) str_replace = MultiMethod('replace', 4, defaults=(-1,)) str_zfill = MultiMethod('zfill', 2) -str_strip = MultiMethod('strip', 2, defaults=('', ' ')) -str_rstrip = MultiMethod('rstrip', 2, defaults=('', ' ')) -str_lstrip = MultiMethod('lstrip', 2, defaults=('', ' ')) +str_strip = MultiMethod('strip', 2, defaults=(None,)) +str_rstrip = MultiMethod('rstrip', 2, defaults=(None,)) +str_lstrip = MultiMethod('lstrip', 2, defaults=(None,)) str_center = MultiMethod('center', 2, ) str_count = MultiMethod('count', 4, defaults=(0, maxint)) str_endswith = MultiMethod('endswith', 2) #[optional arguments not supported now] From mwh at codespeak.net Tue Jan 25 18:50:59 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 25 Jan 2005 18:50:59 +0100 (MET) Subject: [pypy-svn] r8586 - pypy/dist/pypy/objspace/std Message-ID: <20050125175059.D1ECB27B5F@code1.codespeak.net> Author: mwh Date: Tue Jan 25 18:50:59 2005 New Revision: 8586 Modified: pypy/dist/pypy/objspace/std/stdtypedef.py Log: remove what looks a great deal like a no-longer-used obscure hack. Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Tue Jan 25 18:50:59 2005 @@ -121,12 +121,10 @@ code = result[name] if code.bound_position < i: continue - mmframeclass = multimethod.extras.get('mmframeclass') - if mmframeclass is None: - if len(multimethod.specialnames) > 1: - mmframeclass = SpecialMmFrame - else: - mmframeclass = MmFrame + if len(multimethod.specialnames) > 1: + mmframeclass = SpecialMmFrame + else: + mmframeclass = MmFrame code = MultimethodCode(multimethod, mmframeclass, typeclass, i) result[name] = code From tismer at codespeak.net Wed Jan 26 01:36:13 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Wed, 26 Jan 2005 01:36:13 +0100 (MET) Subject: [pypy-svn] r8588 - pypy/dist/pypy/appspace Message-ID: <20050126003613.EA82327B5F@code1.codespeak.net> Author: tismer Date: Wed Jan 26 01:36:13 2005 New Revision: 8588 Modified: pypy/dist/pypy/appspace/struct.py Log: irrelevant cosmetics Modified: pypy/dist/pypy/appspace/struct.py ============================================================================== --- pypy/dist/pypy/appspace/struct.py (original) +++ pypy/dist/pypy/appspace/struct.py Wed Jan 26 01:36:13 2005 @@ -342,5 +342,5 @@ if __name__ == '__main__': print pack_float(1.23,4,'little') import struct - print struct.pack('f',1.23), pack('f',1.23) + print (struct.pack('f',1.23), pack('f',1.23)) print unpack('f',pack('f',1.23)) From adim at codespeak.net Wed Jan 26 10:25:01 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Wed, 26 Jan 2005 10:25:01 +0100 (MET) Subject: [pypy-svn] r8590 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050126092501.18C3127B8A@code1.codespeak.net> Author: adim Date: Wed Jan 26 10:25:00 2005 New Revision: 8590 Modified: pypy/dist/pypy/objspace/std/sliceobject.py pypy/dist/pypy/objspace/std/test/test_sliceobject.py Log: added the slice.repr's implementation Modified: pypy/dist/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/sliceobject.py Wed Jan 26 10:25:00 2005 @@ -6,6 +6,7 @@ """ from pypy.objspace.std.objspace import * +from pypy.interpreter import gateway class W_SliceObject(W_Object): @@ -19,4 +20,9 @@ registerimplementation(W_SliceObject) +def app_repr__Slice(aslice): + return 'slice(%r, %r, %r)' % (aslice.start, aslice.stop, aslice.step) + +repr__Slice = gateway.app2interp(app_repr__Slice) + register_all(vars()) Modified: pypy/dist/pypy/objspace/std/test/test_sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_sliceobject.py Wed Jan 26 10:25:00 2005 @@ -49,3 +49,9 @@ assert slice(11,4,-2).indices(28) == (11, 4, -2) assert slice(11,4,-2).indices(8) == (7, 4, -2) assert slice(11,4,-2).indices(2) == (1, 2, -2) + + def test_repr(self): + assert repr(slice(1, 2, 3)) == 'slice(1, 2, 3)' + assert repr(slice(1, 2)) == 'slice(1, 2, None)' + assert repr(slice('a', 'b')) == "slice('a', 'b', None)" + From pedronis at codespeak.net Wed Jan 26 10:45:05 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 26 Jan 2005 10:45:05 +0100 (MET) Subject: [pypy-svn] r8591 - in pypy/dist/pypy: interpreter module Message-ID: <20050126094505.20ADD27B8A@code1.codespeak.net> Author: pedronis Date: Wed Jan 26 10:45:04 2005 New Revision: 8591 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/executioncontext.py pypy/dist/pypy/module/sysinterp.py Log: check for recursion limit Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Wed Jan 26 10:45:04 2005 @@ -34,6 +34,8 @@ def __init__(self): "NOT_RPYTHON: Basic initialization of objects." self._gatewaycache = Cache() + # set recursion limit + self.recursion_limit = 1000 # sets all the internal descriptors self.initialize() Modified: pypy/dist/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/dist/pypy/interpreter/executioncontext.py (original) +++ pypy/dist/pypy/interpreter/executioncontext.py Wed Jan 26 10:45:04 2005 @@ -10,6 +10,9 @@ self.framestack = Stack() def enter(self, frame): + if self.framestack.depth() > self.space.recursion_limit: + raise OperationError(self.space.w_RuntimeError, + self.space.wrap("maximum recursion depth exceeded")) locals = getthreadlocals() previous_ec = locals.executioncontext locals.executioncontext = self Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Wed Jan 26 10:45:04 2005 @@ -122,13 +122,6 @@ # directly from the C code in ceval.c, might be moved somewhere else. -# this variable is living here, but we -# access it this way, later: -# space.sys.recursion_limit = 1000 -# note that we cannot do it *here* because -# space.sys does not exist, yet. -recursion_limit = 1000 - def setrecursionlimit(w_new_limit): """setrecursionlimit(n) @@ -142,7 +135,7 @@ space.wrap("recursion limit must be positive")) # global recursion_limit # we need to do it without writing globals. - space.sys.recursion_limit = new_limit + space.recursion_limit = new_limit def getrecursionlimit(): """getrecursionlimit() @@ -151,7 +144,7 @@ of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.""" - return space.newint(recursion_limit) + return space.newint(space.recursion_limit) checkinterval = 100 From mwh at codespeak.net Wed Jan 26 10:54:58 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 10:54:58 +0100 (MET) Subject: [pypy-svn] r8592 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050126095458.9E8C127B45@code1.codespeak.net> Author: mwh Date: Wed Jan 26 10:54:58 2005 New Revision: 8592 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: union(SomeSlice, SomeSlice) builtin_slice (mainly so I could write the tests for the above) tests. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Wed Jan 26 10:54:58 2005 @@ -199,6 +199,14 @@ generalize(dic1.factories, obj2, s_value) +class __extend__(pairtype(SomeSlice, SomeSlice)): + + def union((slic1, slic2)): + return SomeSlice(unionof(slic1.start, slic2.start), + unionof(slic1.stop, slic2.stop), + unionof(slic1.step, slic2.step)) + + class __extend__(pairtype(SomeTuple, SomeInteger)): def getitem((tup1, int2)): Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Wed Jan 26 10:54:58 2005 @@ -4,7 +4,7 @@ import types from pypy.annotation.model import SomeInteger, SomeObject, SomeChar, SomeBool -from pypy.annotation.model import SomeList, SomeString, SomeTuple +from pypy.annotation.model import SomeList, SomeString, SomeTuple, SomeSlice from pypy.annotation.bookkeeper import getbookkeeper from pypy.annotation.factory import ListFactory from pypy.objspace.flow.model import Constant @@ -138,6 +138,21 @@ s.knowntype = types.CodeType return s +def builtin_slice(*args): + bk = getbookkeeper() + if len(args) == 1: + return SomeSlice( + bk.immutablevalue(None), args[0], bk.immutablevalue(None)) + elif len(args) == 2: + return SomeSlice( + args[0], args[1], bk.immutablevalue(None)) + elif len(args) == 3: + return SomeSlice( + args[0], args[1], args[2]) + else: + raise Exception, "bogus call to slice()" + + def exception_init(s_self, *args): s_self.setattr(immutablevalue('args'), SomeTuple(args)) Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Wed Jan 26 10:54:58 2005 @@ -694,3 +694,8 @@ d = {'a' : 1} return d.items() +def slice_union(x): + if x: + return slice(1) + else: + return slice(0, 10, 2) Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Wed Jan 26 10:54:58 2005 @@ -397,7 +397,6 @@ s = a.build_types(snippet.simple_slice, [list]) assert isinstance(s, annmodel.SomeList) - def test_simple_iter_list(self): a = RPythonAnnotator() s = a.build_types(snippet.simple_iter, [list]) @@ -463,6 +462,10 @@ assert isinstance(s_key, annmodel.SomeString) assert isinstance(s_value, annmodel.SomeInteger) + def test_slice_union(self): + a = RPythonAnnotator() + s = a.build_types(snippet.slice_union, [int]) + assert isinstance(s, annmodel.SomeSlice) def g(n): From ac at codespeak.net Wed Jan 26 11:11:33 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 26 Jan 2005 11:11:33 +0100 (MET) Subject: [pypy-svn] r8593 - in pypy/dist/pypy: appspace module Message-ID: <20050126101133.D8EC527B8A@code1.codespeak.net> Author: ac Date: Wed Jan 26 11:11:33 2005 New Revision: 8593 Modified: pypy/dist/pypy/appspace/_file.py pypy/dist/pypy/appspace/sio.py pypy/dist/pypy/module/__builtin__module.py Log: Start using appspace _file.file as __builtin__.file Modified: pypy/dist/pypy/appspace/_file.py ============================================================================== --- pypy/dist/pypy/appspace/_file.py (original) +++ pypy/dist/pypy/appspace/_file.py Wed Jan 26 11:11:33 2005 @@ -54,6 +54,20 @@ "Read and write buffered stream." self.fd = sio.BufferingInputOutputStream(self.fd, bufsize) + def __iter__(self): + """ + Return an iterator for the file. + """ + return self + + def next(self): + if self._closed: + raise StopIteration + line = self.fd.readline() + if line == '': + raise StopIteration + return line + def close(self): """ Close the file Modified: pypy/dist/pypy/appspace/sio.py ============================================================================== --- pypy/dist/pypy/appspace/sio.py (original) +++ pypy/dist/pypy/appspace/sio.py Wed Jan 26 11:11:33 2005 @@ -36,6 +36,7 @@ class Stream(object): "All streams except the base ones need to inherit from this class." + base = None def __getattr__(self, name): """ Delegate all other methods to the underlying file object. @@ -267,6 +268,7 @@ bufsize = 2**13 # 8 K def __init__(self, base, bufsize=None): + self.base = base self.do_write = base.write # Flush buffer self.do_tell = base.tell # Return a byte offset; has to exist or this __init__() will fail Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Jan 26 11:11:33 2005 @@ -928,3 +928,5 @@ def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" +from _file import file_ as file +open = file From mwh at codespeak.net Wed Jan 26 11:19:56 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 11:19:56 +0100 (MET) Subject: [pypy-svn] r8594 - pypy/dist/pypy/interpreter Message-ID: <20050126101956.28BC927B8A@code1.codespeak.net> Author: mwh Date: Wed Jan 26 11:19:55 2005 New Revision: 8594 Modified: pypy/dist/pypy/interpreter/gateway.py Log: Shorten the names of the auto-generated BuiltinFrame subclasses. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Wed Jan 26 11:19:55 2005 @@ -217,8 +217,9 @@ try: return cache[key] except KeyError: + name = '<'+ ', '.join([getattr(k, "__name__", k) for k in key]) + '>' emit_sig = apply_unwrap_spec(unwrap_spec, None, - BuiltinCodeSignature(name=repr(key)), + BuiltinCodeSignature(name=name), unwrap_spec_emit) cache[key] = cls = emit_sig.make_frame_class() From adim at codespeak.net Wed Jan 26 11:27:54 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Wed, 26 Jan 2005 11:27:54 +0100 (MET) Subject: [pypy-svn] r8595 - in pypy/dist/pypy: interpreter objspace/std objspace/std/test Message-ID: <20050126102754.A8C0427B8A@code1.codespeak.net> Author: adim Date: Wed Jan 26 11:27:54 2005 New Revision: 8595 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/objspace/std/sliceobject.py pypy/dist/pypy/objspace/std/test/test_sliceobject.py Log: added Slice.eq() operation and hash(Slice) which raises a TypeError added ObjSpace.is_w (shortcut for space.is_true(space.is_(w_obj1, wobj2))) added ObjSpace.eq_w (shortcut for space.is_true(space.eq(w_obj1, wobj2))) Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Wed Jan 26 11:27:54 2005 @@ -125,6 +125,14 @@ def not_(self, w_obj): return self.wrap(not self.is_true(w_obj)) + def eq_w(self, w_obj1, w_obj2): + """shortcut for space.is_true(space.eq(w_obj1, w_obj2))""" + return self.is_true(self.eq(w_obj1, w_obj2)) + + def is_w(self, w_obj1, w_obj2): + """shortcut for space.is_true(space.is_(w_obj1, w_obj2))""" + return self.is_true(self.is_(w_obj1, w_obj2)) + def newbool(self, b): if b: return self.w_True Modified: pypy/dist/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/sliceobject.py Wed Jan 26 11:27:54 2005 @@ -25,4 +25,22 @@ repr__Slice = gateway.app2interp(app_repr__Slice) +def eq__Slice_Slice(space, w_slice1, w_slice2): + # We need this because CPython considers that slice1 == slice1 + # is *always* True (e.g. even if slice1 was built with non-comparable + # parameters + if space.is_w(w_slice1, w_slice2): + return space.w_True + if space.eq_w(w_slice1.w_start, w_slice2.w_start) and \ + space.eq_w(w_slice1.w_stop, w_slice2.w_stop) and \ + space.eq_w(w_slice1.w_step, w_slice2.w_step): + return space.w_True + else: + return space.w_False + +def hash__Slice(space, w_slice): + """space are not hashables but they must have a __hash__ method""" + raise OperationError(space.w_TypeError, + space.wrap("unhashable type")) + register_all(vars()) Modified: pypy/dist/pypy/objspace/std/test/test_sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_sliceobject.py Wed Jan 26 11:27:54 2005 @@ -55,3 +55,9 @@ assert repr(slice(1, 2)) == 'slice(1, 2, None)' assert repr(slice('a', 'b')) == "slice('a', 'b', None)" + def test_eq(self): + slice1 = slice(1, 2, 3) + slice2 = slice(1, 2, 3) + assert slice1 == slice2 + slice2 = slice(1, 2) + assert slice1 != slice2 From mwh at codespeak.net Wed Jan 26 11:47:03 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 11:47:03 +0100 (MET) Subject: [pypy-svn] r8596 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050126104703.5E11527B88@code1.codespeak.net> Author: mwh Date: Wed Jan 26 11:47:03 2005 New Revision: 8596 Modified: pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/test/test_dictobject.py Log: Make the dictionary's dummy object a W_Root (an empty list to be precise) so avoid confusing the annotator. Fix the tests. Holger, I have another py.test bug to beat you with :) Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Wed Jan 26 11:47:03 2005 @@ -10,8 +10,6 @@ from pypy.objspace.std.restricted_int import r_uint -dummy = object() - class Entry: def __init__(self): self.hash = r_uint(0) @@ -29,6 +27,7 @@ w_self.used = 0 w_self.data = [] w_self.resize(len(list_pairs_w)*2) + w_self.w_dummy = space.newlist([]) for w_k, w_v in list_pairs_w: w_self.insert(w_self.hash(w_k), w_k, w_v) @@ -74,7 +73,7 @@ if entry.w_key is None or \ space.is_true(space.is_(w_lookup, entry.w_key)): return entry - if entry.w_key is dummy: + if entry.w_key is self.w_dummy: freeslot = entry else: if entry.hash == lookup_hash and space.is_true( @@ -91,11 +90,11 @@ return freeslot else: return entry - if entry.hash == lookup_hash and entry.w_key is not dummy \ + if entry.hash == lookup_hash and entry.w_key is not self.w_dummy \ and space.is_true( space.eq(entry.w_key, w_lookup)): return entry - if entry.w_key is dummy and freeslot is None: + if entry.w_key is self.w_dummy and freeslot is None: freeslot = entry perturb >>= 5 @@ -150,7 +149,7 @@ entry = w_dict.lookdict(w_dict.hash(w_lookup), w_lookup) if entry.w_value is not None: w_dict.used -= 1 - entry.w_key = dummy + entry.w_key = w_dict.w_dummy entry.w_value = None else: raise OperationError(space.w_KeyError, w_lookup) Modified: pypy/dist/pypy/objspace/std/test/test_dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_dictobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_dictobject.py Wed Jan 26 11:47:03 2005 @@ -308,6 +308,8 @@ return x is y def eq(self, x, y): return x == y + def newlist(self, l): + return [] from pypy.objspace.std.dictobject import getitem__Dict_ANY, setitem__Dict_ANY_ANY From mwh at codespeak.net Wed Jan 26 12:02:06 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 12:02:06 +0100 (MET) Subject: [pypy-svn] r8597 - pypy/dist/pypy/interpreter Message-ID: <20050126110206.CFC2B27B8E@code1.codespeak.net> Author: mwh Date: Wed Jan 26 12:02:06 2005 New Revision: 8597 Modified: pypy/dist/pypy/interpreter/executioncontext.py Log: Add missing import (detected by translate_pypy, ho hum). Modified: pypy/dist/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/dist/pypy/interpreter/executioncontext.py (original) +++ pypy/dist/pypy/interpreter/executioncontext.py Wed Jan 26 12:02:06 2005 @@ -1,4 +1,5 @@ from pypy.interpreter.miscutils import getthreadlocals, Stack +from pypy.interpreter.error import OperationError class ExecutionContext: """An ExecutionContext holds the state of an execution thread From ludal at codespeak.net Wed Jan 26 12:41:30 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Wed, 26 Jan 2005 12:41:30 +0100 (MET) Subject: [pypy-svn] r8598 - pypy/dist/pypy/interpreter Message-ID: <20050126114130.E509F27B8D@code1.codespeak.net> Author: ludal Date: Wed Jan 26 12:41:30 2005 New Revision: 8598 Modified: pypy/dist/pypy/interpreter/function.py pypy/dist/pypy/interpreter/typedef.py Log: * added __module__ attribute to function objects * functions' __dict__ attribute only accepts dict instances * modules' __dict__ attribute is readonly Modified: pypy/dist/pypy/interpreter/function.py ============================================================================== --- pypy/dist/pypy/interpreter/function.py (original) +++ pypy/dist/pypy/interpreter/function.py Wed Jan 26 12:41:30 2005 @@ -24,6 +24,7 @@ self.closure = closure # normally, list of Cell instances or None self.defs_w = defs_w # list of w_default's self.w_func_dict = space.newdict([]) + self.w_module = None def __repr__(self): # return "function %s.%s" % (self.space, self.name) @@ -41,6 +42,9 @@ return self.w_func_dict def setdict(self, w_dict): + space = self.space + if not space.is_true(space.isinstance( w_dict, space.w_dict )): + raise OperationError( space.w_TypeError, space.wrap("setting function's dictionary to a non-dict") ) self.w_func_dict = w_dict def descr_function_get(self, w_obj, w_cls=None): @@ -80,6 +84,23 @@ self = space.interpclass_w(w_self) self.w_doc = space.w_None + def fget___module__(space, w_self): + self = space.interpclass_w(w_self) + if self.w_module is None: + if self.w_func_globals is not None and not space.is_w(self.w_func_globals, space.w_None): + self.w_module = space.call_method( self.w_func_globals, "get", space.wrap("__name__") ) + else: + self.w_module = space.w_None + return self.w_module + + def fset___module__(space, w_self, w_module ): + self = space.interpclass_w(w_self) + self.w_module = space.w_module + + def fdel___module__(space, w_self, w_module ): + self = space.interpclass_w(w_self) + self.w_module = space.w_None + class Method(Wrappable): """A method is a function bound to a specific instance or class.""" Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Wed Jan 26 12:41:30 2005 @@ -218,7 +218,7 @@ Module.typedef = TypeDef("module", __new__ = interp2app(Module.descr_module__new__.im_func), __init__ = interp2app(Module.descr_module__init__.im_func), - __dict__ = interp_dict_descr, + __dict__ = GetSetProperty(descr_get_dict), # module dictionaries are readonly attributes __getattr__ = interp2app(Module.descr_module__getattr__.im_func), ) @@ -226,6 +226,15 @@ Function.fset_func_doc, Function.fdel_func_doc) +# __module__ attribute lazily gets its value from the w_globals +# at the time of first invocation. This is not 100% compatible but +# avoid problems at the time we construct the first functions when +# it's not really possible to do a get or getitem on dictionaries +# (mostly because wrapped exceptions don't exist at that time) +getset___module__ = GetSetProperty(Function.fget___module__, + Function.fset___module__, + Function.fdel___module__) + Function.typedef = TypeDef("function", __call__ = interp2app(Function.descr_function_call.im_func), __get__ = interp2app(Function.descr_function_get.im_func), @@ -237,7 +246,8 @@ func_globals = interp_attrproperty_w('w_func_globals'), __doc__ = getset_func_doc, __name__ = interp_attrproperty('name'), - __dict__ = interp_dict_descr, + __dict__ = GetSetProperty(descr_get_dict, descr_set_dict), + __module__ = getset___module__, # XXX func_closure, etc.pp ) From ac at codespeak.net Wed Jan 26 12:48:17 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 26 Jan 2005 12:48:17 +0100 (MET) Subject: [pypy-svn] r8599 - pypy/dist/pypy/module Message-ID: <20050126114817.18FF127B8A@code1.codespeak.net> Author: ac Date: Wed Jan 26 12:48:16 2005 New Revision: 8599 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Make __builtin__.map support any iterable and not only lists/tuples. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Jan 26 12:48:16 2005 @@ -94,33 +94,31 @@ if len(collections) == 0: raise TypeError, "map() requires at least one sequence" - elif len(collections) == 1: + if len(collections) == 1: #it's the most common case, so make it faster if function is None: return list(collections[0]) + return [function(x) for x in collections[0]] + + iterators = [ iter(collection) for collection in collections ] + res = [] + while 1: + cont = False #is any collection not empty? + args = [] + for iterator in iterators: + try: + elem = iterator.next() + cont = True + except StopIteration: + elem = None + args.append(elem) + if cont: + if function is None: + res.append(tuple(args)) + else: + res.append(function(*args)) else: - return [function(x) for x in collections[0]] - else: - res = [] - idx = 0 - while 1: - cont = 0 #is any collection not empty? - args = [] - for collection in collections: - try: - elem = collection[idx] - cont = cont + 1 - except IndexError: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - idx = idx + 1 + return res def filter(function, collection): """construct a list of those elements of collection for which function From ac at codespeak.net Wed Jan 26 13:01:57 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 26 Jan 2005 13:01:57 +0100 (MET) Subject: [pypy-svn] r8600 - pypy/dist/pypy/module Message-ID: <20050126120157.32E3327B84@code1.codespeak.net> Author: ac Date: Wed Jan 26 13:01:57 2005 New Revision: 8600 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Make __builtin__.zip support any iterables as arguments. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Jan 26 13:01:57 2005 @@ -144,19 +144,17 @@ ignoring the trailing items in the other collections.""" if len(collections) == 0: - raise TypeError, "zip() requires at least one sequence" + return [] res = [] - idx = 0 + iterators = [ iter(collection) for collection in collections ] while 1: try: elems = [] - for collection in collections: - elems.append(collection[idx]) + for iterator in iterators: + elems.append(iterator.next()) res.append(tuple(elems)) - except IndexError: - break - idx = idx + 1 - return res + except StopIteration: + return res def reduce(function, l, *initialt): """ Apply function of two arguments cumulatively to the items of From ac at codespeak.net Wed Jan 26 13:16:04 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 26 Jan 2005 13:16:04 +0100 (MET) Subject: [pypy-svn] r8603 - pypy/dist/pypy/module Message-ID: <20050126121604.CD37C27B84@code1.codespeak.net> Author: ac Date: Wed Jan 26 13:16:04 2005 New Revision: 8603 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Make __builtin__.reduce support any iterable as argument. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Jan 26 13:16:04 2005 @@ -156,26 +156,26 @@ except StopIteration: return res -def reduce(function, l, *initialt): +def reduce(function, seq, *initialt): """ Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Optionally begin with an initial value.""" + seqiter = iter(seq) if initialt: initial, = initialt - idx = 0 else: try: - initial = l[0] - except IndexError: + initial = seqiter.next() + except StopIteration: raise TypeError, "reduce() of empty sequence with no initial value" - idx = 1 while 1: - try: - initial = function(initial, l[idx]) - idx = idx + 1 - except IndexError: - break + try: + arg = seqiter.next() + except StopIteration: + break + initial = function(initial, arg) + return initial def issubclass(cls, klass_or_tuple): From adim at codespeak.net Wed Jan 26 13:24:11 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Wed, 26 Jan 2005 13:24:11 +0100 (MET) Subject: [pypy-svn] r8604 - in pypy/dist/pypy: module module/test objspace/std Message-ID: <20050126122411.BFC5727B84@code1.codespeak.net> Author: adim Date: Wed Jan 26 13:24:11 2005 New Revision: 8604 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py pypy/dist/pypy/objspace/std/listtype.py Log: added sorted and reversed builtins (+ tests) also added list.__reversed__ definition / implementation in listtype.py (assuming that, for now, we don't want to have several possible implementation of list.__reversed__) Side Note : reversed() is implemented as a builtin function, not as a type like in Python2.4 Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Jan 26 13:24:11 2005 @@ -924,5 +924,25 @@ def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" +def sorted(lst): + "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" + sorted_lst = list(lst) + sorted_lst.sort() + return sorted_lst + +def reversed(iterable): + """reversed(sequence) -> reverse iterator over values of the sequence + + Return a reverse iterator + """ + if hasattr(iterable, '__reversed__'): + return iterable.__reversed__() + seq = list(iterable) + def reversed_gen(local_iterable): + len_iterable = len(local_iterable) + for index in range(len_iterable-1, -1, -1): + yield local_iterable[index] + return reversed_gen(seq) + from _file import file_ as file open = file Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Wed Jan 26 13:24:11 2005 @@ -180,6 +180,32 @@ raises(IndexError, x.__getitem__, -18) raises(TypeError, x.__getitem__, slice(0,3,1)) + def test_sorted(self): + l = [] + sorted_l = sorted(l) + assert sorted_l is not l + assert sorted_l == l + l = [1, 5, 2, 3] + sorted_l = sorted(l) + assert sorted_l == [1, 2, 3, 5] + + def test_reversed_simple_sequences(self): + l = range(5) + rev = reversed(l) + assert list(rev) == [4, 3, 2, 1, 0] + assert list(l.__reversed__()) == [4, 3, 2, 1, 0] + s = "abcd" + assert list(reversed(s)) == ['d', 'c', 'b', 'a'] + + def test_reversed_custom_objects(self): + """make sure __reversed__ is called when defined""" + class SomeClass: + def __reversed__(self): + return 42 + obj = SomeClass() + assert reversed(obj) == 42 + + def test_cmp(self): assert cmp(9,9) == 0 assert cmp(0,9) < 0 Modified: pypy/dist/pypy/objspace/std/listtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/listtype.py (original) +++ pypy/dist/pypy/objspace/std/listtype.py Wed Jan 26 13:24:11 2005 @@ -1,15 +1,28 @@ from pypy.objspace.std.stdtypedef import * +from pypy.objspace.std.register_all import register_all from sys import maxint -list_append = MultiMethod('append', 2) -list_insert = MultiMethod('insert', 3) -list_extend = MultiMethod('extend', 2) -list_pop = MultiMethod('pop', 2, defaults=(-1,)) -list_remove = MultiMethod('remove', 2) -list_index = MultiMethod('index', 4, defaults=(0,maxint)) -list_count = MultiMethod('count', 2) -list_reverse= MultiMethod('reverse',1) -list_sort = MultiMethod('sort', 2, defaults=(None,)) +list_append = MultiMethod('append', 2) +list_insert = MultiMethod('insert', 3) +list_extend = MultiMethod('extend', 2) +list_pop = MultiMethod('pop', 2, defaults=(-1,)) +list_remove = MultiMethod('remove', 2) +list_index = MultiMethod('index', 4, defaults=(0,maxint)) +list_count = MultiMethod('count', 2) +list_reverse = MultiMethod('reverse',1) +list_sort = MultiMethod('sort', 2, defaults=(None,)) +list_reversed = MultiMethod('__reversed__', 1) + +def app_list_reversed__ANY(lst): + def reversed_gen(local_iterable): + len_iterable = len(local_iterable) + for index in range(len_iterable-1, -1, -1): + yield local_iterable[index] + return reversed_gen(lst) + +# gateway is imported in the stdtypedef module +gateway.importall(globals()) +register_all(vars(), globals()) # ____________________________________________________________ From hpk at codespeak.net Wed Jan 26 13:28:34 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 26 Jan 2005 13:28:34 +0100 (MET) Subject: [pypy-svn] r8605 - pypy/dist/pypy Message-ID: <20050126122834.7F09627B84@code1.codespeak.net> Author: hpk Date: Wed Jan 26 13:28:34 2005 New Revision: 8605 Modified: pypy/dist/pypy/conftest.py Log: for interp-level tests we should not pass back an app-level exception info (and traceback). Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Wed Jan 26 13:28:34 2005 @@ -111,10 +111,14 @@ if 'space' in co.co_varnames[:co.co_argcount]: name = target.func_globals.get('objspacename', None) space = gettestobjspace(name) - self.execute_appex(space, target, space, *args) + target(space, *args) else: target(*args) +class IntTestMethod(PyPyItem): + def execute(self, target, *args): + target(*args) + class AppTestFunction(PyPyItem): def execute(self, target, *args): assert not args @@ -123,10 +127,6 @@ func = app2interp_temp(target, target.__name__) self.execute_appex(space, func, space) -class IntTestMethod(PyPyItem): - def execute(self, target, *args): - space = target.im_self.space - self.execute_appex(space, target, *args) class AppTestMethod(PyPyItem): def execute(self, target, *args): From hpk at codespeak.net Wed Jan 26 13:38:18 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 26 Jan 2005 13:38:18 +0100 (MET) Subject: [pypy-svn] r8606 - pypy/dist/pypy/documentation Message-ID: <20050126123818.6D0B727B84@code1.codespeak.net> Author: hpk Date: Wed Jan 26 13:38:18 2005 New Revision: 8606 Modified: pypy/dist/pypy/documentation/newrepolayout.txt Log: improved version of the repolayout. this is a result of a discussion between Bea and Holger reflecting various aspects of the PyPy project both regarding development, EU-information and various dissemeniation aspects as well as internal tracking aspects relating to audits and internal controling. Modified: pypy/dist/pypy/documentation/newrepolayout.txt ============================================================================== --- pypy/dist/pypy/documentation/newrepolayout.txt (original) +++ pypy/dist/pypy/documentation/newrepolayout.txt Wed Jan 26 13:38:18 2005 @@ -5,27 +5,24 @@ Motivation ---------- -The `PyPy repository layout`_ has evolved for two -years into something that needs some refactoring -to become more practical. - -For example, the `extradoc`_ directory was originally intended -to hold developer documentation but nowadays it contains -funding, negotiations, mails and misc-other-stuff documents. It is -not easy and obvious anymore to know which files are relevant. -Moreover, `extradoc`_ is too far away from the source code: -developers currently checkout the 'dist' directory and -don't even get the documentation. This also makes it more -difficult to keep the documentation up-to-date. +We want to move to the following structure: + +- `dist`_: source code + documentation (for developer needs) + +- `extradoc`_: talks, papers, newsletters and EU-related information + that are useful for not-only-developers + +- `eu-tracking`_: eu-tracking details that involve internal + budget/cost/audit preparations and documentations (not + available to anonymous checkouts) .. _`extradoc`: http://codespeak.net/svn/pypy/extradoc -.. _`PyPy repository layout`: http://codespeak.net/svn/pypy/ +.. _`dist`: http://codespeak.net/svn/pypy/dist +.. _`eu-tracking`: http://codespeak.net/svn/pypy/eu-tracking -New repo layout proposal Nr. 1 ------------------------------- +More detailed layout (work in progress) +--------------------------------------- -Based on experiences in various repositories here is a -new proposition describing a possible new structure (starting at /svn/pypy):: branch # holds branches @@ -44,23 +41,32 @@ paper # various pypy-related papers (including our own) sprint # sprint related information (reports etc.pp.) irclog # IRC logs (snipped appropriately) - + eu-info # legal guidelines/rules partcipation + eu-forms # Accession forms (empty) + proposal # several versions + newsletter # ... + press # ... + + eu-tracking # strong focus on eu-internal details + timesheets # monthly timesheets + monthly-reports + deliverables # deliverable/documents + minutes # meeting protocols + budget.sxc + calendar.sxc + ... www # website-related stuff (needs its own reconsideration) - funding # funding related documents - eu-info # official information from the EU - contract # contract material (EU-contract, amendments) - eu-report # eu reports (time/cost/budget) - ... # probably more, we'll see later The idea is that developers can use a simple url:: svn co https://codespeak.net/svn/pypy/dist dist-pypy in order to get everything neccessary for sourcecode, documentation -and test development. Obviously, if you care about the funding +and test development. Obviously, if you care about the EU-funding or web site application/contents you can do an appropriate checkout -as well. +as well. The extradoc contains information interesting to +developers and other open source projects (seeking funding or not). Note, that having documentation inside the source tree will help with keeping a closer eye on documentation - especially when we From ludal at codespeak.net Wed Jan 26 15:02:15 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Wed, 26 Jan 2005 15:02:15 +0100 (MET) Subject: [pypy-svn] r8607 - pypy/dist/pypy/interpreter Message-ID: <20050126140215.B8EF627B88@code1.codespeak.net> Author: ludal Date: Wed Jan 26 15:02:15 2005 New Revision: 8607 Modified: pypy/dist/pypy/interpreter/function.py pypy/dist/pypy/interpreter/typedef.py Log: * fixed function attributes handling to pass test_funcattrs.py Modified: pypy/dist/pypy/interpreter/function.py ============================================================================== --- pypy/dist/pypy/interpreter/function.py (original) +++ pypy/dist/pypy/interpreter/function.py Wed Jan 26 15:02:15 2005 @@ -9,6 +9,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.argument import Arguments +from pypy.interpreter.eval import Code class Function(Wrappable): """A function is a code object captured with some environment: @@ -69,6 +70,16 @@ if not values_w: return space.w_None return space.newtuple(values_w) + + def fset_func_defaults(space, w_self, w_defaults): + self = space.interpclass_w(w_self) + if not space.is_true( space.isinstance( w_defaults, space.w_tuple ) ): + raise OperationError( space.w_TypeError, space.wrap("func_defaults must be set to a tuple object") ) + self.defs_w = space.unpackiterable( w_defaults ) + + def fdel_func_defaults(space, w_self): + self = space.interpclass_w(w_self) + self.defs_w = [] def fget_func_doc(space, w_self): self = space.interpclass_w(w_self) @@ -101,6 +112,23 @@ self = space.interpclass_w(w_self) self.w_module = space.w_None + def fget_func_code(space, w_self): + self = space.interpclass_w(w_self) + return space.wrap(self.code) + + def fset_func_code(space, w_self, w_code): + self = space.interpclass_w(w_self) + code = space.interpclass_w(w_code) + if not isinstance(code, Code ): + raise OperationError( space.w_TypeError, space.wrap("func_code must be set to a code object") ) + self.code = code + + def fget_func_closure(space, w_self): + self = space.interpclass_w(w_self) + w_res = space.newtuple( [ space.wrap(i) for i in self.closure ] ) + return w_res + + class Method(Wrappable): """A method is a function bound to a specific instance or class.""" @@ -110,6 +138,13 @@ self.w_instance = w_instance # or None self.w_class = w_class + def descr_method__new__(space, w_subtype, w_function, w_instance, w_class): + method = space.allocate_instance(Method, w_subtype) + if space.is_w( w_instance, space.w_None ): + w_instance = None + method.__init__(space, w_function, w_instance, w_class) + return space.wrap(method) + def __repr__(self): if self.w_instance: pre = "bound" Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Wed Jan 26 15:02:15 2005 @@ -232,26 +232,36 @@ # it's not really possible to do a get or getitem on dictionaries # (mostly because wrapped exceptions don't exist at that time) getset___module__ = GetSetProperty(Function.fget___module__, - Function.fset___module__, - Function.fdel___module__) + Function.fset___module__, + Function.fdel___module__) + +getset_func_defaults = GetSetProperty(Function.fget_func_defaults, + Function.fset_func_defaults, + Function.fdel_func_defaults) +getset_func_code = GetSetProperty(Function.fget_func_code, + Function.fset_func_code) + +getset_func_dict = GetSetProperty(descr_get_dict, descr_set_dict) Function.typedef = TypeDef("function", __call__ = interp2app(Function.descr_function_call.im_func), __get__ = interp2app(Function.descr_function_get.im_func), - func_code = interp_attrproperty('code'), + func_code = getset_func_code, func_doc = getset_func_doc, func_name = interp_attrproperty('name'), - func_dict = interp_attrproperty_w('w_func_dict'), - func_defaults = GetSetProperty(Function.fget_func_defaults), + func_dict = getset_func_dict, + func_defaults = getset_func_defaults, func_globals = interp_attrproperty_w('w_func_globals'), + func_closure = GetSetProperty( Function.fget_func_closure ), __doc__ = getset_func_doc, __name__ = interp_attrproperty('name'), - __dict__ = GetSetProperty(descr_get_dict, descr_set_dict), + __dict__ = getset_func_dict, __module__ = getset___module__, # XXX func_closure, etc.pp ) Method.typedef = TypeDef("method", + __new__ = interp2app(Method.descr_method__new__.im_func), __call__ = interp2app(Method.descr_method_call.im_func), __get__ = interp2app(Method.descr_method_get.im_func), im_func = interp_attrproperty_w('w_function'), @@ -280,7 +290,7 @@ gi_frame = interp_attrproperty('frame'), ) -Cell.typedef = TypeDef("Cell") +Cell.typedef = TypeDef("cell") Ellipsis.typedef = TypeDef("Ellipsis", __repr__ = interp2app(Ellipsis.descr__repr__.im_func), From pedronis at codespeak.net Wed Jan 26 15:12:34 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 26 Jan 2005 15:12:34 +0100 (MET) Subject: [pypy-svn] r8608 - in pypy/dist/pypy: annotation translator translator/test Message-ID: <20050126141234.1F2C827B88@code1.codespeak.net> Author: pedronis Date: Wed Jan 26 15:12:33 2005 New Revision: 8608 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: Teach the annotator how to deduce the type of e in try: ... except SomeException, e: ... <-- here This involved changing the way the special last_exception and last_exc_value Constants are transferred across Links (which was already horrible :), slightly extending the SomeBool.knowntypedata hack, implementing issubtype(SomeObject,SomePBC) and tweaking is_. Test. -This line, and those below, will be ignored-- M translator/test/test_annrpython.py M translator/test/snippet.py M translator/annrpython.py M annotation/builtin.py M annotation/binaryop.py Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Wed Jan 26 15:12:33 2005 @@ -97,13 +97,17 @@ # XXX HACK HACK HACK # XXX HACK HACK HACK # XXX HACK HACK HACK - fn, block, i = getbookkeeper().position_key - annotator = getbookkeeper().annotator + bk = getbookkeeper() + if hasattr(obj1,'is_type_of') and obj2.is_constant(): + r.knowntypedata = (obj1.is_type_of, bk.valueoftype(obj2.const)) + return r + fn, block, i = bk.position_key + annotator = bk.annotator op = block.operations[i] assert op.opname == "is_" assert len(op.args) == 2 assert annotator.binding(op.args[0]) == obj1 - r.knowntypedata = (op.args[0], obj2) + r.knowntypedata = ([op.args[0]], obj2) return r class __extend__(pairtype(SomeInteger, SomeInteger)): @@ -311,3 +315,12 @@ class __extend__(pairtype(SomePBC, SomeInstance)): def union((pbc, ins)): return pair(ins, pbc).union() + +class __extend__(pairtype(SomeObject, SomePBC)): + def issubtype((obj, pbc)): + s = SomeBool() + if hasattr(obj,'is_type_of') and pbc.is_constant(): + bk = getbookkeeper() + s.knowntypedata = (obj.is_type_of, bk.valueoftype(pbc.const)) + return s + Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Wed Jan 26 15:12:33 2005 @@ -74,7 +74,7 @@ assert len(op.args) == 3 assert op.args[0] == Constant(isinstance) assert annotator.binding(op.args[1]) == s_obj - s.knowntypedata = (op.args[1], bk.valueoftype(typ)) + s.knowntypedata = ([op.args[1]], bk.valueoftype(typ)) return s def builtin_issubclass(s_cls1, s_cls2): Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Wed Jan 26 15:12:33 2005 @@ -142,18 +142,14 @@ print "++-" * 20 - def binding(self, arg, in_link=None): + def binding(self, arg): "Gives the SomeValue corresponding to the given Variable or Constant." if isinstance(arg, Variable): return self.bindings[arg] elif isinstance(arg, UndefinedConstant): # undefined local variables return annmodel.SomeImpossibleValue() elif isinstance(arg, Constant): - if arg.value is last_exception or arg.value is last_exc_value: - assert in_link - assert isinstance(in_link.exitcase, type(Exception)) - assert issubclass(in_link.exitcase, Exception) - return annmodel.SomeObject() # XXX + assert not arg.value is last_exception and not arg.value is last_exc_value return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError, 'Variable or Constant expected, got %r' % (arg,) @@ -311,17 +307,41 @@ if s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase == s_exitswitch.const] - knownvar, knownvarvalue = getattr(self.bindings.get(block.exitswitch), + knownvars, knownvarvalue = getattr(self.bindings.get(block.exitswitch), "knowntypedata", (None, None)) for link in exits: self.links_followed[link] = True - cells = [] - for a in link.args: - cell = self.binding(a, in_link=link) - if link.exitcase is True and a is knownvar \ - and not knownvarvalue.contains(cell): - cell = knownvarvalue - cells.append(cell) + import types + if isinstance(link.exitcase, types.ClassType) and issubclass(link.exitcase, Exception): + last_exception_object = annmodel.SomeObject() + last_exc_value_object = annmodel.SomeObject() + last_exc_value_vars = last_exception_object.is_type_of = [] + cells = [] + for a,v in zip(link.args,link.target.inputargs): + if a == Constant(last_exception): + cells.append(last_exception_object) + elif a == Constant(last_exc_value): + cells.append(last_exc_value_object) + last_exc_value_vars.append(v) + else: + assert False, "exception handling blocks should only have exception inputargs!!" + else: + cells = [] + renaming = dict(zip(link.args,link.target.inputargs)) + for a in link.args: + cell = self.binding(a) + if link.exitcase is True and knownvars is not None and a in knownvars \ + and not knownvarvalue.contains(cell): + cell = knownvarvalue + if hasattr(cell,'is_type_of'): + renamed_is_type_of = [] + for v in cell.is_type_of: + new_v = renaming.get(v,None) + if new_v is not None: + renamed_is_type_of.append(new_v) + cell = annmodel.SomeObject() + cell.is_type_of = renamed_is_type_of + cells.append(cell) self.addpendingblock(fn, link.target, cells) if block in self.notify: # reflow from certain positions when this block is done Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Wed Jan 26 15:12:33 2005 @@ -694,6 +694,19 @@ d = {'a' : 1} return d.items() +class Exc(Exception): + pass + +def exception_deduction0(x): + pass + +def exception_deduction(): + try: + exception_deduction0(2) + except Exc, e: + return e + return Exc() + def slice_union(x): if x: return slice(1) Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Wed Jan 26 15:12:33 2005 @@ -461,6 +461,12 @@ s_key, s_value = s.s_item.items assert isinstance(s_key, annmodel.SomeString) assert isinstance(s_value, annmodel.SomeInteger) + + def test_exception_deduction(self): + a = RPythonAnnotator() + s = a.build_types(snippet.exception_deduction, []) + assert isinstance(s, annmodel.SomeInstance) + assert s.knowntype is snippet.Exc def test_slice_union(self): a = RPythonAnnotator() From mwh at codespeak.net Wed Jan 26 15:27:35 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 15:27:35 +0100 (MET) Subject: [pypy-svn] r8609 - in pypy/dist/pypy/translator: . test Message-ID: <20050126142735.155EA27B88@code1.codespeak.net> Author: mwh Date: Wed Jan 26 15:27:34 2005 New Revision: 8609 Modified: pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: OK, we made a daft assumption in the last checkin. More tests. Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Wed Jan 26 15:27:34 2005 @@ -312,23 +312,25 @@ for link in exits: self.links_followed[link] = True import types - if isinstance(link.exitcase, types.ClassType) and issubclass(link.exitcase, Exception): + in_except_block = False + if isinstance(link.exitcase, types.ClassType) \ + and issubclass(link.exitcase, Exception): last_exception_object = annmodel.SomeObject() last_exc_value_object = annmodel.SomeObject() last_exc_value_vars = last_exception_object.is_type_of = [] - cells = [] - for a,v in zip(link.args,link.target.inputargs): - if a == Constant(last_exception): - cells.append(last_exception_object) - elif a == Constant(last_exc_value): - cells.append(last_exc_value_object) - last_exc_value_vars.append(v) - else: - assert False, "exception handling blocks should only have exception inputargs!!" - else: - cells = [] - renaming = dict(zip(link.args,link.target.inputargs)) - for a in link.args: + in_except_block = True + + cells = [] + renaming = dict(zip(link.args,link.target.inputargs)) + for a,v in zip(link.args,link.target.inputargs): + if a == Constant(last_exception): + assert in_except_block + cells.append(last_exception_object) + elif a == Constant(last_exc_value): + assert in_except_block + cells.append(last_exc_value_object) + last_exc_value_vars.append(v) + else: cell = self.binding(a) if link.exitcase is True and knownvars is not None and a in knownvars \ and not knownvarvalue.contains(cell): @@ -342,6 +344,7 @@ cell = annmodel.SomeObject() cell.is_type_of = renamed_is_type_of cells.append(cell) + self.addpendingblock(fn, link.target, cells) if block in self.notify: # reflow from certain positions when this block is done Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Wed Jan 26 15:27:34 2005 @@ -712,3 +712,26 @@ return slice(1) else: return slice(0, 10, 2) + +def exception_deduction_we_are_dumb(): + a = 1 + try: + exception_deduction0(2) + except Exc, e: + a += 1 + return e + return Exc() + +class Exc2(Exception): + pass + +def nested_exception_deduction(): + try: + exception_deduction0(1) + except Exc, e: + try: + exception_deduction0(2) + except Exc2, f: + return (e, f) + return (e, Exc2()) + return (Exc(), Exc2()) Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Wed Jan 26 15:27:34 2005 @@ -468,6 +468,21 @@ assert isinstance(s, annmodel.SomeInstance) assert s.knowntype is snippet.Exc + def test_exception_deduction_we_are_dumb(self): + a = RPythonAnnotator() + s = a.build_types(snippet.exception_deduction_we_are_dumb, []) + assert isinstance(s, annmodel.SomeInstance) + assert s.knowntype is snippet.Exc + + def test_nested_exception_deduction(self): + a = RPythonAnnotator() + s = a.build_types(snippet.nested_exception_deduction, []) + assert isinstance(s, annmodel.SomeTuple) + assert isinstance(s.items[0], annmodel.SomeInstance) + assert isinstance(s.items[1], annmodel.SomeInstance) + assert s.items[0].knowntype is snippet.Exc + assert s.items[1].knowntype is snippet.Exc2 + def test_slice_union(self): a = RPythonAnnotator() s = a.build_types(snippet.slice_union, [int]) From mwh at codespeak.net Wed Jan 26 15:36:20 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 15:36:20 +0100 (MET) Subject: [pypy-svn] r8610 - pypy/dist/pypy/interpreter Message-ID: <20050126143620.BAEA427B88@code1.codespeak.net> Author: mwh Date: Wed Jan 26 15:36:20 2005 New Revision: 8610 Modified: pypy/dist/pypy/interpreter/argument.py Log: The annotator is no longer dumb! Modified: pypy/dist/pypy/interpreter/argument.py ============================================================================== --- pypy/dist/pypy/interpreter/argument.py (original) +++ pypy/dist/pypy/interpreter/argument.py Wed Jan 26 15:36:20 2005 @@ -121,9 +121,6 @@ try: return self.match_signature(signature, defaults_w) except ArgErr, e: - # XXX this hack is necessary because the annotator is - # dumb! -- mwh 2005-01-25 - assert isinstance(e, ArgErr) raise OperationError(space.w_TypeError, space.wrap(e.getmsg(self, fnname))) From ac at codespeak.net Wed Jan 26 15:37:45 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 26 Jan 2005 15:37:45 +0100 (MET) Subject: [pypy-svn] r8611 - pypy/dist/pypy/module/test Message-ID: <20050126143745.807C727B88@code1.codespeak.net> Author: ac Date: Wed Jan 26 15:37:45 2005 New Revision: 8611 Modified: pypy/dist/pypy/module/test/test_reduce.py pypy/dist/pypy/module/test/test_zip.py Log: Add test from cpython for zip() and reduce(). Modified: pypy/dist/pypy/module/test/test_reduce.py ============================================================================== --- pypy/dist/pypy/module/test/test_reduce.py (original) +++ pypy/dist/pypy/module/test/test_reduce.py Wed Jan 26 15:37:45 2005 @@ -1,5 +1,6 @@ import autopath + class AppTestReduce: def test_None(self): raises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) @@ -11,3 +12,25 @@ def test_minus(self): assert reduce(lambda x, y: x-y, [10, 2, 8]) == 0 assert reduce(lambda x, y: x-y, [2, 8], 10) == 0 + + def test_from_cpython(self): + class SequenceClass: + def __init__(self, n): + self.n = n + def __getitem__(self, i): + if 0 <= i < self.n: + return i + else: + raise IndexError + + from operator import add + assert reduce(add, SequenceClass(5)) == 10 + assert reduce(add, SequenceClass(5), 42) == 52 + raises(TypeError, reduce, add, SequenceClass(0)) + assert reduce(add, SequenceClass(0), 42) == 42 + assert reduce(add, SequenceClass(1)) == 0 + assert reduce(add, SequenceClass(1), 42) == 42 + + d = {"one": 1, "two": 2, "three": 3} + assert reduce(add, d) == "".join(d.keys()) + Modified: pypy/dist/pypy/module/test/test_zip.py ============================================================================== --- pypy/dist/pypy/module/test/test_zip.py (original) +++ pypy/dist/pypy/module/test/test_zip.py Wed Jan 26 15:37:45 2005 @@ -3,8 +3,9 @@ class AppTestZip: def test_zip_no_arguments(self): - raises(TypeError, zip) - + assert zip() == [] + assert zip(*[]) == [] + def test_one_list(self): assert zip([1, 2, 3]) == [(1,), (2,), (3,)] @@ -29,3 +30,105 @@ def test_mixed_types(self): assert zip('hello', [1,2,3,4], (7,8,9,10)) == ( [('h', 1, 7), ('e', 2, 8), ('l', 3, 9), ('l', 4, 10)]) + + def test_from_cpython(self): + from test.support_tests import TESTFN, unlink + class BasicIterClass: + def __init__(self, n): + self.n = n + self.i = 0 + def next(self): + res = self.i + if res >= self.n: + raise StopIteration + self.i = res + 1 + return res + + + class IteratingSequenceClass: + def __init__(self, n): + self.n = n + def __iter__(self): + return BasicIterClass(self.n) + + class SequenceClass: + def __init__(self, n): + self.n = n + def __getitem__(self, i): + if 0 <= i < self.n: + return i + else: + raise IndexError + + assert zip(*[(1, 2), 'ab']) == [(1, 'a'), (2, 'b')] + + raises(TypeError, zip, None) + raises(TypeError, zip, range(10), 42) + raises(TypeError, zip, range(10), zip) + + assert zip(IteratingSequenceClass(3)) == [(0,), (1,), (2,)] + assert zip(SequenceClass(3)) == [(0,), (1,), (2,)] + + d = {"one": 1, "two": 2, "three": 3} + assert d.items() == zip(d, d.itervalues()) + + # Generate all ints starting at constructor arg. + class IntsFrom: + def __init__(self, start): + self.i = start + + def __iter__(self): + return self + + def next(self): + i = self.i + self.i = i+1 + return i + + f = open(TESTFN, "w") + try: + f.write("a\n" "bbb\n" "cc\n") + finally: + f.close() + f = open(TESTFN, "r") + try: + assert (zip(IntsFrom(0), f, IntsFrom(-100)) == + [(0, "a\n", -100), + (1, "bbb\n", -99), + (2, "cc\n", -98)]) + finally: + f.close() + try: + unlink(TESTFN) + except OSError: + pass + + assert zip(xrange(5)) == [(i,) for i in range(5)] + + # Classes that lie about their lengths. + class NoGuessLen5: + def __getitem__(self, i): + if i >= 5: + raise IndexError + return i + + class Guess3Len5(NoGuessLen5): + def __len__(self): + return 3 + + class Guess30Len5(NoGuessLen5): + def __len__(self): + return 30 + + assert len(Guess3Len5()) == 3 + assert len(Guess30Len5()) == 30 + assert zip(NoGuessLen5()) == zip(range(5)) + assert zip(Guess3Len5()) == zip(range(5)) + assert zip(Guess30Len5()) == zip(range(5)) + + expected = [(i, i) for i in range(5)] + for x in NoGuessLen5(), Guess3Len5(), Guess30Len5(): + for y in NoGuessLen5(), Guess3Len5(), Guess30Len5(): + assert zip(x, y) == expected + + From mwh at codespeak.net Wed Jan 26 16:04:33 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 16:04:33 +0100 (MET) Subject: [pypy-svn] r8612 - pypy/dist/pypy/objspace/std Message-ID: <20050126150433.0572627B7B@code1.codespeak.net> Author: mwh Date: Wed Jan 26 16:04:33 2005 New Revision: 8612 Modified: pypy/dist/pypy/objspace/std/stdtypedef.py Log: Somewhat gateway-like (but lesser, because doing less) auto-class generating hacks for MmFrame & SpecialMmFrame. This should clear up the last *known* obstruction to the annotation of PyPy... Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Wed Jan 26 16:04:33 2005 @@ -111,6 +111,45 @@ result.append(value) return result +def make_frameclass_for_arity(arity, varargs, keywords, isspecial): + argnames = [] + for i in range(arity): + argnames.append('arg%dof%d'%(i+1, arity)) + if varargs: + argnames.append('var_args') + if keywords: + argnames.append('kw_args') + self_args_assigning = [] + for i in range(len(argnames)): + self_args_assigning.append(' self.%s = args[%i]'%(argnames[i], i)) + self_args_assigning = "\n".join(self_args_assigning) + self_args = ", ".join(['self.'+ a for a in argnames]) + name = 'MmFrameOfArity%d'%arity + if varargs: + name += "Var" + if keywords: + name += "KW" + if isspecial: + name = "Special" + name + d = locals() + template = mmtemplate + if isspecial: + template += specialmmruntemplate + else: + template += mmruntemplate +# print template%d + exec template%d in globals(), d + return d[name] + +_frameclass_for_arity_cache = {} +def frameclass_for_arity(arity, varargs, keywords, isspecial): + try: + return _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] + except KeyError: + r = _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] = \ + make_frameclass_for_arity(arity, varargs, keywords, isspecial) + return r + def slicemultimethod(multimethod, typeclass, result): for i in range(len(multimethod.specialnames)): # each MultimethodCode embeds a multimethod @@ -121,10 +160,10 @@ code = result[name] if code.bound_position < i: continue - if len(multimethod.specialnames) > 1: - mmframeclass = SpecialMmFrame - else: - mmframeclass = MmFrame + mmframeclass = frameclass_for_arity(multimethod.arity, + multimethod.extras.get('varargs', False), + multimethod.extras.get('keywords', False), + len(multimethod.specialnames) > 1) code = MultimethodCode(multimethod, mmframeclass, typeclass, i) result[name] = code @@ -181,33 +220,39 @@ def create_frame(self, space, w_globals, closure=None): return self.framecls(space, self) -class MmFrame(eval.Frame): +mmtemplate = """ +class %(name)s(eval.Frame): def setfastscope(self, scope_w): args = list(scope_w) args.insert(0, args.pop(self.code.bound_position)) - self.args = args +%(self_args_assigning)s def getfastscope(self): raise OperationError(self.space.w_TypeError, self.space.wrap("cannot get fastscope of a MmFrame")) - +""" + +mmruntemplate = """ def run(self): "Call the multimethod, raising a TypeError if not implemented." - w_result = self.code.mm(*self.args) + w_result = self.code.mm(%(self_args)s) # we accept a real None from operations with no return value if w_result is None: w_result = self.space.w_None return w_result +""" + +specialmmruntemplate = """ -class SpecialMmFrame(MmFrame): def run(self): "Call the multimethods, possibly returning a NotImplemented." try: - return self.code.mm.perform_call(*self.args) + return self.code.mm.perform_call(%(self_args)s) except FailedToImplement, e: if e.args: raise OperationError(e.args[0], e.args[1]) else: return self.space.w_NotImplemented +""" From arigo at codespeak.net Wed Jan 26 16:16:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 26 Jan 2005 16:16:09 +0100 (MET) Subject: [pypy-svn] r8613 - pypy/dist/pypy/interpreter Message-ID: <20050126151609.20CEB27B7B@code1.codespeak.net> Author: arigo Date: Wed Jan 26 16:16:08 2005 New Revision: 8613 Modified: pypy/dist/pypy/interpreter/pyframe.py Log: Catch interp-level KeyboardInterrupt, RuntimeError and MemoryError and turn them into OperationErrors in the main interpreter loop. Modified: pypy/dist/pypy/interpreter/pyframe.py ============================================================================== --- pypy/dist/pypy/interpreter/pyframe.py (original) +++ pypy/dist/pypy/interpreter/pyframe.py Wed Jan 26 16:16:08 2005 @@ -54,13 +54,27 @@ "Interpreter main loop!" try: while True: - executioncontext.bytecode_trace(self) - last_instr = self.next_instr try: try: - # fetch and dispatch the next opcode - # dispatch() is abstract, see pyopcode. - self.dispatch() + try: + while True: + # fetch and dispatch the next opcode + # dispatch() is abstract, see pyopcode. + executioncontext.bytecode_trace(self) + last_instr = self.next_instr + self.dispatch() + # catch asynchronous exceptions and turn them + # into OperationErrors + except KeyboardInterrupt: + raise OperationError(self.space.w_KeyboardInterrupt, + self.space.w_None) + except MemoryError: + raise OperationError(self.space.w_MemoryError, + self.space.w_None) + except RuntimeError, e: + raise OperationError(self.space.w_RuntimeError, + self.space.wrap("internal error: " + str(e))) + except OperationError, e: pytraceback.record_application_traceback( self.space, e, self, last_instr) @@ -70,8 +84,6 @@ import sys tb = sys.exc_info()[2] raise SApplicationException(e, tb) - # XXX some other exceptions could be caught here too, - # like KeyboardInterrupt except ControlFlowException, ctlflowexc: # we have a reason to change the control flow From pedronis at codespeak.net Wed Jan 26 16:21:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 26 Jan 2005 16:21:15 +0100 (MET) Subject: [pypy-svn] r8614 - pypy/dist/pypy/interpreter Message-ID: <20050126152115.4B0E627B7B@code1.codespeak.net> Author: pedronis Date: Wed Jan 26 16:21:15 2005 New Revision: 8614 Modified: pypy/dist/pypy/interpreter/baseobjspace.py Log: What was this code doing? Besides breaking translate_pypy... Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Wed Jan 26 16:21:15 2005 @@ -85,10 +85,6 @@ if name not in self.sys.builtin_modules: return None module = self.sys.builtin_modules[name] - if module is None: - from pypy.interpreter.extmodule import BuiltinModule - module = BuiltinModule(self, name) - self.sys.builtin_modules[name] = module w_module = self.wrap(module) self.sys.setbuiltinmodule(w_module, name) return w_module From mwh at codespeak.net Wed Jan 26 16:37:14 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Wed, 26 Jan 2005 16:37:14 +0100 (MET) Subject: [pypy-svn] r8615 - pypy/dist/pypy/interpreter Message-ID: <20050126153714.5729A27B7B@code1.codespeak.net> Author: mwh Date: Wed Jan 26 16:37:14 2005 New Revision: 8615 Modified: pypy/dist/pypy/interpreter/gateway.py Log: defancify the name of the auto-generated BuiltinFrame subclasses, so they become clickable in the pygame viewer. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Wed Jan 26 16:37:14 2005 @@ -217,7 +217,7 @@ try: return cache[key] except KeyError: - name = '<'+ ', '.join([getattr(k, "__name__", k) for k in key]) + '>' + name = '_'.join([getattr(k, "__name__", k) for k in key]) emit_sig = apply_unwrap_spec(unwrap_spec, None, BuiltinCodeSignature(name=name), unwrap_spec_emit) From ludal at codespeak.net Wed Jan 26 16:45:51 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Wed, 26 Jan 2005 16:45:51 +0100 (MET) Subject: [pypy-svn] r8616 - pypy/dist/pypy/objspace/std Message-ID: <20050126154551.3C7AE27B7B@code1.codespeak.net> Author: ludal Date: Wed Jan 26 16:45:51 2005 New Revision: 8616 Modified: pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/std/sliceobject.py Log: allow unwrapping of slice object for the purpose of slicing unicode (faked) objects Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Wed Jan 26 16:45:51 2005 @@ -285,6 +285,8 @@ def newslice(self, w_start, w_end, w_step): # w_step may be a real None + if w_step is None: + w_step = self.w_None return W_SliceObject(self, w_start, w_end, w_step) def newstring(self, chars_w): Modified: pypy/dist/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/sliceobject.py Wed Jan 26 16:45:51 2005 @@ -43,4 +43,7 @@ raise OperationError(space.w_TypeError, space.wrap("unhashable type")) +def unwrap__Slice(space, w_slice): + return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step)) + register_all(vars()) From pedronis at codespeak.net Wed Jan 26 17:14:22 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 26 Jan 2005 17:14:22 +0100 (MET) Subject: [pypy-svn] r8617 - pypy/dist/pypy/annotation Message-ID: <20050126161422.BA95327B88@code1.codespeak.net> Author: pedronis Date: Wed Jan 26 17:14:22 2005 New Revision: 8617 Modified: pypy/dist/pypy/annotation/builtin.py Log: annotation for ord builtin Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Wed Jan 26 17:14:22 2005 @@ -37,6 +37,9 @@ def builtin_chr(s_int): return SomeChar() +def builtin_ord(s_chr): + return SomeInteger(nonneg=True) + def builtin_unicode(s_obj): return SomeString() From arigo at codespeak.net Wed Jan 26 17:59:10 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 26 Jan 2005 17:59:10 +0100 (MET) Subject: [pypy-svn] r8618 - pypy/dist/pypy/objspace/std Message-ID: <20050126165910.6E73527B76@code1.codespeak.net> Author: arigo Date: Wed Jan 26 17:59:10 2005 New Revision: 8618 Modified: pypy/dist/pypy/objspace/std/listtype.py pypy/dist/pypy/objspace/std/stdtypedef.py Log: Allow arguments to be named in the stdobjspace's type's methods. As a first example, this enables list.sort(cmp=...) . Modified: pypy/dist/pypy/objspace/std/listtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/listtype.py (original) +++ pypy/dist/pypy/objspace/std/listtype.py Wed Jan 26 17:59:10 2005 @@ -10,7 +10,7 @@ list_index = MultiMethod('index', 4, defaults=(0,maxint)) list_count = MultiMethod('count', 2) list_reverse = MultiMethod('reverse',1) -list_sort = MultiMethod('sort', 2, defaults=(None,)) +list_sort = MultiMethod('sort', 2, defaults=(None,), argnames=['cmp']) list_reversed = MultiMethod('__reversed__', 1) def app_list_reversed__ANY(lst): Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Wed Jan 26 17:59:10 2005 @@ -187,7 +187,9 @@ self.typeclass = typeclass self.bound_position = bound_position self.framecls = framecls - argnames = ['x%d'%(i+1) for i in range(multimethod.arity)] + argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] + explicit_argnames = multimethod.extras.get('argnames', []) + argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames varargname = kwargname = None # XXX do something about __call__ and __init__ which still use # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w From tismer at codespeak.net Thu Jan 27 04:16:08 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 04:16:08 +0100 (MET) Subject: [pypy-svn] r8619 - pypy/dist/pypy/appspace Message-ID: <20050127031608.AB5F627B72@code1.codespeak.net> Author: tismer Date: Thu Jan 27 04:16:08 2005 New Revision: 8619 Modified: pypy/dist/pypy/appspace/exceptions.py Log: an exception module, generated by introspection and parameter probing. Well, the specific formatting is still bad, but all initializations seem to be very ok. I will not generate an interp-level version of this, to be integrated with PyPy. Modified: pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/exceptions.py (original) +++ pypy/dist/pypy/appspace/exceptions.py Thu Jan 27 04:16:08 2005 @@ -1,7 +1,3 @@ -# XXX -# This file is almost auto-generated now and yet -# not ableto adopt changes by hand. Please don't edit now. - class Exception: """Common base class for all exceptions.""" @@ -14,8 +10,14 @@ self.args = args # auto-generated code, please check carefully! - # please implement Exception.__str__ - # instantiation of Exception works with 13119 solutions + def __str__(self): + argc = len(self.args) + if argc == 0: + return '' + elif argc == 1: + return str(self.args[0]) + else: + return str(self.args) class StandardError(Exception): """Base class for all standard Python exceptions.""" @@ -36,12 +38,26 @@ """Unicode translation error.""" # auto-generated code, please check carefully! - ##def __init__(self, *args): - ## pass - ## completely wrong - # auto-generated code, please check carefully! - # please implement UnicodeTranslateError.__str__ - # instantiation of UnicodeTranslateError works with 1 solutions + def __init__(self, *args): + argc = len(args) + self.args = args # modified: always assign args, no error check + if argc == 4: + self.object = args[0] + self.start = args[1] + self.end = args[2] + self.reason = args[3] + + # auto-generated code, please check carefully! + def __str__(self): + # this is a bad hack, please supply an implementation + res = ' '.join([ + 'start=%s' % self.start), + 'reason=%s' % self.reason), + 'args=%s' % self.args), + 'end=%s' % self.end), + 'object=%s' % self.object), + ]) + return res class LookupError(StandardError): """Base class for lookup errors.""" @@ -50,8 +66,14 @@ """Mapping key not found.""" # auto-generated code, please check carefully! - # please implement KeyError.__str__ - # instantiation of KeyError works with 13119 solutions + def __str__(self): + argc = len(self.args) + if argc == 0: + return '' + elif argc == 1: + return repr(self.args[0]) + else: + return str(self.args) class Warning(Exception): """Base class for warning categories.""" @@ -69,12 +91,29 @@ """Base class for I/O related errors.""" # auto-generated code, please check carefully! - ##def __init__(self, *args): - ## pass - ## completely wrong - # auto-generated code, please check carefully! - # please implement EnvironmentError.__str__ - # instantiation of EnvironmentError works with 13119 solutions + def __init__(self, *args): + argc = len(args) + self.args = args + self.errno = None # default, hopefully + self.strerror = None # default, hopefully + self.filename = None # default, hopefully + if 2 <= argc <= 3: + self.errno = args[0] + self.strerror = args[1] + if argc == 3: + self.filename = args[2] + self.args = (args[0], args[1]) + + # auto-generated code, please check carefully! + def __str__(self): + # this is a bad hack, please supply an implementation + res = ' '.join([ + 'errno=%s' % self.errno), + 'args=%s' % self.args), + 'strerror=%s' % self.strerror), + 'filename=%s' % self.filename), + ]) + return res class OSError(EnvironmentError): """OS system call failed.""" @@ -86,12 +125,28 @@ """Unicode encoding error.""" # auto-generated code, please check carefully! - ##def __init__(self, *args): - ## pass - ## completely wrong - # auto-generated code, please check carefully! - # please implement UnicodeEncodeError.__str__ - # instantiation of UnicodeEncodeError works with 1 solutions + def __init__(self, *args): + argc = len(args) + self.args = args # modified: always assign args, no error check + if argc == 5: + self.encoding = args[0] + self.object = args[1] + self.start = args[2] + self.end = args[3] + self.reason = args[4] + + # auto-generated code, please check carefully! + def __str__(self): + # this is a bad hack, please supply an implementation + res = ' '.join([ + 'object=%s' % self.object), + 'end=%s' % self.end), + 'encoding=%s' % self.encoding), + 'args=%s' % self.args), + 'start=%s' % self.start), + 'reason=%s' % self.reason), + ]) + return res class ArithmeticError(StandardError): """Base class for arithmetic errors.""" @@ -121,12 +176,24 @@ text = None # auto-generated code, please check carefully! - ##def __init__(self, *args): - ## pass - ## completely wrong + def __init__(self, *args): + argc = len(args) + self.args = args + if argc >= 1: + self.msg = args[0] + if argc == 2: + self.filename = args[1][0] + self.lineno = args[1][1] + self.offset = args[1][2] + self.text = args[1][3] + # auto-generated code, please check carefully! - # please implement SyntaxError.__str__ - # instantiation of SyntaxError works with 13116 solutions + def __str__(self): + # this is a bad hack, please supply an implementation + res = ' '.join([ + 'args=%s' % self.args), + ]) + return res class FutureWarning(Warning): """Base class for warnings about constructs that will change semantically in the future.""" @@ -136,12 +203,13 @@ # auto-generated code, please check carefully! def __init__(self, *args): + argc = len(args) + if argc == 0: + self.code = None # default, hopefully self.args = args - if len(args) == 0: - self.code = None - elif len(args) == 1: + if argc == 1: self.code = args[0] - else: + if argc >= 2: self.code = args class EOFError(StandardError): @@ -169,12 +237,28 @@ """Unicode decoding error.""" # auto-generated code, please check carefully! - ##def __init__(self, *args): - ## pass - ## completely wrong - # auto-generated code, please check carefully! - # please implement UnicodeDecodeError.__str__ - # instantiation of UnicodeDecodeError works with 1 solutions + def __init__(self, *args): + argc = len(args) + self.args = args # modified: always assign args, no error check + if argc == 5: + self.encoding = args[0] + self.object = args[1] + self.start = args[2] + self.end = args[3] + self.reason = args[4] + + # auto-generated code, please check carefully! + def __str__(self): + # this is a bad hack, please supply an implementation + res = ' '.join([ + 'object=%s' % self.object), + 'end=%s' % self.end), + 'encoding=%s' % self.encoding), + 'args=%s' % self.args), + 'start=%s' % self.start), + 'reason=%s' % self.reason), + ]) + return res class TypeError(StandardError): """Inappropriate argument type.""" From tismer at codespeak.net Thu Jan 27 04:22:15 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 04:22:15 +0100 (MET) Subject: [pypy-svn] r8620 - pypy/dist/pypy/appspace Message-ID: <20050127032215.CD10727B72@code1.codespeak.net> Author: tismer Date: Thu Jan 27 04:22:15 2005 New Revision: 8620 Modified: pypy/dist/pypy/appspace/exceptions.py Log: an exception module, generated by introspection and parameter probing. Well, the specific formatting is still bad, but all initializations seem to be very ok. I will now generate an interp-level version of this, to be integrated with PyPy. Bugfix, works now. Text above was also wrong. Modified: pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/exceptions.py (original) +++ pypy/dist/pypy/appspace/exceptions.py Thu Jan 27 04:22:15 2005 @@ -51,11 +51,11 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'start=%s' % self.start), - 'reason=%s' % self.reason), - 'args=%s' % self.args), - 'end=%s' % self.end), - 'object=%s' % self.object), + 'start=%s' % self.start, + 'reason=%s' % self.reason, + 'args=%s' % self.args, + 'end=%s' % self.end, + 'object=%s' % self.object, ]) return res @@ -108,10 +108,10 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'errno=%s' % self.errno), - 'args=%s' % self.args), - 'strerror=%s' % self.strerror), - 'filename=%s' % self.filename), + 'errno=%s' % self.errno, + 'args=%s' % self.args, + 'strerror=%s' % self.strerror, + 'filename=%s' % self.filename, ]) return res @@ -139,12 +139,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=%s' % self.object), - 'end=%s' % self.end), - 'encoding=%s' % self.encoding), - 'args=%s' % self.args), - 'start=%s' % self.start), - 'reason=%s' % self.reason), + 'object=%s' % self.object, + 'end=%s' % self.end, + 'encoding=%s' % self.encoding, + 'args=%s' % self.args, + 'start=%s' % self.start, + 'reason=%s' % self.reason, ]) return res @@ -191,7 +191,7 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'args=%s' % self.args), + 'args=%s' % self.args, ]) return res @@ -251,12 +251,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=%s' % self.object), - 'end=%s' % self.end), - 'encoding=%s' % self.encoding), - 'args=%s' % self.args), - 'start=%s' % self.start), - 'reason=%s' % self.reason), + 'object=%s' % self.object, + 'end=%s' % self.end, + 'encoding=%s' % self.encoding, + 'args=%s' % self.args, + 'start=%s' % self.start, + 'reason=%s' % self.reason, ]) return res From ac at codespeak.net Thu Jan 27 09:47:34 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Thu, 27 Jan 2005 09:47:34 +0100 (MET) Subject: [pypy-svn] r8621 - in pypy/dist/pypy/appspace: . test Message-ID: <20050127084734.3BC4627B8D@code1.codespeak.net> Author: ac Date: Thu Jan 27 09:47:33 2005 New Revision: 8621 Modified: pypy/dist/pypy/appspace/_file.py pypy/dist/pypy/appspace/sio.py pypy/dist/pypy/appspace/test/test_file.py Log: Add tests of __builtin__.file from cpython (and make file comply). Modified: pypy/dist/pypy/appspace/_file.py ============================================================================== --- pypy/dist/pypy/appspace/_file.py (original) +++ pypy/dist/pypy/appspace/_file.py Thu Jan 27 09:47:33 2005 @@ -58,11 +58,14 @@ """ Return an iterator for the file. """ + if self._closed: + raise ValueError('I/O operation on closed file') return self - + xreadlines = __iter__ + def next(self): if self._closed: - raise StopIteration + raise ValueError('I/O operation on closed file') line = self.fd.readline() if line == '': raise StopIteration @@ -73,7 +76,10 @@ Close the file """ self._closed = True - getattr(self.fd, 'close', lambda: None)() + try: + self.fd.close() + except AttributeError: + pass def __getattr__(self, attr): """ @@ -93,3 +99,20 @@ if attr in ['mode', 'name', 'closed', 'encoding']: raise TypeError, "readonly attribute:'%s'" % attr self.__dict__[attr] = val + + def seek(self, *args, **kw): + if self._closed: + raise ValueError('I/O operation on closed file') + self.fd.seek(*args, **kw) + + def write(self, *args, **kw): + if self._closed: + raise ValueError('I/O operation on closed file') + self.fd.write(*args, **kw) + + def writelines(self, seq = ()): + if self._closed: + raise ValueError('I/O operation on closed file') + for line in seq: + self.write(line) + Modified: pypy/dist/pypy/appspace/sio.py ============================================================================== --- pypy/dist/pypy/appspace/sio.py (original) +++ pypy/dist/pypy/appspace/sio.py Thu Jan 27 09:47:33 2005 @@ -54,6 +54,7 @@ bufsize = 2**13 # 8 K def __init__(self, base, bufsize=None): + self.base = base self.do_read = getattr(base, "read", None) # function to fill buffer some more self.do_tell = getattr(base, "tell", None) @@ -298,6 +299,7 @@ def flush(self): self.do_write(self.buf) self.buf = '' + self.base.flush() def write(self, data): buflen = len(self.buf) @@ -317,10 +319,10 @@ self.write(s) def close(self): - self.do_write(self.buf) - self.buf = '' - if self.do_close(): - self.do_close() + if (self.buf): + self.do_write(self.buf) + self.buf = '' + self.do_close() def truncate(self, size=None): self.flush() @@ -334,6 +336,7 @@ """ def __init__(self, base, bufsize=None): + self.base = base self.do_write = base.write # Flush buffer self.do_tell = base.tell # Return a byte offset; has to exist or this __init__() will fail @@ -381,6 +384,13 @@ self.do_write(self.buf) self.buf = '' self.write(line[self.bufsize-buflen:]) + + def flush(self): + if self.buf: + self.do_write(self.buf) + self.buf = '' + self.base.flush() + class BufferingInputOutputStream(Stream): """To handle buffered input and output at the same time, we are @@ -445,11 +455,12 @@ """ def __init__(self, base): + self.base = base self.do_read = base.read self.atcr = False self.close = base.close - def read(self, n): + def read(self, n=-1): data = self.do_read(n) if self.atcr: if data.startswith("\n"): @@ -597,6 +608,11 @@ def writelines(self, lines): filter(self.write, lines) + def flush(self): + if self.mm is None: + raise ValueError('I/O operation on closed file') + self.mm.flush() + class DiskFile(object): """Standard I/O basis stream using os.open/close/read/write/lseek""" @@ -643,15 +659,30 @@ os.lseek(self.fd, 0, 2) # Move to end of file def seek(self, offset, whence=0): + if self.fd is None: + raise ValueError('I/O operation on closed file') os.lseek(self.fd, offset, whence) def tell(self): + if self.fd is None: + raise ValueError('I/O operation on closed file') return os.lseek(self.fd, 0, 1) - def read(self, n): - return os.read(self.fd, n) + def read(self, n=-1): + if self.fd is None: + raise ValueError('I/O operation on closed file') + if n >= 0: + return os.read(self.fd, n) + data = [] + while 1: + moreData = os.read(self.fd, 2**20) + if len(moreData) == 0: + return ''.join(data) + data.append(moreData) def write(self, data): + if self.fd is None: + raise ValueError('I/O operation on closed file') while data: n = os.write(self.fd, data) data = data[n:] @@ -663,21 +694,31 @@ os.close(fd) def truncate(self, size=None): + if self.fd is None: + raise ValueError('I/O operation on closed file') if size is None: size = self.tell() - if os.name == 'posix': + try: os.ftruncate(self.fd, size) - else: + except AttributeError: raise NotImplementedError def isatty(self): - if os.name == 'posix': + if self.fd is None: + raise ValueError('I/O operation on closed file') + try: return os.isatty(self.fd) - else: + except AttributeError: raise NotImplementedError - def fileno(): + def fileno(self): + if self.fd is None: + raise ValueError('I/O operation on closed file') return self.fd + + def flush(self): + if self.fd is None: + raise ValueError('I/O operation on closed file') def __del__(self): try: Modified: pypy/dist/pypy/appspace/test/test_file.py ============================================================================== --- pypy/dist/pypy/appspace/test/test_file.py (original) +++ pypy/dist/pypy/appspace/test/test_file.py Thu Jan 27 09:47:33 2005 @@ -24,3 +24,170 @@ assert f.closed == False assert f.encoding == None # Fix when we find out what this is py.test.raises(TypeError, setattr, f, 'name', 42) + + + def test_from_cpython(self): + + from test.test_support import verify, TESTFN, TestFailed + from UserList import UserList + + # verify expected attributes exist + f = file(TESTFN, 'w') + softspace = f.softspace + f.name # merely shouldn't blow up + f.mode # ditto + f.closed # ditto + + # verify softspace is writable + f.softspace = softspace # merely shouldn't blow up + + # verify the others aren't + for attr in 'name', 'mode', 'closed': + try: + setattr(f, attr, 'oops') + except TypeError: + pass + else: + raise TestFailed('expected TypeError setting file attr %r' % attr) + f.close() + + # verify writelines with instance sequence + l = UserList(['1', '2']) + f = open(TESTFN, 'wb') + f.writelines(l) + f.close() + f = open(TESTFN, 'rb') + buf = f.read() + f.close() + verify(buf == '12') + + # verify writelines with integers + f = open(TESTFN, 'wb') + try: + f.writelines([1, 2, 3]) + except TypeError: + pass + else: + print "writelines accepted sequence of integers" + f.close() + + # verify writelines with integers in UserList + f = open(TESTFN, 'wb') + l = UserList([1,2,3]) + try: + f.writelines(l) + except TypeError: + pass + else: + print "writelines accepted sequence of integers" + f.close() + + # verify writelines with non-string object + class NonString: pass + + f = open(TESTFN, 'wb') + try: + f.writelines([NonString(), NonString()]) + except TypeError: + pass + else: + print "writelines accepted sequence of non-string objects" + f.close() + + # verify that we get a sensible error message for bad mode argument + bad_mode = "qwerty" + try: + open(TESTFN, bad_mode) + except IOError, msg: + pass # We have problems with Exceptions + #if msg[0] != 0: + # s = str(msg) + # if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: + # print "bad error message for invalid mode: %s" % s + ## if msg[0] == 0, we're probably on Windows where there may be + ## no obvious way to discover why open() failed. + else: + print "no error for invalid mode: %s" % bad_mode + + f = open(TESTFN) + if f.name != TESTFN: + raise TestFailed, 'file.name should be "%s"' % TESTFN + + if f.isatty(): + raise TestFailed, 'file.isatty() should be false' + + if f.closed: + raise TestFailed, 'file.closed should be false' + + + f.close() + if not f.closed: + raise TestFailed, 'file.closed should be true' + + # make sure that explicitly setting the buffer size doesn't cause + # misbehaviour especially with repeated close() calls + for s in (-1, 0, 1, 512): + try: + f = open(TESTFN, 'w', s) + f.write(str(s)) + f.close() + f.close() + f = open(TESTFN, 'r', s) + d = int(f.read()) + f.close() + f.close() + except IOError, msg: + raise TestFailed, 'error setting buffer size %d: %s' % (s, str(msg)) + if d != s: + raise TestFailed, 'readback failure using buffer size %d' + + methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readline', + 'readlines', 'seek', 'tell', 'truncate', 'write', + 'xreadlines', '__iter__'] + + for methodname in methods: + method = getattr(f, methodname) + try: + method() + except ValueError: + pass + else: + raise TestFailed, 'file.%s() on a closed file should raise a ValueError' % methodname + + try: + f.writelines([]) + except ValueError: + pass + else: + raise TestFailed, 'file.writelines([]) on a closed file should raise a ValueError' + + os.unlink(TESTFN) + + def bug801631(): + # SF bug + # "file.truncate fault on windows" + f = file(TESTFN, 'wb') + f.write('12345678901') # 11 bytes + f.close() + + f = file(TESTFN,'rb+') + data = f.read(5) + if data != '12345': + raise TestFailed("Read on file opened for update failed %r" % data) + if f.tell() != 5: + raise TestFailed("File pos after read wrong %d" % f.tell()) + + f.truncate() + if f.tell() != 5: + raise TestFailed("File pos after ftruncate wrong %d" % f.tell()) + + f.close() + size = os.path.getsize(TESTFN) + if size != 5: + raise TestFailed("File size after ftruncate wrong %d" % size) + + try: + bug801631() + finally: + os.unlink(TESTFN) + From ac at codespeak.net Thu Jan 27 09:50:38 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Thu, 27 Jan 2005 09:50:38 +0100 (MET) Subject: [pypy-svn] r8622 - pypy/dist/pypy/appspace/test Message-ID: <20050127085038.F239F27B8D@code1.codespeak.net> Author: ac Date: Thu Jan 27 09:50:38 2005 New Revision: 8622 Modified: pypy/dist/pypy/appspace/test/test_sio.py Log: Fix sio tests. Modified: pypy/dist/pypy/appspace/test/test_sio.py ============================================================================== --- pypy/dist/pypy/appspace/test/test_sio.py (original) +++ pypy/dist/pypy/appspace/test/test_sio.py Thu Jan 27 09:50:38 2005 @@ -90,6 +90,8 @@ def close(self): pass + def flush(self): + pass class TestWriter(object): def __init__(self, data=''): @@ -131,6 +133,9 @@ self.buf = self.buf[:size] else: self.buf += '\0' * (size - len(self.buf)) + + def flush(self): + pass class TestReaderWriter(TestWriter): From ac at codespeak.net Thu Jan 27 10:24:19 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Thu, 27 Jan 2005 10:24:19 +0100 (MET) Subject: [pypy-svn] r8623 - pypy/dist/pypy/appspace/test Message-ID: <20050127092419.BDE9927B88@code1.codespeak.net> Author: ac Date: Thu Jan 27 10:24:19 2005 New Revision: 8623 Modified: pypy/dist/pypy/appspace/test/test_file.py Log: Enable another test for file. Modified: pypy/dist/pypy/appspace/test/test_file.py ============================================================================== --- pypy/dist/pypy/appspace/test/test_file.py (original) +++ pypy/dist/pypy/appspace/test/test_file.py Thu Jan 27 10:24:19 2005 @@ -100,12 +100,12 @@ open(TESTFN, bad_mode) except IOError, msg: pass # We have problems with Exceptions - #if msg[0] != 0: - # s = str(msg) - # if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: - # print "bad error message for invalid mode: %s" % s - ## if msg[0] == 0, we're probably on Windows where there may be - ## no obvious way to discover why open() failed. + if msg[0] != 0: + s = str(msg) + if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: + print "bad error message for invalid mode: %s" % s + # if msg[0] == 0, we're probably on Windows where there may be + # no obvious way to discover why open() failed. else: print "no error for invalid mode: %s" % bad_mode From tismer at codespeak.net Thu Jan 27 10:51:40 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 10:51:40 +0100 (MET) Subject: [pypy-svn] r8624 - pypy/dist/pypy/appspace Message-ID: <20050127095140.0BA9C27B88@code1.codespeak.net> Author: tismer Date: Thu Jan 27 10:51:39 2005 New Revision: 8624 Modified: pypy/dist/pypy/appspace/exceptions.py Log: better default formatting via getattr, but still just a joke. Modified: pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/exceptions.py (original) +++ pypy/dist/pypy/appspace/exceptions.py Thu Jan 27 10:51:39 2005 @@ -51,11 +51,11 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'start=%s' % self.start, - 'reason=%s' % self.reason, - 'args=%s' % self.args, - 'end=%s' % self.end, - 'object=%s' % self.object, + 'start=' + str(self.start), + 'reason=' + str(self.reason), + 'args=' + str(self.args), + 'end=' + str(self.end), + 'object=' + str(self.object), ]) return res @@ -108,10 +108,10 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'errno=%s' % self.errno, - 'args=%s' % self.args, - 'strerror=%s' % self.strerror, - 'filename=%s' % self.filename, + 'errno=' + str(self.errno), + 'args=' + str(self.args), + 'strerror=' + str(self.strerror), + 'filename=' + str(self.filename), ]) return res @@ -139,12 +139,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=%s' % self.object, - 'end=%s' % self.end, - 'encoding=%s' % self.encoding, - 'args=%s' % self.args, - 'start=%s' % self.start, - 'reason=%s' % self.reason, + 'object=' + str(self.object), + 'end=' + str(self.end), + 'encoding=' + str(self.encoding), + 'args=' + str(self.args), + 'start=' + str(self.start), + 'reason=' + str(self.reason), ]) return res @@ -191,7 +191,7 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'args=%s' % self.args, + 'args=' + str(self.args), ]) return res @@ -251,12 +251,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=%s' % self.object, - 'end=%s' % self.end, - 'encoding=%s' % self.encoding, - 'args=%s' % self.args, - 'start=%s' % self.start, - 'reason=%s' % self.reason, + 'object=' + str(self.object), + 'end=' + str(self.end), + 'encoding=' + str(self.encoding), + 'args=' + str(self.args), + 'start=' + str(self.start), + 'reason=' + str(self.reason), ]) return res From tismer at codespeak.net Thu Jan 27 10:58:28 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 10:58:28 +0100 (MET) Subject: [pypy-svn] r8625 - pypy/dist/pypy/appspace Message-ID: <20050127095828.72DBB27B88@code1.codespeak.net> Author: tismer Date: Thu Jan 27 10:58:28 2005 New Revision: 8625 Added: pypy/dist/pypy/appspace/_exceptions.py - copied unchanged from r8624, pypy/dist/pypy/appspace/exceptions.py Log: renamed exceptions.py into _exceptions.py, to avoid confusion. It is also not quite clear, how to sort this out, because there will be more modules which might or might not get turned into interp level. Discussion needed. From tismer at codespeak.net Thu Jan 27 11:02:39 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 11:02:39 +0100 (MET) Subject: [pypy-svn] r8626 - pypy/dist/pypy/tool Message-ID: <20050127100239.B609B27B88@code1.codespeak.net> Author: tismer Date: Thu Jan 27 11:02:39 2005 New Revision: 8626 Added: pypy/dist/pypy/tool/_enum_exceptions.py Log: This is the crazy module that introspects and regenerates the exceptions module. It works very nice for the __init__ methods. Automatic recreation of the __str__ methods appears to be almost impossible with reasonable effort. Not that this source file is already as large as the output it produces :-) Some of the ideas might be applicable in other fields as well. I learned quite a bit from this. Added: pypy/dist/pypy/tool/_enum_exceptions.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/tool/_enum_exceptions.py Thu Jan 27 11:02:39 2005 @@ -0,0 +1,327 @@ +# this script is used for extracting +# the information available for exceptions +# via introspection. +# The idea is to use it once to create +# a template for a re-birth of exceptions.py + +import types + +def classOfAttribute(klass, attname): + if attname in klass.__dict__: + return klass + for base in klass.__bases__: + ret = classOfAttribute(base, attname) + if ret: + return ret + +def getAttributes(klass, ignorelist = []): + return [name for name in dir(klass) if name not in ignorelist] + +def makeExceptionsTemplate(f=None): + + def enumExceptionsInOrder(): + import exceptions + seen = {} + ordered = [] + + def enumerateOne(exc): + seen[exc] = 1 + for each in exc.__bases__: + if each not in seen: + enumerateOne(each) + ordered.append(exc) + + for each in exceptions.__dict__.values(): + if isinstance(each, (types.ClassType, type)) and \ + each not in seen: + enumerateOne(each) + + return ordered + + if not f: + f = sys.stdout + + for exc in enumExceptionsInOrder(): + name = exc.__name__ + bases = exc.__bases__ + doc = exc.__doc__ + bases = [this.__name__ for this in bases] + bases = ", ".join(bases) + if bases: bases = "(%s)" % bases + + ignorelist = "__doc__ __module__".split() + # find out class variables and methods + simple = [] + difficult = [] + for attname in getAttributes(exc, ignorelist): + if classOfAttribute(exc, attname) is exc: + obj = getattr(exc, attname) + (simple, difficult)[callable(obj)].append( (attname, obj) ) + print >> f, "class %s%s:" % (name, bases) + if doc: + print >> f, ' """%s"""' % doc + if not (simple or difficult or doc): + print >> f, " pass" + for tup in simple: + print >> f, " %s = %r" % tup + + for attname, meth in difficult: + print >> f + func = globals().get("tryGenerate" + attname, None) + if not func: + print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) + else: + try: + print >> f, " # auto-generated code, please check carefully!" + for line in func(exc): + print >> f, " " + line + except ValueError, e: + print >> f, " # %s" % e + print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) + print >> f + +def tryGenerate__getitem__(exc): + for args in (), (1, 2, 3): + try: + sample = exc(*args) + except: + raise ValueError, "cannot create instance" + if "args" not in sample.__dict__: + raise ValueError, "args attribute not found in __dict__" + if args != sample.args: + raise ValueError, "instance has modified args" + for i in range(5): + try: x = sample[i] + except IndexError: x = 42 + try: y = args[i] + except IndexError: y = 42 + if x != y: + raise ValueError, "args does not behave like a sequence" + del sample.args + try: x = sample[0] + except: x = 42 + use_default = x is None + # looks fine so far. + yield "def __getitem__(self, idx):" + if use_default: + yield " if not hasattr(self, 'args'):" + yield " return None" + yield " return self.args[idx]" + + +class ProbeObject(object): + """ this class creates general "any" objects, and + for the special case of SyntaxError, it can behave + like a subscriptable object + """ + def __init__(self, argpos, maxprobe=None): + self.argpos = argpos + self.maxprobe = maxprobe + self.probed = [] + def __getitem__(self, idx): + if idx not in self.probed: + self.probed.append(idx) + if self.maxprobe is not None and idx > self.maxprobe: + raise IndexError, "cheat cheat %d" % idx + return "arg%d_%s" % (self.argpos, idx) + def __repr__(self): + if self.probed: + return "" % (self.argpos, self.probed) + else: + return "" % self.argpos + def __str__(self): + # make this different from repr! + return repr(self)[1:-1] + def __cmp__(self, other): + return cmp( (self.argpos, self.probed), other) + +def genArgsToTry(argpos): + args = [ProbeObject(argpos), + "arg%d" % argpos, u"arg%d" %argpos, 1000+argpos*10] + return args + +def cartesian(*args): + if len(args)== 0: + yield args + elif len(args) == 1: + for item in args[0]: + yield (item,) + else: + for item in args[0]: + for other in cartesian(*args[1:]): + yield (item,) + other + +def probeArgCount(exc, maxprobe=20): + worksmaybe = [] + for i in range(maxprobe): + try: + probe = exc(*(i,)*i) # test i-tuple + worksmaybe.append(i) + except TypeError, e: + if not str(e).startswith("function takes "): + worksmaybe.append(i) + except: + pass + return min(worksmaybe), max(worksmaybe) + +def refreshArgs(tup): + res = [] + for arg in tup: + if type(arg) is ProbeObject: + arg = ProbeObject(arg.argpos) # cleanup probing + res.append(arg) + return tuple(res) + +def findAllArgs(exc, maxprobe): + minargs, maxargs = probeArgCount(exc, maxprobe=20) + res = [] + # for minargs args, we need to try combinations + arglist = tuple([genArgsToTry(i) for i in range(minargs)]) + for args in cartesian(*arglist): + try: + probe = exc(*args) + res.append(args) + works = refreshArgs(args) + break + except Exception, e: + continue + else: + raise TypeError, "cannot analyse arguments of %s" % exc.__name__ + # for the variable part, don't try combinations + for i in range(minargs, maxargs): + for arg in genArgsToTry(i): + args = works + (arg,) + try: + probe = exc(*args) + res.append(args) + works = refreshArgs(args) + break + except: + continue + else: + raise TypeError, "cannot analyse arguments of %s" % exc.__name__ + return minargs, maxargs, res + +def captureAssignments(exc, args): + """ we wrap a class around the exc class and record attribute access """ + assigned = [] + class WrapExc(exc): + def __setattr__(self, name, obj): + assigned.append( (name, obj) ) + self.__dict__[name] = obj + probe = WrapExc(*args) + names = {} + names[args] = "args" + for i, arg in enumerate(args): + names[arg] = "args[%d]" % i + if not isinstance(arg, ProbeObject): + continue + for subidx in arg.probed: + names[arg[subidx]] = "args[%d][%d]" % (i, subidx) + def nameof(obj): + if obj in names: + return names[obj] + elif isinstance(obj, (tuple, list)): + stuff = [nameof(x) for x in obj] + br = str(type(obj)()) + txt = br[0] + ", ".join(stuff) + br[-1] + names[obj] = txt + else: + names[obj] = "%r # default, hopefully" % obj + return names[obj] + res = [] + for name, obj in assigned: + res.append("self.%s = %s" % (name, nameof(obj))) + return tuple(res) + +def tryGenerate__init__(exc, maxprobe=20): + minargs, maxargs, working = findAllArgs(exc, maxprobe) + # merge assignments in order, record set of arg counts + foldcases = {} + for args in working: + singleprog = captureAssignments(exc, args) + for tup in enumerate(singleprog): + foldcases.setdefault(tup, []) + foldcases[tup].append(len(args)) + # group assignments by set of arg counts and order + groupassign = {} + for (order, assignment), argcounts in foldcases.items(): + key = tuple(argcounts) + # special case: we don't raise errors + # and always assign to self.args + if assignment == "self.args = args" and len(key) != maxprobe: + assignment += " # modified: always assign args, no error check" + key = tuple(range(maxprobe)) + groupassign.setdefault(key, []) + groupassign[key].append( (order, assignment) ) + cases = groupassign.items() + cases.sort() + yield "def __init__(self, *args):" + if len(cases) > 1 or len(cases[0][0]) != maxprobe: + yield " argc = len(args)" + for argcounts, ordered_statements in cases: + ordered_statements.sort() + if len(argcounts) == maxprobe: + # all counts, no condition + indent = 1 + else: + indent = 2 + dense = tuple(range(argcounts[0], argcounts[-1]+1)) == argcounts + if len(argcounts) == 1: + yield " if argc == %d:" % argcounts + elif dense and argcounts[0] == 0: + yield " if argc <= %d:" % argcounts[-1] + elif dense and argcounts[-1] == maxprobe-1: + yield " if argc >= %d:" % argcounts[0] + elif dense: + yield " if %d <= argc <= %d:" % (argcounts[0], argcounts[-1]) + else: + yield " if argc in %r:" % (argcounts, ) + for order, line in ordered_statements: + yield indent * " " + line + +def tryGenerate__str__(exc, maxprobe=20): + minargs, maxargs, working = findAllArgs(exc, maxprobe) + # checking the default case (well, there are two) + simple = False + arg1_methods = [] + for args in working: + test = str(exc(*args)) + if len(args) == 0 and test != "": + break + if len(args) == 1: + if test == repr(args[0]): + arg1_methods.append("repr") + elif test == str(args[0]): + arg1_methods.append("str") + else: + break + if len(args) >= 2 and test != repr(args): + break + else: + simple = arg1_methods and min(arg1_methods) == max(arg1_methods) + if simple: + yield "def __str__(self):" + yield " argc = len(self.args)" + yield " if argc == 0:" + yield " return ''" + yield " elif argc == 1:" + yield " return %s(self.args[0])" % arg1_methods.pop() + yield " else:" + yield " return str(self.args)" + return + # no idea how I should do this + probe = exc(*working[0]) + dic = probe.__dict__ + for key in dic.keys(): + if key.startswith("__") and key.endswith("__"): + del dic[key] + yield "def __str__(self):" + yield " # this is a bad hack, please supply an implementation" + yield " res = ' '.join([" + for key in dic.keys(): + yield " '%s=' + str(self.%s)," % (key, key) + yield " ])" + yield " return res" + +makeExceptionsTemplate(file("d:/tmp/look.py", "w")) From adim at codespeak.net Thu Jan 27 11:08:44 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Thu, 27 Jan 2005 11:08:44 +0100 (MET) Subject: [pypy-svn] r8627 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050127100844.93FBC27B88@code1.codespeak.net> Author: adim Date: Thu Jan 27 11:08:44 2005 New Revision: 8627 Modified: pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/listtype.py pypy/dist/pypy/objspace/std/test/test_listobject.py Log: added key and reverse optional arguments to list.sort() (+tests) Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Thu Jan 27 11:08:44 2005 @@ -454,8 +454,9 @@ # CPython sort() should be studied to learn how # to implement this functionality. -def _partition(list, start, end, lt): - pivot = list[end] # Partition around the last value +def _partition(list, key_list, start, end, lt): + pivot = list[end] + key_pivot = key_list[end] # Partition around the last value bottom = start-1 # Start outside the area to be partitioned top = end # Ditto @@ -469,7 +470,8 @@ done = 1 # ... we are done. break - if lt(pivot, list[bottom]): # Is the bottom out of place? + if lt(key_pivot, key_list[bottom]): # Is the bottom out of place? + key_list[top] = key_list[bottom] list[top] = list[bottom] # Then put it at the top... break # ... and start searching from the top. @@ -480,19 +482,24 @@ done = 1 # ... we are done. break - if lt(list[top], pivot): # Is the top out of place? + if lt(key_list[top], key_pivot): # Is the top out of place? + key_list[bottom] = key_list[top] list[bottom] = list[top] # Then put it at the bottom... break # ...and start searching from the bottom. + key_list[top] = key_pivot list[top] = pivot # Put the pivot in its place. return top # Return the split point -def _quicksort(list, start, end, lt): +def _quicksort(list, key_list, start, end, lt): + """list is the list to be sorted + key_list is the list that will be used for comparisions + """ if start < end: # If there are two or more elements... - split = _partition(list, start, end, lt) # ... partition the sublist... - _quicksort(list, start, split-1, lt) # ... and sort both halves. - _quicksort(list, split+1, end, lt) + split = _partition(list, key_list, start, end, lt) # ... partition the sublist... + _quicksort(list, key_list, start, split-1, lt) # ... and sort both halves. + _quicksort(list, key_list, split+1, end, lt) class Comparer: """Just a dumb container class for a space and a w_cmp, because @@ -519,16 +526,28 @@ raise return result < 0 -def list_sort__List_ANY(space, w_list, w_cmp): +def list_sort__List_ANY_ANY_ANY(space, w_list, w_cmp, w_key, w_reverse): comparer = Comparer(space, w_cmp) if w_cmp is space.w_None: lt = comparer.simple_lt else: lt = comparer.complex_lt - + # The key_list is the result of map(w_key, w_list), and will be + # used for comparisons during the qsort + if w_key is not space.w_None: + key_list = [space.call_function(w_key, item) + for item in w_list.ob_item[:w_list.ob_size]] + else: + # If no key was specified, then comparison will be made on + # the original list + key_list = w_list.ob_item # XXX Basic quicksort implementation # XXX this is not stable !! - _quicksort(w_list.ob_item, 0, w_list.ob_size-1, lt) + _quicksort(w_list.ob_item, key_list, 0, w_list.ob_size-1, lt) + # _quicksort(w_list.ob_item, 0, w_list.ob_size-1, lt) + # reverse list if needed + if space.is_true(w_reverse): + list_reverse__List(space, w_list) return space.w_None Modified: pypy/dist/pypy/objspace/std/listtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/listtype.py (original) +++ pypy/dist/pypy/objspace/std/listtype.py Thu Jan 27 11:08:44 2005 @@ -10,7 +10,7 @@ list_index = MultiMethod('index', 4, defaults=(0,maxint)) list_count = MultiMethod('count', 2) list_reverse = MultiMethod('reverse',1) -list_sort = MultiMethod('sort', 2, defaults=(None,), argnames=['cmp']) +list_sort = MultiMethod('sort', 4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse']) list_reversed = MultiMethod('__reversed__', 1) def app_list_reversed__ANY(lst): Modified: pypy/dist/pypy/objspace/std/test/test_listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_listobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_listobject.py Thu Jan 27 11:08:44 2005 @@ -313,6 +313,35 @@ l = [ 'a' ] l.sort(lencmp) assert l == [ 'a' ] + + def test_sort_key(self): + def lower(x): return x.lower() + l = ['a', 'C', 'b'] + l.sort(key = lower) + assert l == ['a', 'b', 'C'] + l = [] + l.sort(key = lower) + assert l == [] + l = [ 'a' ] + l.sort(key = lower) + assert l == [ 'a' ] + + def test_sort_reversed(self): + l = range(10) + l.sort(reverse = True) + assert l == range(9, -1, -1) + l = [] + l.sort(reverse = True) + assert l == [] + l = [1] + l.sort(reverse = True) + assert l == [1] + + def test_sort_cmp_key_reverse(self): + def lower(x): return x.lower() + l = ['a', 'C', 'b'] + l.sort(reverse = True, key = lower) + assert l == ['C', 'b', 'a'] def test_extended_slice(self): l = range(10) From tismer at codespeak.net Thu Jan 27 11:09:07 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 11:09:07 +0100 (MET) Subject: [pypy-svn] r8628 - pypy/dist/pypy/tool Message-ID: <20050127100907.6008727B88@code1.codespeak.net> Author: tismer Date: Thu Jan 27 11:09:07 2005 New Revision: 8628 Modified: pypy/dist/pypy/tool/_enum_exceptions.py Log: changed main code to generate the right output path. Modified: pypy/dist/pypy/tool/_enum_exceptions.py ============================================================================== --- pypy/dist/pypy/tool/_enum_exceptions.py (original) +++ pypy/dist/pypy/tool/_enum_exceptions.py Thu Jan 27 11:09:07 2005 @@ -323,5 +323,9 @@ yield " '%s=' + str(self.%s)," % (key, key) yield " ])" yield " return res" - -makeExceptionsTemplate(file("d:/tmp/look.py", "w")) + +if __name__ == "__main__": + import pypy.appspace, os + targetdir = os.path.dirname(pypy.appspace.__file__) + fname = os.path.join(targetdir, "_exceptions.py") + makeExceptionsTemplate(file(fname, "w")) From arigo at codespeak.net Thu Jan 27 11:19:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 27 Jan 2005 11:19:26 +0100 (MET) Subject: [pypy-svn] r8629 - in pypy/dist/pypy: interpreter objspace/std Message-ID: <20050127101926.C6E3E27B88@code1.codespeak.net> Author: arigo Date: Thu Jan 27 11:19:26 2005 New Revision: 8629 Modified: pypy/dist/pypy/interpreter/error.py pypy/dist/pypy/objspace/std/fake.py Log: - hide the interp-level traceback unless the environment variable PYPY_TB is defined. - added a debug_print() function that prints "internal stuff" in red :-) Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Thu Jan 27 11:19:26 2005 @@ -1,6 +1,7 @@ import os, sys AUTO_DEBUG = os.getenv('PYPY_DEBUG') +INTERP_LEVEL_TRACEBACK = os.getenv('PYPY_TB') class PyPyError(Exception): @@ -97,12 +98,18 @@ def print_detailed_traceback(self, space=None, file=None): """NOT_RPYTHON: Dump a nice detailed interpreter- and application-level traceback, useful to debug the interpreter.""" + import traceback, cStringIO if file is None: file = sys.stderr - for i in range(len(self.debug_excs)-1, -1, -1): - import traceback - interpr_file = LinePrefixer(file, '||') - print >> interpr_file, "Traceback (interpreter-level):" - traceback.print_tb(self.debug_excs[i][2], file=interpr_file) + f = cStringIO.StringIO() + if not INTERP_LEVEL_TRACEBACK: + print >> f, ("Traceback (interpreter-level): " + "hidden ($PYPY_TB not set)") + else: + for i in range(len(self.debug_excs)-1, -1, -1): + print >> f, "Traceback (interpreter-level):" + traceback.print_tb(self.debug_excs[i][2], file=f) + f.seek(0) + debug_print(''.join(['|| ' + line for line in f.readlines()]), file) if self.debug_excs: from pypy.tool import tb_server tb_server.publish_exc(self.debug_excs[-1]) @@ -143,24 +150,15 @@ return compile(source, '\n%s'%source, symbol, 0, 0) -class LinePrefixer: - """File-like class that inserts a prefix string - at the beginning of each line it prints.""" - def __init__(self, file, prefix): - self.file = file - self.prefix = prefix - self.linestart = True - def write(self, data): - if self.linestart: - self.file.write(self.prefix) - if data.endswith('\n'): - data = data[:-1] - self.linestart = True - else: - self.linestart = False - self.file.write(data.replace('\n', '\n'+self.prefix)) - if self.linestart: - self.file.write('\n') +def debug_print(text, file=None): + if file is None: file = sys.stderr + text = text.rstrip() + if file.isatty(): + text = ('\x1b[31m' + # ANSI color code "red" + text + + '\x1b[0m') # ANSI color code "reset" + file.write(text + '\n') + ### installing the excepthook for OperationErrors ##def operr_excepthook(exctype, value, traceback): Modified: pypy/dist/pypy/objspace/std/fake.py ============================================================================== --- pypy/dist/pypy/objspace/std/fake.py (original) +++ pypy/dist/pypy/objspace/std/fake.py Thu Jan 27 11:19:26 2005 @@ -1,4 +1,4 @@ -from pypy.interpreter.error import OperationError +from pypy.interpreter.error import OperationError, debug_print from pypy.interpreter import baseobjspace from pypy.interpreter import eval from pypy.interpreter.function import Function @@ -39,7 +39,7 @@ def really_build_fake_type(cpy_type, ignored): "NOT_RPYTHON (not remotely so!)." - print 'faking %r'%(cpy_type,) + debug_print('faking %r'%(cpy_type,)) kw = {} for s, v in cpy_type.__dict__.items(): if cpy_type is not unicode or s not in ['__add__', '__contains__']: From tismer at codespeak.net Thu Jan 27 11:52:25 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 11:52:25 +0100 (MET) Subject: [pypy-svn] r8630 - pypy/dist/pypy/translator Message-ID: <20050127105225.4BDC127B8D@code1.codespeak.net> Author: tismer Date: Thu Jan 27 11:52:25 2005 New Revision: 8630 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: adapted geninterplevel to the additional local names preserving feature. Also made it so that function names are kept. The functions just appear with a different name in the globals. Still not ready to create exceptions. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Jan 27 11:52:25 2005 @@ -142,6 +142,19 @@ else: localnames[v.name] = ret = "v%d" % len(localnames) return ret + scorepos = n.rfind("_") + print n, scorepos + if scorepos >= 0 and n[scorepos+1:].isdigit(): + name = n[:scorepos] + ret = localnames.get(v.name) + if not ret: + if wrapped: + fmt = "w_%s_%d" + else: + fmt = "%s_%d" + localnames[v.name] = ret = fmt % (name, len(localnames)) + print ret + return ret elif isinstance(v, Constant): return self.nameof(v.value, debug=('Constant in the graph of', self.currentfunc)) @@ -164,7 +177,7 @@ fmt = ("_tup = space.newtuple([%(args)s])\n" "%(res)s = space.call(%(func)s, _tup)") # see if we can optimize for a fast call. - # we justdo the very simple ones. + # we just do the very simple ones. if self.use_fast_call and (isinstance(v, Constant) and exv.startswith('gfunc_')): func = v.value @@ -276,6 +289,15 @@ else: return self.uniquename('%s_%d' % (basename, n)) + def uniquelocalname(self, basename, seennames): + basename = basename.translate(C_IDENTIFIER) + n = seennames.get(basename, 0) + seennames[basename] = n+1 + if n == 0: + return basename + else: + return self.uniquelocalname('%s_%d' % (basename, n), seennames) + def nameof_object(self, value): if type(value) is not object: #raise Exception, "nameof(%r) in %r" % (value, self.currentfunc) @@ -302,7 +324,9 @@ if value >= 0: name = 'gi_%d' % value else: - name = 'gim_%d' % abs(value) + # make sure that the type ident is completely described by + # the prefixbefore the initial '_' for easy postprocessing + name = 'gi_minus_%d' % abs(value) name = self.uniquename(name) self.initcode.append('m.%s = space.newint(%d)' % (name, value)) return name @@ -319,7 +343,9 @@ if value >= 0: name = 'glong_%s' % s else: - name = 'glongm_%d' % abs(value) + # mae sure that the type ident is completely described by + # the prefix before the initial '_' + name = 'glong_minus_%d' % abs(value) name = self.uniquename(name) self.initcode.append('m.%s = space.wrap(%s) # XXX implement long!' % (name, s)) return name @@ -425,10 +451,15 @@ content.sort() for key, value in content: if self.should_translate_attr(instance, key): - yield 'space.setattr(%s, %s, %s)' % ( - name, self.nameof(key), self.nameof(value)) + try: + yield 'space.setattr(%s, %s, %s)' % ( + name, self.nameof(key), self.nameof(value)) + except: + print >>sys.stderr, "Problem while generating %s of %r" % ( + name, instance) + raise if isinstance(instance, Exception): - # specialcase for exception instances: wrap them directly + # special-case for exception instances: wrap them directly self.initcode.append('_ins = %s()\n' 'm.%s = space.wrap(_ins)' % ( instance.__class__.__name__, name)) @@ -746,6 +777,21 @@ pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) del g[:] + + def render_docstr(self, func, indent_str, q='"""', redo=True): + doc = func.__doc__ + if doc is None: + return [] + doc2 = "" + if q in doc and redo: + doc2 = self.render_docstr(func, indent_str, "'''", False) + doc = indent_str + q + doc.replace(q, "\\"+q) + q + if not redo: + return doc # recursion case + doc = (doc, doc2)[len(doc2) < len(doc)] + assert func.__doc__ == eval(doc, {}), "check geninterplevel!!" + return [line for line in doc.split('\n')] + def gen_rpyfunction(self, func): f = self.f @@ -764,6 +810,7 @@ self.gen_global_declarations() # print header + doc_lines = self.render_docstr(func, " ") cname = self.nameof(func) assert cname.startswith('gfunc_') f_name = 'f_' + cname[6:] @@ -794,13 +841,15 @@ fast_set = dict(zip(fast_args, fast_args)) # create function declaration - name = func.__name__ + name = self.trans_funcname(func.__name__) # for argstr = ", ".join(fast_args) fast_function_header = ('def %s(space, %s):' - % (fast_name, argstr)) + % (name, argstr)) - print >> f, 'def %s(space, *args_w):' % (f_name,) - kwlist = ['"%s"' % name for name in + print >> f, 'def %s(space, *args_w):' % (name,) + for line in doc_lines: + print >> f, line + kwlist = ['"%s"' % var for var in func.func_code.co_varnames[:func.func_code.co_argcount]] print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) @@ -825,7 +874,7 @@ print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) theargs = [arg for arg in fast_args if arg != varname] - txt = ('from pypy.translator.genrpy import PyArg_ParseMini\n' + txt = ('from pypy.translator.geninterplevel import PyArg_ParseMini\n' 'm.PyArg_ParseMini = PyArg_ParseMini\n' 'from pypy.interpreter.error import OperationError\n' 'm.OperationError = OperationError') @@ -839,9 +888,12 @@ txt = ' PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' print >>f, txt % (min_number_of_args, len(positional_args)) print >> f, ' return %s(space, %s)' % (fast_name, ', '.join(fast_args)) + print >> f, '%s = globals().pop("%s")' % (f_name, name) print >> f print >> f, fast_function_header + for line in doc_lines: + print >> f, line fast_locals = [arg for arg in localnames if arg not in fast_set] if fast_locals: @@ -855,6 +907,7 @@ # print the body for line in body: print >> f, line + print >> f, '%s = globals().pop("%s")' % (fast_name, name) print >> f # print the PyMethodDef @@ -1044,6 +1097,26 @@ def somefunc(arg): pass +# XXX problem with local functions: +def randint(low, high, seed = 1234567): # really not a real random + return (seed % (high-low)) + low + +def small_loop(): + ''' this is a test for small loops. + How would we generate small blocks which call + each other? Hey, and """ is a doc string test """ + ''' + #from random import randint + # does not work. flowspace really complains on random. + # XXX we also seem to have problems with local functions + #def randint(low, high, seed = 1234567): # really not a real random + # return (seed % (high-low)) + low + + for i in range(10000): + r = randint(0, 10000) + if r > 9000: + return r + def f(a,b): ## print "start" a = [] @@ -1066,6 +1139,10 @@ class TestClass:pass def ff(a, b, c=3,*rest): + """ this is + some + docstring +""" try: try: if rest: @@ -1147,11 +1224,17 @@ res2 = struct.unpack('f', struct.pack('f',1.23)) return res1, res2 +def test_exceptions(): + from pypy.appspace import _exceptions + _exceptions.Exception() + #return [thing for thing in _exceptions.__dict__.values()] + def all_entries(): res = [func() for func in entry_points[:-1]] return res -entry_points = (lambda: f(2, 3), +entry_points = (small_loop, + lambda: f(2, 3), lambda: ff(2, 3, 5), fff, lambda: app_str_decode__String_ANY_ANY("hugo"), @@ -1161,7 +1244,8 @@ test_iter, test_strutil, test_struct, - all_entries) + test_exceptions, + all_entries) entry_point = entry_points[-2] if __name__ == "__main__": From sanxiyn at codespeak.net Thu Jan 27 12:27:31 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 27 Jan 2005 12:27:31 +0100 (MET) Subject: [pypy-svn] r8631 - pypy/dist/pypy/tool Message-ID: <20050127112731.DC04627B90@code1.codespeak.net> Author: sanxiyn Date: Thu Jan 27 12:27:31 2005 New Revision: 8631 Modified: pypy/dist/pypy/tool/option.py Log: remove dead code Modified: pypy/dist/pypy/tool/option.py ============================================================================== --- pypy/dist/pypy/tool/option.py (original) +++ pypy/dist/pypy/tool/option.py Thu Jan 27 12:27:31 2005 @@ -25,17 +25,6 @@ '-T', action="callback", callback=objspace_callback, callback_args=("trivial",), help="run in trivial object space")) - """ - unneeded options that don't even make sense any more? - options.append(make_option( - '-P', action="callback", - callback=objspace_callback, callback_args=("trace",), - help="run in trace object space")) - options.append(make_option( - '-A', action="callback", - callback=objspace_callback, callback_args=("ann",), - help="run in annotation object space")) - """ options.append(make_option( '-v', action="count", dest="verbose", help="verbose")) From sanxiyn at codespeak.net Thu Jan 27 13:30:04 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 27 Jan 2005 13:30:04 +0100 (MET) Subject: [pypy-svn] r8632 - in pypy/dist/pypy: interpreter tool Message-ID: <20050127123004.02B8627B8E@code1.codespeak.net> Author: sanxiyn Date: Thu Jan 27 13:30:04 2005 New Revision: 8632 Modified: pypy/dist/pypy/interpreter/error.py pypy/dist/pypy/interpreter/interactive.py pypy/dist/pypy/interpreter/main.py pypy/dist/pypy/interpreter/py.py pypy/dist/pypy/tool/option.py pypy/dist/pypy/tool/pytestsupport.py Log: 1) pypy -v was not used and broken 2) So let's use -v for PYPY_TB 3) pypy.interpreter.error.PyPyError removed 4) Use errorstr() in both interp and appl level traceback 5) pypy.main has main() no more used Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Thu Jan 27 13:30:04 2005 @@ -1,14 +1,6 @@ import os, sys AUTO_DEBUG = os.getenv('PYPY_DEBUG') -INTERP_LEVEL_TRACEBACK = os.getenv('PYPY_TB') - - -class PyPyError(Exception): - "Raise this when you encounter an exceptional situation in PyPy itself." - def __init__(self, space, operationerr): - self.space = space - self.operationerr = operationerr class OperationError(Exception): @@ -44,10 +36,24 @@ def errorstr(self, space): "NOT_RPYTHON: The exception class and value, as a string." - exc_type = space.str_w( - space.getattr(self.w_type, space.wrap('__name__'))) - exc_value = space.str_w(space.str(self.w_value)) - return '%s: %s' % (exc_type, exc_value) + if space is None: + exc_typename = str(self.w_type) + exc_value = self.w_value + else: + w = space.wrap + if space.is_true(space.is_(space.type(self.w_type), space.w_str)): + exc_typename = space.str_w(self.w_type) + else: + exc_typename = space.str_w( + space.getattr(self.w_type, w('__name__'))) + if self.w_value == space.w_None: + exc_value = None + else: + exc_value = space.str_w(space.str(self.w_value)) + if not exc_value: + return exc_typename + else: + return '%s: %s' % (exc_typename, exc_value) def getframe(self): "The frame this exception was raised in, or None." @@ -101,38 +107,16 @@ import traceback, cStringIO if file is None: file = sys.stderr f = cStringIO.StringIO() - if not INTERP_LEVEL_TRACEBACK: - print >> f, ("Traceback (interpreter-level): " - "hidden ($PYPY_TB not set)") - else: - for i in range(len(self.debug_excs)-1, -1, -1): - print >> f, "Traceback (interpreter-level):" - traceback.print_tb(self.debug_excs[i][2], file=f) + for i in range(len(self.debug_excs)-1, -1, -1): + print >> f, "Traceback (interpreter-level):" + traceback.print_tb(self.debug_excs[i][2], file=f) f.seek(0) debug_print(''.join(['|| ' + line for line in f.readlines()]), file) if self.debug_excs: from pypy.tool import tb_server tb_server.publish_exc(self.debug_excs[-1]) self.print_app_tb_only(file) - if space is None: - exc_typename = str(self.w_type) - exc_value = self.w_value - else: - w = space.wrap - if space.is_true(space.is_(space.type(self.w_type), space.w_str)): - exc_typename = space.str_w(self.w_type) - else: - exc_typename = space.str_w( - space.getattr(self.w_type, w('__name__'))) - if self.w_value == space.w_None: - exc_value = None - else: - exc_value = space.str_w(space.str(self.w_value)) - print >> file, '(application-level)', - if not exc_value: - print >> file, exc_typename - else: - print >> file, exc_typename+':', exc_value + print >> file, '(application-level)', self.errorstr(space) if AUTO_DEBUG: import debug debug.fire(self) Modified: pypy/dist/pypy/interpreter/interactive.py ============================================================================== --- pypy/dist/pypy/interpreter/interactive.py (original) +++ pypy/dist/pypy/interpreter/interactive.py Thu Jan 27 13:30:04 2005 @@ -1,14 +1,16 @@ import autopath +from pypy.interpreter import error from pypy.interpreter import executioncontext, baseobjspace import sys import code class PyPyConsole(code.InteractiveConsole): - def __init__(self, objspace): + def __init__(self, objspace, verbose=0): code.InteractiveConsole.__init__(self) self.space = objspace + self.verbose = verbose self.ec = executioncontext.ExecutionContext(self.space) self.w_globals = self.ec.make_standard_w_globals() self.space.setitem(self.w_globals, @@ -54,13 +56,16 @@ pycode = PyCode(self.space)._from_code(code) try: pycode.exec_code(self.space, self.w_globals, self.w_globals) - except baseobjspace.OperationError, operationerr: + except error.OperationError, operationerr: space = self.space if operationerr.match(space, space.w_SystemExit): # XXX fetch the exit code from somewhere inside the w_SystemExit raise SystemExit # XXX insert exception info into the application-level sys.last_xxx - operationerr.print_detailed_traceback(space) + if self.verbose: + operationerr.print_detailed_traceback(space) + else: + operationerr.print_application_traceback(space) # for debugging convenience we also insert the exception into # the interpreter-level sys.last_xxx sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info() Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Thu Jan 27 13:30:04 2005 @@ -1,7 +1,6 @@ import autopath -from pypy.tool import option from pypy.interpreter import executioncontext, module -from pypy.interpreter.error import OperationError, PyPyError +from pypy.interpreter.error import OperationError import sys def _run_eval_string(source, filename, space, eval): @@ -9,7 +8,7 @@ cmd = 'eval' else: cmd = 'exec' - + try: if space is None: from pypy.objspace.std import StdObjSpace @@ -31,7 +30,7 @@ except OperationError, operationerr: operationerr.record_interpreter_traceback() - raise PyPyError(space, operationerr) + raise def run_string(source, filename='', space=None): _run_eval_string(source, filename, space, False) @@ -44,19 +43,3 @@ print "Running %r with %r" % (filename, space) istring = open(filename).read() run_string(istring, filename, space) - -def main(argv=None): - if argv is None: - argv = sys.argv - - argv = option.process_options(option.get_standard_options(), - option.Options) - space = option.objspace() - try: - run_file(argv[0], space) - except PyPyError, pypyerr: - pypyerr.operationerr.print_detailed_traceback(pypyerr.space) - -if __name__ == '__main__': - main(sys.argv) - Modified: pypy/dist/pypy/interpreter/py.py ============================================================================== --- pypy/dist/pypy/interpreter/py.py (original) +++ pypy/dist/pypy/interpreter/py.py Thu Jan 27 13:30:04 2005 @@ -8,14 +8,20 @@ from pypy.tool import option from pypy.tool.optik import make_option from pypy.interpreter import main, interactive, error -import sys +import os, sys class Options(option.Options): + verbose = os.getenv('PYPY_TB') interactive = 0 command = [] def get_main_options(): options = option.get_standard_options() + + options.append(make_option( + '-v', action='store_true', dest='verbose', + help='show verbose interpreter-level traceback')) + options.append(make_option( '-i', action="store_true", dest="interactive", help="inspect interactively after running script")) @@ -48,22 +54,22 @@ args = ['-c'] + Options.command[1:] for arg in args: space.call_method(space.sys.w_argv, 'append', space.wrap(arg)) - if Options.command: - try: + try: + if Options.command: main.run_string(Options.command[0], '', space) - except error.PyPyError, pypyerr: - pypyerr.operationerr.print_detailed_traceback(pypyerr.space) - elif args: - try: + elif args: main.run_file(args[0], space) - except error.PyPyError, pypyerr: - pypyerr.operationerr.print_detailed_traceback(pypyerr.space) - else: - space.call_method(space.sys.w_argv, 'append', space.wrap('')) - go_interactive = 1 - banner = None + else: + space.call_method(space.sys.w_argv, 'append', space.wrap('')) + go_interactive = 1 + banner = None + except error.OperationError, operationerr: + if Options.verbose: + operationerr.print_detailed_traceback(space) + else: + operationerr.print_application_traceback(space) if go_interactive: - con = interactive.PyPyConsole(space) + con = interactive.PyPyConsole(space, Options.verbose) if banner == '': banner = '%s / %s'%(con.__class__.__name__, space.__class__.__name__) Modified: pypy/dist/pypy/tool/option.py ============================================================================== --- pypy/dist/pypy/tool/option.py (original) +++ pypy/dist/pypy/tool/option.py Thu Jan 27 13:30:04 2005 @@ -3,7 +3,6 @@ make_option = optik.make_option class Options: - verbose = 0 showwarning = 0 spaces = [] @@ -26,9 +25,6 @@ callback=objspace_callback, callback_args=("trivial",), help="run in trivial object space")) options.append(make_option( - '-v', action="count", dest="verbose", - help="verbose")) - options.append(make_option( '-w', action="store_true", dest="showwarning", help="enable warnings (disabled by default)")) options.append(make_option( Modified: pypy/dist/pypy/tool/pytestsupport.py ============================================================================== --- pypy/dist/pypy/tool/pytestsupport.py (original) +++ pypy/dist/pypy/tool/pytestsupport.py Thu Jan 27 13:30:04 2005 @@ -44,7 +44,7 @@ self.traceback = AppTraceback(self.operr.application_traceback) def __str__(self): - return '[app-level] ' + self.operr.errorstr(self.space) + return '(application-level) ' + self.operr.errorstr(self.space) class AppTracebackEntry(py.code.Traceback.Entry): exprinfo = None From sanxiyn at codespeak.net Thu Jan 27 13:43:01 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 27 Jan 2005 13:43:01 +0100 (MET) Subject: [pypy-svn] r8633 - pypy/dist/pypy/appspace Message-ID: <20050127124301.08AEF27B8E@code1.codespeak.net> Author: sanxiyn Date: Thu Jan 27 13:43:00 2005 New Revision: 8633 Added: pypy/dist/pypy/appspace/re.py Log: Regex is currently not working. Die gloriously. Added: pypy/dist/pypy/appspace/re.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/re.py Thu Jan 27 13:43:00 2005 @@ -0,0 +1,17 @@ +class Pattern: + def __init__(self, pattern, flags): + print 'regex', pattern + print 'killed' + raise SystemExit + +_cache = {} + +def compile(pattern, flags=0): + if (pattern, flags) in _cache: + return _cache[pattern, flags] + compiled = Pattern(pattern, flags) + _cache[pattern, flags] = compiled + return compiled + +def match(pattern, string, flags=0): + return compile(pattern, flags).match(string) From sanxiyn at codespeak.net Thu Jan 27 13:51:34 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 27 Jan 2005 13:51:34 +0100 (MET) Subject: [pypy-svn] r8634 - pypy/dist/pypy/appspace Message-ID: <20050127125134.DF74E27B4A@code1.codespeak.net> Author: sanxiyn Date: Thu Jan 27 13:51:34 2005 New Revision: 8634 Modified: pypy/dist/pypy/appspace/re.py Log: better bozo re module Modified: pypy/dist/pypy/appspace/re.py ============================================================================== --- pypy/dist/pypy/appspace/re.py (original) +++ pypy/dist/pypy/appspace/re.py Thu Jan 27 13:51:34 2005 @@ -1,3 +1,16 @@ +# From CPython +def escape(pattern): + "Escape all non-alphanumeric characters in pattern." + s = list(pattern) + for i in range(len(pattern)): + c = pattern[i] + if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"): + if c == "\000": + s[i] = "\\000" + else: + s[i] = "\\" + c + return ''.join(s) + class Pattern: def __init__(self, pattern, flags): print 'regex', pattern From hpk at codespeak.net Thu Jan 27 14:00:48 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 27 Jan 2005 14:00:48 +0100 (MET) Subject: [pypy-svn] r8635 - pypy/dist/pypy/appspace Message-ID: <20050127130048.5163627B5A@code1.codespeak.net> Author: hpk Date: Thu Jan 27 14:00:48 2005 New Revision: 8635 Modified: pypy/dist/pypy/appspace/sre_parse.py Log: import from python2.4 (unmodified) hum, but we need to do this better somehow Modified: pypy/dist/pypy/appspace/sre_parse.py ============================================================================== --- pypy/dist/pypy/appspace/sre_parse.py (original) +++ pypy/dist/pypy/appspace/sre_parse.py Thu Jan 27 14:00:48 2005 @@ -12,8 +12,7 @@ # XXX: show string offset and offending character for all errors -# this module works under 1.5.2 and later. don't use string methods -import string, sys +import sys from sre_constants import * @@ -63,13 +62,6 @@ "u": SRE_FLAG_UNICODE, } -# figure out best way to convert hex/octal numbers to integers -try: - int("10", 8) - atoi = int # 2.0 and later -except TypeError: - atoi = string.atoi # 1.5.2 - class Pattern: # master pattern object. keeps track of global attributes def __init__(self): @@ -103,6 +95,7 @@ self.width = None def dump(self, level=0): nl = 1 + seqtypes = type(()), type([]) for op, av in self.data: print level*" " + op,; nl = 0 if op == "in": @@ -118,7 +111,7 @@ print level*" " + "or" a.dump(level+1); nl = 1 i = i + 1 - elif type(av) in (type(()), type([])): + elif type(av) in seqtypes: for a in av: if isinstance(a, SubPattern): if not nl: print @@ -132,17 +125,14 @@ return repr(self.data) def __len__(self): return len(self.data) - def __iter__(self): - return iter(self.data) def __delitem__(self, index): del self.data[index] def __getitem__(self, index): - if isinstance(index, slice): - return SubPattern(self.pattern, self.data[index]) - else: - return self.data[index] + return self.data[index] def __setitem__(self, index, code): self.data[index] = code + def __getslice__(self, start, stop): + return SubPattern(self.pattern, self.data[start:stop]) def insert(self, index, code): self.data.insert(index, code) def append(self, code): @@ -152,6 +142,8 @@ if self.width: return self.width lo = hi = 0L + UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY) + REPEATCODES = (MIN_REPEAT, MAX_REPEAT) for op, av in self.data: if op is BRANCH: i = sys.maxint @@ -170,11 +162,11 @@ i, j = av[1].getwidth() lo = lo + i hi = hi + j - elif op in (MIN_REPEAT, MAX_REPEAT): + elif op in REPEATCODES: i, j = av[2].getwidth() lo = lo + long(i) * av[0] hi = hi + long(j) * av[1] - elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY): + elif op in UNITCODES: lo = lo + 1 hi = hi + 1 elif op == SUCCESS: @@ -225,21 +217,11 @@ # check that group name is a valid string if not isident(name[0]): return False - for char in name: + for char in name[1:]: if not isident(char) and not isdigit(char): return False return True -def _group(escape, groups): - # check if the escape string represents a valid group - try: - gid = atoi(escape[1:]) - if gid and gid < groups: - return gid - except ValueError: - pass - return None # not a valid group - def _class_escape(source, escape): # handle escape code inside character class code = ESCAPES.get(escape) @@ -249,20 +231,23 @@ if code: return code try: - if escape[1:2] == "x": + c = escape[1:2] + if c == "x": # hexadecimal escape (exactly two digits) while source.next in HEXDIGITS and len(escape) < 4: escape = escape + source.get() escape = escape[2:] if len(escape) != 2: raise error, "bogus escape: %s" % repr("\\" + escape) - return LITERAL, atoi(escape, 16) & 0xff - elif escape[1:2] in OCTDIGITS: + return LITERAL, int(escape, 16) & 0xff + elif c in OCTDIGITS: # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 5: + while source.next in OCTDIGITS and len(escape) < 4: escape = escape + source.get() escape = escape[1:] - return LITERAL, atoi(escape, 8) & 0xff + return LITERAL, int(escape, 8) & 0xff + elif c in DIGITS: + raise error, "bogus escape: %s" % repr(escape) if len(escape) == 2: return LITERAL, ord(escape[1]) except ValueError: @@ -278,19 +263,20 @@ if code: return code try: - if escape[1:2] == "x": + c = escape[1:2] + if c == "x": # hexadecimal escape while source.next in HEXDIGITS and len(escape) < 4: escape = escape + source.get() if len(escape) != 4: raise ValueError - return LITERAL, atoi(escape[2:], 16) & 0xff - elif escape[1:2] == "0": + return LITERAL, int(escape[2:], 16) & 0xff + elif c == "0": # octal escape while source.next in OCTDIGITS and len(escape) < 4: escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - elif escape[1:2] in DIGITS: + return LITERAL, int(escape[1:], 8) & 0xff + elif c in DIGITS: # octal escape *or* decimal group reference (sigh) if source.next in DIGITS: escape = escape + source.get() @@ -298,10 +284,10 @@ source.next in OCTDIGITS): # got three octal digits; this is an octal escape escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - # got at least one decimal digit; this is a group reference - group = _group(escape, state.groups) - if group: + return LITERAL, int(escape[1:], 8) & 0xff + # not an octal escape, so this is a group reference + group = int(escape[1:]) + if group < state.groups: if not state.checkgroup(group): raise error, "cannot refer to open group" return GROUPREF, group @@ -316,13 +302,15 @@ # parse an alternation: a|b|c items = [] + itemsappend = items.append + sourcematch = source.match while 1: - items.append(_parse(source, state)) - if source.match("|"): + itemsappend(_parse(source, state)) + if sourcematch("|"): continue if not nested: break - if not source.next or source.match(")", 0): + if not source.next or sourcematch(")", 0): break else: raise error, "pattern not properly closed" @@ -331,6 +319,7 @@ return items[0] subpattern = SubPattern(state) + subpatternappend = subpattern.append # check if all items share a common prefix while 1: @@ -347,7 +336,7 @@ # move it out of the branch for item in items: del item[0] - subpattern.append(prefix) + subpatternappend(prefix) continue # check next one break @@ -359,24 +348,48 @@ # we can store this as a character set instead of a # branch (the compiler may optimize this even more) set = [] + setappend = set.append for item in items: - set.append(item[0]) - subpattern.append((IN, set)) + setappend(item[0]) + subpatternappend((IN, set)) return subpattern subpattern.append((BRANCH, (None, items))) return subpattern +def _parse_sub_cond(source, state, condgroup): + item_yes = _parse(source, state) + if source.match("|"): + item_no = _parse(source, state) + if source.match("|"): + raise error, "conditional backref with more than two branches" + else: + item_no = None + if source.next and not source.match(")", 0): + raise error, "pattern not properly closed" + subpattern = SubPattern(state) + subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no))) + return subpattern + def _parse(source, state): # parse a simple pattern - subpattern = SubPattern(state) + # precompute constants into local variables + subpatternappend = subpattern.append + sourceget = source.get + sourcematch = source.match + _len = len + PATTERNENDERS = ("|", ")") + ASSERTCHARS = ("=", "!", "<") + LOOKBEHINDASSERTCHARS = ("=", "!") + REPEATCODES = (MIN_REPEAT, MAX_REPEAT) + while 1: - if source.next in ("|", ")"): + if source.next in PATTERNENDERS: break # end of subpattern - this = source.get() + this = sourceget() if this is None: break # end of pattern @@ -386,25 +399,26 @@ continue if this == "#": while 1: - this = source.get() + this = sourceget() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: - subpattern.append((LITERAL, ord(this))) + subpatternappend((LITERAL, ord(this))) elif this == "[": # character set set = [] -## if source.match(":"): + setappend = set.append +## if sourcematch(":"): ## pass # handle character classes - if source.match("^"): - set.append((NEGATE, None)) + if sourcematch("^"): + setappend((NEGATE, None)) # check remaining characters start = set[:] while 1: - this = source.get() + this = sourceget() if this == "]" and set != start: break elif this and this[0] == "\\": @@ -413,14 +427,14 @@ code1 = LITERAL, ord(this) else: raise error, "unexpected end of regular expression" - if source.match("-"): + if sourcematch("-"): # potential range - this = source.get() + this = sourceget() if this == "]": if code1[0] is IN: code1 = code1[1][0] - set.append(code1) - set.append((LITERAL, ord("-"))) + setappend(code1) + setappend((LITERAL, ord("-"))) break elif this: if this[0] == "\\": @@ -433,22 +447,22 @@ hi = code2[1] if hi < lo: raise error, "bad character range" - set.append((RANGE, (lo, hi))) + setappend((RANGE, (lo, hi))) else: raise error, "unexpected end of regular expression" else: if code1[0] is IN: code1 = code1[1][0] - set.append(code1) + setappend(code1) # XXX: should move set optimization to compiler! - if len(set)==1 and set[0][0] is LITERAL: - subpattern.append(set[0]) # optimization - elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: - subpattern.append((NOT_LITERAL, set[1][1])) # optimization + if _len(set)==1 and set[0][0] is LITERAL: + subpatternappend(set[0]) # optimization + elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: + subpatternappend((NOT_LITERAL, set[1][1])) # optimization else: # XXX: should add charmap optimization here - subpattern.append((IN, set)) + subpatternappend((IN, set)) elif this and this[0] in REPEAT_CHARS: # repeat previous item @@ -465,19 +479,19 @@ lo = hi = "" while source.next in DIGITS: lo = lo + source.get() - if source.match(","): + if sourcematch(","): while source.next in DIGITS: - hi = hi + source.get() + hi = hi + sourceget() else: hi = lo - if not source.match("}"): - subpattern.append((LITERAL, ord(this))) + if not sourcematch("}"): + subpatternappend((LITERAL, ord(this))) source.seek(here) continue if lo: - min = atoi(lo) + min = int(lo) if hi: - max = atoi(hi) + max = int(hi) if max < min: raise error, "bad repeat interval" else: @@ -487,31 +501,32 @@ item = subpattern[-1:] else: item = None - if not item or (len(item) == 1 and item[0][0] == AT): + if not item or (_len(item) == 1 and item[0][0] == AT): raise error, "nothing to repeat" - if item[0][0] in (MIN_REPEAT, MAX_REPEAT): + if item[0][0] in REPEATCODES: raise error, "multiple repeat" - if source.match("?"): + if sourcematch("?"): subpattern[-1] = (MIN_REPEAT, (min, max, item)) else: subpattern[-1] = (MAX_REPEAT, (min, max, item)) elif this == ".": - subpattern.append((ANY, None)) + subpatternappend((ANY, None)) elif this == "(": group = 1 name = None - if source.match("?"): + condgroup = None + if sourcematch("?"): group = 0 # options - if source.match("P"): + if sourcematch("P"): # python extensions - if source.match("<"): + if sourcematch("<"): # named group: skip forward to end of name name = "" while 1: - char = source.get() + char = sourceget() if char is None: raise error, "unterminated name" if char == ">": @@ -520,11 +535,11 @@ group = 1 if not isname(name): raise error, "bad character in group name" - elif source.match("="): + elif sourcematch("="): # named backreference name = "" while 1: - char = source.get() + char = sourceget() if char is None: raise error, "unterminated name" if char == ")": @@ -535,48 +550,68 @@ gid = state.groupdict.get(name) if gid is None: raise error, "unknown group name" - subpattern.append((GROUPREF, gid)) + subpatternappend((GROUPREF, gid)) continue else: - char = source.get() + char = sourceget() if char is None: raise error, "unexpected end of pattern" raise error, "unknown specifier: ?P%s" % char - elif source.match(":"): + elif sourcematch(":"): # non-capturing group group = 2 - elif source.match("#"): + elif sourcematch("#"): # comment while 1: if source.next is None or source.next == ")": break - source.get() - if not source.match(")"): + sourceget() + if not sourcematch(")"): raise error, "unbalanced parenthesis" continue - elif source.next in ("=", "!", "<"): + elif source.next in ASSERTCHARS: # lookahead assertions - char = source.get() + char = sourceget() dir = 1 if char == "<": - if source.next not in ("=", "!"): + if source.next not in LOOKBEHINDASSERTCHARS: raise error, "syntax error" dir = -1 # lookbehind - char = source.get() + char = sourceget() p = _parse_sub(source, state) - if not source.match(")"): + if not sourcematch(")"): raise error, "unbalanced parenthesis" if char == "=": - subpattern.append((ASSERT, (dir, p))) + subpatternappend((ASSERT, (dir, p))) else: - subpattern.append((ASSERT_NOT, (dir, p))) + subpatternappend((ASSERT_NOT, (dir, p))) continue + elif sourcematch("("): + # conditional backreference group + condname = "" + while 1: + char = sourceget() + if char is None: + raise error, "unterminated name" + if char == ")": + break + condname = condname + char + group = 2 + if isname(condname): + condgroup = state.groupdict.get(condname) + if condgroup is None: + raise error, "unknown group name" + else: + try: + condgroup = int(condname) + except ValueError: + raise error, "bad character in group name" else: # flags if not source.next in FLAGS: raise error, "unexpected end of pattern" while source.next in FLAGS: - state.flags = state.flags | FLAGS[source.get()] + state.flags = state.flags | FLAGS[sourceget()] if group: # parse group contents if group == 2: @@ -584,15 +619,18 @@ group = None else: group = state.opengroup(name) - p = _parse_sub(source, state) - if not source.match(")"): + if condgroup: + p = _parse_sub_cond(source, state, condgroup) + else: + p = _parse_sub(source, state) + if not sourcematch(")"): raise error, "unbalanced parenthesis" if group is not None: state.closegroup(group) - subpattern.append((SUBPATTERN, (group, p))) + subpatternappend((SUBPATTERN, (group, p))) else: while 1: - char = source.get() + char = sourceget() if char is None: raise error, "unexpected end of pattern" if char == ")": @@ -600,14 +638,14 @@ raise error, "unknown extension" elif this == "^": - subpattern.append((AT, AT_BEGINNING)) + subpatternappend((AT, AT_BEGINNING)) elif this == "$": subpattern.append((AT, AT_END)) elif this and this[0] == "\\": code = _escape(source, this, state) - subpattern.append(code) + subpatternappend(code) else: raise error, "parser error" @@ -646,29 +684,31 @@ # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) + sget = s.get p = [] a = p.append - def literal(literal, p=p): + def literal(literal, p=p, pappend=a): if p and p[-1][0] is LITERAL: p[-1] = LITERAL, p[-1][1] + literal else: - p.append((LITERAL, literal)) + pappend((LITERAL, literal)) sep = source[:0] if type(sep) is type(""): makechar = chr else: makechar = unichr while 1: - this = s.get() + this = sget() if this is None: break # end of replacement string if this and this[0] == "\\": # group - if this == "\\g": + c = this[1:2] + if c == "g": name = "" if s.match("<"): while 1: - char = s.get() + char = sget() if char is None: raise error, "unterminated group name" if char == ">": @@ -677,7 +717,9 @@ if not name: raise error, "bad group name" try: - index = atoi(name) + index = int(name) + if index < 0: + raise error, "negative group number" except ValueError: if not isname(name): raise error, "bad character in group name" @@ -686,26 +728,23 @@ except KeyError: raise IndexError, "unknown group name" a((MARK, index)) - elif len(this) > 1 and this[1] in DIGITS: - code = None - while 1: - group = _group(this, pattern.groups+1) - if group: - if (s.next not in DIGITS or - not _group(this + s.next, pattern.groups+1)): - code = MARK, group - break - elif s.next in OCTDIGITS: - this = this + s.get() - else: - break - if not code: - this = this[1:] - code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff) - if code[0] is LITERAL: - literal(code[1]) - else: - a(code) + elif c == "0": + if s.next in OCTDIGITS: + this = this + sget() + if s.next in OCTDIGITS: + this = this + sget() + literal(makechar(int(this[1:], 8) & 0xff)) + elif c in DIGITS: + isoctal = False + if s.next in DIGITS: + this = this + sget() + if (c in OCTDIGITS and this[2] in OCTDIGITS and + s.next in OCTDIGITS): + this = this + sget() + isoctal = True + literal(makechar(int(this[1:], 8) & 0xff)) + if not isoctal: + a((MARK, int(this[1:]))) else: try: this = makechar(ESCAPES[this][1]) @@ -717,13 +756,14 @@ # convert template to groups and literals lists i = 0 groups = [] - literals = [] + groupsappend = groups.append + literals = [None] * len(p) for c, s in p: if c is MARK: - groups.append((i, s)) - literals.append(None) + groupsappend((i, s)) + # literal[i] is already None else: - literals.append(s) + literals[i] = s i = i + 1 return groups, literals @@ -736,7 +776,7 @@ for index, group in groups: literals[index] = s = g(group) if s is None: - raise IndexError + raise error, "unmatched group" except IndexError: - raise error, "empty group" - return string.join(literals, sep) + raise error, "invalid group reference" + return sep.join(literals) From sanxiyn at codespeak.net Thu Jan 27 14:16:28 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 27 Jan 2005 14:16:28 +0100 (MET) Subject: [pypy-svn] r8636 - pypy/dist/pypy/appspace Message-ID: <20050127131628.EE15C27B5A@code1.codespeak.net> Author: sanxiyn Date: Thu Jan 27 14:16:28 2005 New Revision: 8636 Added: pypy/dist/pypy/appspace/dumbre.py pypy/dist/pypy/appspace/plexre.py Modified: pypy/dist/pypy/appspace/re.py Log: plexre, Plex-based regex implementation. "gloriously dying" implementation moved to dumbre. Now, you can edit re.py to enable plexre. And it let pickle import and run, unmodified! Added: pypy/dist/pypy/appspace/dumbre.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/dumbre.py Thu Jan 27 14:16:28 2005 @@ -0,0 +1,5 @@ +class Pattern: + def __init__(self, pattern, flags): + print 'regex', pattern + print 'killed' + raise SystemExit Added: pypy/dist/pypy/appspace/plexre.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/plexre.py Thu Jan 27 14:16:28 2005 @@ -0,0 +1,15 @@ +from StringIO import StringIO +from Pyrex.Plex import Scanner, Lexicon, Traditional, Errors +class Pattern: + def __init__(self, pattern, flags): + compiled = Traditional.re(pattern) + lexicon = Lexicon([(compiled, None)]) + self.lexicon = lexicon + def match(self, string): + stream = StringIO(string) + scanner = Scanner(self.lexicon, stream) + try: + scanner.read() + return 1 + except Errors.UnrecognizedInput: + return 0 Modified: pypy/dist/pypy/appspace/re.py ============================================================================== --- pypy/dist/pypy/appspace/re.py (original) +++ pypy/dist/pypy/appspace/re.py Thu Jan 27 14:16:28 2005 @@ -1,3 +1,7 @@ +from dumbre import Pattern +# from plexre import Pattern + + # From CPython def escape(pattern): "Escape all non-alphanumeric characters in pattern." @@ -11,11 +15,6 @@ s[i] = "\\" + c return ''.join(s) -class Pattern: - def __init__(self, pattern, flags): - print 'regex', pattern - print 'killed' - raise SystemExit _cache = {} From tismer at codespeak.net Thu Jan 27 14:21:42 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 14:21:42 +0100 (MET) Subject: [pypy-svn] r8637 - pypy/dist/pypy/translator Message-ID: <20050127132142.8135027B5A@code1.codespeak.net> Author: tismer Date: Thu Jan 27 14:21:42 2005 New Revision: 8637 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: trying hard to create something that can be plugged into the kernel and implements all exceptions. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Jan 27 14:21:42 2005 @@ -94,7 +94,10 @@ except TypeError: # not hashable if arg not in self: list.append(self, arg) - + def appendnew(self, arg): + "always append" + list.append(self, arg) + class GenRpy: def __init__(self, translator, modname=None): self.translator = translator @@ -143,7 +146,6 @@ localnames[v.name] = ret = "v%d" % len(localnames) return ret scorepos = n.rfind("_") - print n, scorepos if scorepos >= 0 and n[scorepos+1:].isdigit(): name = n[:scorepos] ret = localnames.get(v.name) @@ -153,7 +155,6 @@ else: fmt = "%s_%d" localnames[v.name] = ret = fmt % (name, len(localnames)) - print ret return ret elif isinstance(v, Constant): return self.nameof(v.value, @@ -558,8 +559,16 @@ name, self.nameof(key), self.nameof(value)) baseargs = ", ".join(basenames) - self.initcode.append('_dic = space.newdict([])\n' - '_bases = space.newtuple([%(bases)s])\n' + if cls.__doc__ is not None: + sdoc = self.nameof("__doc__") + lines = list(self.render_docstr(cls, "_doc = space.wrap(")) + lines[-1] +=")" + self.initcode.extend(lines) + self.initcode.appendnew('_dic = space.newdict([(%s, %s)])' % ( + self.nameof("__doc__"), "_doc") ) + else: + self.initcode.appendnew('_dic = space.newdict([])') + self.initcode.append('_bases = space.newtuple([%(bases)s])\n' '_args = space.newtuple([%(name)s, _bases, _dic])\n' 'm.%(klass)s = space.call(%(meta)s, _args)' % {"bases": baseargs, @@ -782,14 +791,13 @@ doc = func.__doc__ if doc is None: return [] - doc2 = "" + doc = indent_str + q + doc.replace(q, "\\"+q) + q + doc2 = doc if q in doc and redo: doc2 = self.render_docstr(func, indent_str, "'''", False) - doc = indent_str + q + doc.replace(q, "\\"+q) + q if not redo: return doc # recursion case doc = (doc, doc2)[len(doc2) < len(doc)] - assert func.__doc__ == eval(doc, {}), "check geninterplevel!!" return [line for line in doc.split('\n')] def gen_rpyfunction(self, func): @@ -1224,16 +1232,28 @@ res2 = struct.unpack('f', struct.pack('f',1.23)) return res1, res2 -def test_exceptions(): +def test_exceptions_helper(): + def demoduliseDict(mod): + # get the raw dict without module stuff like __builtins__ + dic = mod.__dict__.copy() + bad = ("__builtins__", ) # anything else? + for name in bad: + if name in dic: + del dic[name] + return dic from pypy.appspace import _exceptions - _exceptions.Exception() - #return [thing for thing in _exceptions.__dict__.values()] - + a = demoduliseDict(_exceptions) + def test_exceptions(): + """ enumerate all exceptions """ + return a.keys() + #return [thing for thing in _exceptions.__dict__.values()] + return test_exceptions + def all_entries(): - res = [func() for func in entry_points[:-1]] + res = [func() for func in entrypoints[:-1]] return res -entry_points = (small_loop, +entrypoints = (small_loop, lambda: f(2, 3), lambda: ff(2, 3, 5), fff, @@ -1244,9 +1264,9 @@ test_iter, test_strutil, test_struct, - test_exceptions, + test_exceptions_helper, all_entries) -entry_point = entry_points[-2] +entrypoint = entrypoints[-2] if __name__ == "__main__": import os, sys @@ -1257,7 +1277,9 @@ if appdir not in sys.path: sys.path.insert(0, appdir) - t = Translator(entry_point, verbose=False, simplifying=True) + if entrypoint.__name__.endswith("_helper"): + entrypoint = entrypoint() + t = Translator(entrypoint, verbose=False, simplifying=True) gen = GenRpy(t) gen.use_fast_call = True import pypy.appspace.generated as tmp From pedronis at codespeak.net Thu Jan 27 17:37:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 27 Jan 2005 17:37:35 +0100 (MET) Subject: [pypy-svn] r8638 - pypy/dist/pypy/translator/test Message-ID: <20050127163735.EB5CB27B8A@code1.codespeak.net> Author: pedronis Date: Thu Jan 27 17:37:35 2005 New Revision: 8638 Modified: pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: small test reproducing the for the annotator confusing setup of BultinCode and BuiltinFrame subclasses Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Thu Jan 27 17:37:35 2005 @@ -735,3 +735,44 @@ return (e, f) return (e, Exc2()) return (Exc(), Exc2()) + + +class BltinCode: + def __init__(self, func, framecls): + self.func = func + self.framecls = framecls + + def call(self, x): + return self.framecls(self).run(x) + +class BltinFrame: + def __init__(self, code): + self.code = code + +def bltin_code_frame_f(x): + return x + +def bltin_code_frame_g(x): + return x + +class FBltinFrame(BltinFrame): + + def run(self, x): + return self.code.func(x) + +class GBltinFrame(BltinFrame): + + def run(self, x): + return self.code.func(x) + +bltin_code_for_f = BltinCode(bltin_code_frame_f, FBltinFrame) +bltin_code_for_g = BltinCode(bltin_code_frame_g, GBltinFrame) + +def bltin_code_frame_confusion(): + a = bltin_code_for_f.call(0) + a1 = bltin_code_for_f.call(1) + b = bltin_code_for_g.call("a") + b1 = bltin_code_for_g.call("b") + return (a,a1,b,b1) + + Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Thu Jan 27 17:37:35 2005 @@ -1,5 +1,6 @@ import autopath +import py.test from pypy.tool.udir import udir from pypy.translator.annrpython import RPythonAnnotator, annmodel @@ -487,7 +488,18 @@ a = RPythonAnnotator() s = a.build_types(snippet.slice_union, [int]) assert isinstance(s, annmodel.SomeSlice) - + + def test_bltin_code_frame_confusion(self): + a = RPythonAnnotator() + s = a.build_types(snippet.bltin_code_frame_confusion,[]) + assert isinstance(s, annmodel.SomeTuple) + is_int = isinstance(s.items[0], annmodel.SomeInteger) + if not is_int: + py.test.skip("annotator confused with bltin code/frame setup") + assert isinstance(s.items[1], annmodel.SomeInteger) + assert isinstance(s.items[2], annmodel.SomeString) + assert isinstance(s.items[3], annmodel.SomeString) + def g(n): return [0,1,2,n] From hpk at codespeak.net Thu Jan 27 17:53:03 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 27 Jan 2005 17:53:03 +0100 (MET) Subject: [pypy-svn] r8639 - in pypy/dist/lib-python-2.3.4: . bsddb bsddb/test compiler curses distutils distutils/command email email/test email/test/data encodings hotshot idlelib lib-old lib-tk logging plat-aix3 plat-aix4 plat-atheos plat-beos5 plat-darwin plat-freebsd2 plat-freebsd3 plat-freebsd4 plat-freebsd5 plat-irix5 plat-irix6 plat-linux1 plat-linux2 plat-mac plat-mac/Carbon plat-mac/lib-scriptpackages/CodeWarrior plat-mac/lib-scriptpackages/Explorer plat-mac/lib-scriptpackages/Finder plat-mac/lib-scriptpackages/Netscape plat-mac/lib-scriptpackages/StdSuites plat-mac/lib-scriptpackages/SystemEvents plat-mac/lib-scriptpackages/Terminal plat-mac/lib-scriptpackages/_builtinSuites plat-netbsd1 plat-os2emx plat-riscos plat-sunos4 plat-sunos5 plat-unixware7 test xml xml/dom xml/parsers xml/sax Message-ID: <20050127165303.84A0C27B8E@code1.codespeak.net> Author: hpk Date: Thu Jan 27 17:53:02 2005 New Revision: 8639 Added: pypy/dist/lib-python-2.3.4/ (props changed) - copied from r8637, vendor/cpython/Python-r234/dist/src/Lib/ Modified: pypy/dist/lib-python-2.3.4/BaseHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/Bastion.py (props changed) pypy/dist/lib-python-2.3.4/CGIHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/ConfigParser.py (props changed) pypy/dist/lib-python-2.3.4/Cookie.py (props changed) pypy/dist/lib-python-2.3.4/DocXMLRPCServer.py (props changed) pypy/dist/lib-python-2.3.4/FCNTL.py (props changed) pypy/dist/lib-python-2.3.4/HTMLParser.py (props changed) pypy/dist/lib-python-2.3.4/MimeWriter.py (props changed) pypy/dist/lib-python-2.3.4/Queue.py (props changed) pypy/dist/lib-python-2.3.4/SimpleHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/SimpleXMLRPCServer.py (props changed) pypy/dist/lib-python-2.3.4/SocketServer.py (props changed) pypy/dist/lib-python-2.3.4/StringIO.py (props changed) pypy/dist/lib-python-2.3.4/TERMIOS.py (props changed) pypy/dist/lib-python-2.3.4/UserDict.py (props changed) pypy/dist/lib-python-2.3.4/UserList.py (props changed) pypy/dist/lib-python-2.3.4/UserString.py (props changed) pypy/dist/lib-python-2.3.4/__future__.py (props changed) pypy/dist/lib-python-2.3.4/__phello__.foo.py (props changed) pypy/dist/lib-python-2.3.4/_strptime.py (props changed) pypy/dist/lib-python-2.3.4/aifc.py (props changed) pypy/dist/lib-python-2.3.4/anydbm.py (props changed) pypy/dist/lib-python-2.3.4/asynchat.py (props changed) pypy/dist/lib-python-2.3.4/asyncore.py (props changed) pypy/dist/lib-python-2.3.4/atexit.py (props changed) pypy/dist/lib-python-2.3.4/audiodev.py (props changed) pypy/dist/lib-python-2.3.4/base64.py (props changed) pypy/dist/lib-python-2.3.4/bdb.py (props changed) pypy/dist/lib-python-2.3.4/binhex.py (props changed) pypy/dist/lib-python-2.3.4/bisect.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/ (props changed) pypy/dist/lib-python-2.3.4/bsddb/__init__.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/db.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbobj.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbrecio.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbshelve.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbtables.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbutils.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/ (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_all.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_associate.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_basics.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_compat.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbobj.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbshelve.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbtables.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_env_close.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_get_none.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_join.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_lock.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_misc.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_queue.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_recno.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_thread.py (props changed) pypy/dist/lib-python-2.3.4/calendar.py (props changed) pypy/dist/lib-python-2.3.4/cgi.py (props changed) pypy/dist/lib-python-2.3.4/cgitb.py (props changed) pypy/dist/lib-python-2.3.4/chunk.py (props changed) pypy/dist/lib-python-2.3.4/cmd.py (props changed) pypy/dist/lib-python-2.3.4/code.py (props changed) pypy/dist/lib-python-2.3.4/codecs.py (props changed) pypy/dist/lib-python-2.3.4/codeop.py (props changed) pypy/dist/lib-python-2.3.4/colorsys.py (props changed) pypy/dist/lib-python-2.3.4/commands.py (props changed) pypy/dist/lib-python-2.3.4/compileall.py (props changed) pypy/dist/lib-python-2.3.4/compiler/ (props changed) pypy/dist/lib-python-2.3.4/compiler/__init__.py (props changed) pypy/dist/lib-python-2.3.4/compiler/ast.py (props changed) pypy/dist/lib-python-2.3.4/compiler/consts.py (props changed) pypy/dist/lib-python-2.3.4/compiler/future.py (props changed) pypy/dist/lib-python-2.3.4/compiler/misc.py (props changed) pypy/dist/lib-python-2.3.4/compiler/pyassem.py (props changed) pypy/dist/lib-python-2.3.4/compiler/pycodegen.py (props changed) pypy/dist/lib-python-2.3.4/compiler/symbols.py (props changed) pypy/dist/lib-python-2.3.4/compiler/syntax.py (props changed) pypy/dist/lib-python-2.3.4/compiler/transformer.py (props changed) pypy/dist/lib-python-2.3.4/compiler/visitor.py (props changed) pypy/dist/lib-python-2.3.4/copy.py (props changed) pypy/dist/lib-python-2.3.4/copy_reg.py (props changed) pypy/dist/lib-python-2.3.4/csv.py (props changed) pypy/dist/lib-python-2.3.4/curses/ (props changed) pypy/dist/lib-python-2.3.4/curses/__init__.py (props changed) pypy/dist/lib-python-2.3.4/curses/ascii.py (props changed) pypy/dist/lib-python-2.3.4/curses/has_key.py (props changed) pypy/dist/lib-python-2.3.4/curses/panel.py (props changed) pypy/dist/lib-python-2.3.4/curses/textpad.py (props changed) pypy/dist/lib-python-2.3.4/curses/wrapper.py (props changed) pypy/dist/lib-python-2.3.4/dbhash.py (props changed) pypy/dist/lib-python-2.3.4/difflib.py (props changed) pypy/dist/lib-python-2.3.4/dircache.py (props changed) pypy/dist/lib-python-2.3.4/dis.py (props changed) pypy/dist/lib-python-2.3.4/distutils/ (props changed) pypy/dist/lib-python-2.3.4/distutils/__init__.py (props changed) pypy/dist/lib-python-2.3.4/distutils/archive_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/bcppcompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/ccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/cmd.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/ (props changed) pypy/dist/lib-python-2.3.4/distutils/command/__init__.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_dumb.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_rpm.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_wininst.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_clib.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_ext.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_py.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_scripts.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/clean.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/config.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_data.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_headers.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_lib.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_scripts.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/register.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/sdist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/core.py (props changed) pypy/dist/lib-python-2.3.4/distutils/cygwinccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/debug.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dep_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dir_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/emxccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/errors.py (props changed) pypy/dist/lib-python-2.3.4/distutils/extension.py (props changed) pypy/dist/lib-python-2.3.4/distutils/fancy_getopt.py (props changed) pypy/dist/lib-python-2.3.4/distutils/file_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/filelist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/log.py (props changed) pypy/dist/lib-python-2.3.4/distutils/msvccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/mwerkscompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/spawn.py (props changed) pypy/dist/lib-python-2.3.4/distutils/sysconfig.py (props changed) pypy/dist/lib-python-2.3.4/distutils/text_file.py (props changed) pypy/dist/lib-python-2.3.4/distutils/unixccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/version.py (props changed) pypy/dist/lib-python-2.3.4/doctest.py (props changed) pypy/dist/lib-python-2.3.4/dumbdbm.py (props changed) pypy/dist/lib-python-2.3.4/dummy_thread.py (props changed) pypy/dist/lib-python-2.3.4/dummy_threading.py (props changed) pypy/dist/lib-python-2.3.4/email/ (props changed) pypy/dist/lib-python-2.3.4/email/Charset.py (props changed) pypy/dist/lib-python-2.3.4/email/Encoders.py (props changed) pypy/dist/lib-python-2.3.4/email/Errors.py (props changed) pypy/dist/lib-python-2.3.4/email/Generator.py (props changed) pypy/dist/lib-python-2.3.4/email/Header.py (props changed) pypy/dist/lib-python-2.3.4/email/Iterators.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEAudio.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEBase.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEImage.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEMessage.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEMultipart.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMENonMultipart.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEText.py (props changed) pypy/dist/lib-python-2.3.4/email/Message.py (props changed) pypy/dist/lib-python-2.3.4/email/Parser.py (props changed) pypy/dist/lib-python-2.3.4/email/Utils.py (props changed) pypy/dist/lib-python-2.3.4/email/__init__.py (props changed) pypy/dist/lib-python-2.3.4/email/_compat21.py (props changed) pypy/dist/lib-python-2.3.4/email/_compat22.py (props changed) pypy/dist/lib-python-2.3.4/email/_parseaddr.py (props changed) pypy/dist/lib-python-2.3.4/email/base64MIME.py (props changed) pypy/dist/lib-python-2.3.4/email/quopriMIME.py (props changed) pypy/dist/lib-python-2.3.4/email/test/ (props changed) pypy/dist/lib-python-2.3.4/email/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/email/test/data/ (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_01.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_02.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_03.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_04.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_05.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_06.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_07.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_08.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_09.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_10.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_11.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_12.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_13.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_14.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_15.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_16.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_17.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_18.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_19.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_20.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_21.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_22.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_23.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_24.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_25.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_26.txt (contents, props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_27.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_28.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_29.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_30.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_31.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_32.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_33.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_34.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_35.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email.py (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email_codecs.py (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email_torture.py (props changed) pypy/dist/lib-python-2.3.4/encodings/ (props changed) pypy/dist/lib-python-2.3.4/encodings/__init__.py (props changed) pypy/dist/lib-python-2.3.4/encodings/aliases.py (props changed) pypy/dist/lib-python-2.3.4/encodings/ascii.py (props changed) pypy/dist/lib-python-2.3.4/encodings/base64_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/charmap.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp037.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1006.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1026.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1140.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1250.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1251.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1252.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1253.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1254.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1255.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1256.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1257.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1258.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp424.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp437.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp500.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp737.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp775.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp850.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp852.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp855.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp856.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp857.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp860.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp861.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp862.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp863.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp864.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp865.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp866.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp869.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp874.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp875.py (props changed) pypy/dist/lib-python-2.3.4/encodings/hex_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/idna.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_1.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_10.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_13.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_14.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_15.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_2.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_3.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_4.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_5.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_6.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_7.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_8.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_9.py (props changed) pypy/dist/lib-python-2.3.4/encodings/koi8_r.py (props changed) pypy/dist/lib-python-2.3.4/encodings/koi8_u.py (props changed) pypy/dist/lib-python-2.3.4/encodings/latin_1.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_cyrillic.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_greek.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_iceland.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_latin2.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_roman.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_turkish.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mbcs.py (props changed) pypy/dist/lib-python-2.3.4/encodings/palmos.py (props changed) pypy/dist/lib-python-2.3.4/encodings/punycode.py (props changed) pypy/dist/lib-python-2.3.4/encodings/quopri_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/raw_unicode_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/rot_13.py (props changed) pypy/dist/lib-python-2.3.4/encodings/string_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/undefined.py (props changed) pypy/dist/lib-python-2.3.4/encodings/unicode_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/unicode_internal.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16_be.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16_le.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_7.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_8.py (props changed) pypy/dist/lib-python-2.3.4/encodings/uu_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/zlib_codec.py (props changed) pypy/dist/lib-python-2.3.4/filecmp.py (props changed) pypy/dist/lib-python-2.3.4/fileinput.py (props changed) pypy/dist/lib-python-2.3.4/fnmatch.py (props changed) pypy/dist/lib-python-2.3.4/formatter.py (props changed) pypy/dist/lib-python-2.3.4/fpformat.py (props changed) pypy/dist/lib-python-2.3.4/ftplib.py (props changed) pypy/dist/lib-python-2.3.4/getopt.py (props changed) pypy/dist/lib-python-2.3.4/getpass.py (props changed) pypy/dist/lib-python-2.3.4/gettext.py (props changed) pypy/dist/lib-python-2.3.4/glob.py (props changed) pypy/dist/lib-python-2.3.4/gopherlib.py (props changed) pypy/dist/lib-python-2.3.4/gzip.py (props changed) pypy/dist/lib-python-2.3.4/heapq.py (props changed) pypy/dist/lib-python-2.3.4/hmac.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/ (props changed) pypy/dist/lib-python-2.3.4/hotshot/__init__.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/log.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/stats.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/stones.py (props changed) pypy/dist/lib-python-2.3.4/htmlentitydefs.py (props changed) pypy/dist/lib-python-2.3.4/htmllib.py (props changed) pypy/dist/lib-python-2.3.4/httplib.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ (props changed) pypy/dist/lib-python-2.3.4/idlelib/AutoExpand.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Bindings.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/CREDITS.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/CallTipWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/CallTips.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ClassBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ColorDelegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Debugger.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Delegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/EditorWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/FileList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/FormatParagraph.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/GrepDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/HISTORY.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/IOBinding.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/IdleHistory.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/MultiStatusBar.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/NEWS.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/ObjectBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/OutputWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ParenMatch.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PathBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Percolator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PyParse.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PyShell.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/README.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/RemoteDebugger.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/RemoteObjectBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ReplaceDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ScriptBinding.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ScrolledList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchDialogBase.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchEngine.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/StackViewer.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/TODO.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/ToolTip.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/TreeWidget.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/UndoDelegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/WidgetRedirector.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/WindowList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ZoomHeight.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/__init__.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/aboutDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/buildapp.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configHandler.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configHelpSourceEdit.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configSectionNameDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/dynOptionMenuWidget.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/extend.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/help.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/idle.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/idlever.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/keybindingDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/rpc.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/run.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/tabpage.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/testcode.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/textView.py (props changed) pypy/dist/lib-python-2.3.4/ihooks.py (props changed) pypy/dist/lib-python-2.3.4/imaplib.py (props changed) pypy/dist/lib-python-2.3.4/imghdr.py (props changed) pypy/dist/lib-python-2.3.4/imputil.py (props changed) pypy/dist/lib-python-2.3.4/inspect.py (props changed) pypy/dist/lib-python-2.3.4/keyword.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/ (props changed) pypy/dist/lib-python-2.3.4/lib-old/Para.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/addpack.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/cmp.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/cmpcache.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/codehack.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/dircmp.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/dump.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/find.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/fmt.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/grep.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/lockfile.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/newdir.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/ni.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/packmail.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/poly.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/rand.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/tb.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/util.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/whatsound.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/zmod.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/ (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Canvas.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Dialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/FileDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/FixTk.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/ScrolledText.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/SimpleDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tix.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkconstants.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkdnd.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkinter.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkColorChooser.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkCommonDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkFileDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkFont.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkMessageBox.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkSimpleDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/turtle.py (props changed) pypy/dist/lib-python-2.3.4/linecache.py (props changed) pypy/dist/lib-python-2.3.4/locale.py (props changed) pypy/dist/lib-python-2.3.4/logging/ (props changed) pypy/dist/lib-python-2.3.4/logging/__init__.py (props changed) pypy/dist/lib-python-2.3.4/logging/config.py (props changed) pypy/dist/lib-python-2.3.4/logging/handlers.py (props changed) pypy/dist/lib-python-2.3.4/macpath.py (props changed) pypy/dist/lib-python-2.3.4/macurl2path.py (props changed) pypy/dist/lib-python-2.3.4/mailbox.py (props changed) pypy/dist/lib-python-2.3.4/mailcap.py (props changed) pypy/dist/lib-python-2.3.4/markupbase.py (props changed) pypy/dist/lib-python-2.3.4/mhlib.py (props changed) pypy/dist/lib-python-2.3.4/mimetools.py (props changed) pypy/dist/lib-python-2.3.4/mimetypes.py (props changed) pypy/dist/lib-python-2.3.4/mimify.py (props changed) pypy/dist/lib-python-2.3.4/modulefinder.py (props changed) pypy/dist/lib-python-2.3.4/multifile.py (props changed) pypy/dist/lib-python-2.3.4/mutex.py (props changed) pypy/dist/lib-python-2.3.4/netrc.py (props changed) pypy/dist/lib-python-2.3.4/new.py (props changed) pypy/dist/lib-python-2.3.4/nntplib.py (props changed) pypy/dist/lib-python-2.3.4/ntpath.py (props changed) pypy/dist/lib-python-2.3.4/nturl2path.py (props changed) pypy/dist/lib-python-2.3.4/opcode.py (props changed) pypy/dist/lib-python-2.3.4/optparse.py (props changed) pypy/dist/lib-python-2.3.4/os.py (props changed) pypy/dist/lib-python-2.3.4/os2emxpath.py (props changed) pypy/dist/lib-python-2.3.4/pdb.py (props changed) pypy/dist/lib-python-2.3.4/pickle.py (props changed) pypy/dist/lib-python-2.3.4/pickletools.py (props changed) pypy/dist/lib-python-2.3.4/pipes.py (props changed) pypy/dist/lib-python-2.3.4/pkgutil.py (props changed) pypy/dist/lib-python-2.3.4/plat-aix3/ (props changed) pypy/dist/lib-python-2.3.4/plat-aix3/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-aix4/ (props changed) pypy/dist/lib-python-2.3.4/plat-aix4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/ (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-beos5/ (props changed) pypy/dist/lib-python-2.3.4/plat-beos5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-darwin/ (props changed) pypy/dist/lib-python-2.3.4/plat-darwin/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd2/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd2/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd3/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd3/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd4/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd5/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/ (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/AL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CD.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CL_old.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/DEVICE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/ERRNO.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/FILE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/FL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GET.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GLWS.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/IOCTL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/SV.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/cddb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/cdplayer.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/flp.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/jpeg.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/panel.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/panelparser.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/readcd.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/torgb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/ (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/AL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/CD.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/CL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/DEVICE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/ERRNO.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/FILE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/FL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GET.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GLWS.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/IOCTL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/SV.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/cddb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/cdplayer.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/flp.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/jpeg.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/panel.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/panelparser.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/readcd.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/torgb.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux1/ (props changed) pypy/dist/lib-python-2.3.4/plat-linux1/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/ (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/CDROM.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/DLFCN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Audio_mac.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AE.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AH.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Alias.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Aliases.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/App.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Appearance.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AppleEvents.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AppleHelp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CF.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CG.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CarbonEvents.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CarbonEvt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Cm.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Components.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/ControlAccessor.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Controls.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CoreFoundation.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CoreGraphics.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Ctl.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dialogs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dlg.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Drag.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dragconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Events.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Evt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/File.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Files.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Fm.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Folder.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Folders.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Fonts.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Help.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/IBCarbon.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/IBCarbonRuntime.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Icn.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Icons.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/List.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Lists.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MacHelp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MacTextEditor.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MediaDescr.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Menu.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Menus.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Mlte.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QDOffscreen.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qd.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qdoffs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QuickDraw.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QuickTime.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Res.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Resources.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Scrap.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Snd.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Sndihooks.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Sound.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/TE.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/TextEdit.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/WASTEconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Win.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Windows.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/__init__.py (contents, props changed) pypy/dist/lib-python-2.3.4/plat-mac/EasyDialogs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/FrameWork.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/MiniAEFrame.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/PixMapWrapper.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/WASTEconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aepack.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aetools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aetypes.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/applesingle.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/appletrawmain.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/appletrunner.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/argvemulator.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/bgenlocations.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/buildtools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/bundlebuilder.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/cfmfile.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/findertools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/gensuitemodule.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/ic.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/icopen.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Required.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Microsoft_Internet_Explorer.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Netscape_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/URL_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Containers_and_folders.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Enumerations.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Files.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Finder_items.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Type_Definitions.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Window_classes.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Required_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py (contents, props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Text.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suppleme.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Required_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Type_Names_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Hidden_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Login_Items_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Power_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Processes_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/System_Events_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Terminal_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macerrors.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macfs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macostools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macresource.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/pimp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/plistlib.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/terminalcommand.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/videoreader.py (props changed) pypy/dist/lib-python-2.3.4/plat-netbsd1/ (props changed) pypy/dist/lib-python-2.3.4/plat-netbsd1/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/ (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/SOCKET.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/grp.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/pwd.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/ (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/riscosenviron.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/riscospath.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/rourl2path.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/ (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/SUNAUDIODEV.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/ (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/CDIO.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/DLFCN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/STROPTS.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/SUNAUDIODEV.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/ (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/STROPTS.py (props changed) pypy/dist/lib-python-2.3.4/platform.py (props changed) pypy/dist/lib-python-2.3.4/popen2.py (props changed) pypy/dist/lib-python-2.3.4/poplib.py (props changed) pypy/dist/lib-python-2.3.4/posixfile.py (props changed) pypy/dist/lib-python-2.3.4/posixpath.py (props changed) pypy/dist/lib-python-2.3.4/pprint.py (props changed) pypy/dist/lib-python-2.3.4/pre.py (props changed) pypy/dist/lib-python-2.3.4/profile.py (props changed) pypy/dist/lib-python-2.3.4/pstats.py (props changed) pypy/dist/lib-python-2.3.4/pty.py (props changed) pypy/dist/lib-python-2.3.4/py_compile.py (props changed) pypy/dist/lib-python-2.3.4/pyclbr.py (props changed) pypy/dist/lib-python-2.3.4/pydoc.py (props changed) pypy/dist/lib-python-2.3.4/quopri.py (props changed) pypy/dist/lib-python-2.3.4/random.py (props changed) pypy/dist/lib-python-2.3.4/re.py (props changed) pypy/dist/lib-python-2.3.4/reconvert.py (props changed) pypy/dist/lib-python-2.3.4/regex_syntax.py (props changed) pypy/dist/lib-python-2.3.4/regsub.py (props changed) pypy/dist/lib-python-2.3.4/repr.py (props changed) pypy/dist/lib-python-2.3.4/rexec.py (props changed) pypy/dist/lib-python-2.3.4/rfc822.py (props changed) pypy/dist/lib-python-2.3.4/rlcompleter.py (props changed) pypy/dist/lib-python-2.3.4/robotparser.py (props changed) pypy/dist/lib-python-2.3.4/sched.py (props changed) pypy/dist/lib-python-2.3.4/sets.py (props changed) pypy/dist/lib-python-2.3.4/sgmllib.py (props changed) pypy/dist/lib-python-2.3.4/shelve.py (props changed) pypy/dist/lib-python-2.3.4/shlex.py (props changed) pypy/dist/lib-python-2.3.4/shutil.py (props changed) pypy/dist/lib-python-2.3.4/site.py (props changed) pypy/dist/lib-python-2.3.4/smtpd.py (props changed) pypy/dist/lib-python-2.3.4/smtplib.py (props changed) pypy/dist/lib-python-2.3.4/sndhdr.py (props changed) pypy/dist/lib-python-2.3.4/socket.py (props changed) pypy/dist/lib-python-2.3.4/sre.py (props changed) pypy/dist/lib-python-2.3.4/sre_compile.py (props changed) pypy/dist/lib-python-2.3.4/sre_constants.py (props changed) pypy/dist/lib-python-2.3.4/sre_parse.py (props changed) pypy/dist/lib-python-2.3.4/stat.py (props changed) pypy/dist/lib-python-2.3.4/statcache.py (props changed) pypy/dist/lib-python-2.3.4/statvfs.py (props changed) pypy/dist/lib-python-2.3.4/string.py (props changed) pypy/dist/lib-python-2.3.4/stringold.py (props changed) pypy/dist/lib-python-2.3.4/stringprep.py (props changed) pypy/dist/lib-python-2.3.4/sunau.py (props changed) pypy/dist/lib-python-2.3.4/sunaudio.py (props changed) pypy/dist/lib-python-2.3.4/symbol.py (props changed) pypy/dist/lib-python-2.3.4/symtable.py (props changed) pypy/dist/lib-python-2.3.4/tabnanny.py (props changed) pypy/dist/lib-python-2.3.4/tarfile.py (props changed) pypy/dist/lib-python-2.3.4/telnetlib.py (props changed) pypy/dist/lib-python-2.3.4/tempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/ (props changed) pypy/dist/lib-python-2.3.4/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/test/autotest.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future3.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future4.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future5.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future6.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future7.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_nocaret.py (props changed) pypy/dist/lib-python-2.3.4/test/double_const.py (props changed) pypy/dist/lib-python-2.3.4/test/pickletester.py (props changed) pypy/dist/lib-python-2.3.4/test/pydocfodder.py (props changed) pypy/dist/lib-python-2.3.4/test/pystone.py (props changed) pypy/dist/lib-python-2.3.4/test/re_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/regex_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/regrtest.py (props changed) pypy/dist/lib-python-2.3.4/test/reperf.py (props changed) pypy/dist/lib-python-2.3.4/test/sortperf.py (props changed) pypy/dist/lib-python-2.3.4/test/string_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/test_MimeWriter.py (props changed) pypy/dist/lib-python-2.3.4/test/test_StringIO.py (props changed) pypy/dist/lib-python-2.3.4/test/test___all__.py (props changed) pypy/dist/lib-python-2.3.4/test/test___future__.py (props changed) pypy/dist/lib-python-2.3.4/test/test_aepack.py (props changed) pypy/dist/lib-python-2.3.4/test/test_al.py (props changed) pypy/dist/lib-python-2.3.4/test/test_anydbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_array.py (props changed) pypy/dist/lib-python-2.3.4/test/test_asynchat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_atexit.py (props changed) pypy/dist/lib-python-2.3.4/test/test_audioop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_augassign.py (props changed) pypy/dist/lib-python-2.3.4/test/test_base64.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bastion.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binascii.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binhex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bisect.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bool.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb185.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb3.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bufio.py (props changed) pypy/dist/lib-python-2.3.4/test/test_builtin.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bz2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_calendar.py (props changed) pypy/dist/lib-python-2.3.4/test/test_call.py (props changed) pypy/dist/lib-python-2.3.4/test/test_capi.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cd.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cfgparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cgi.py (props changed) pypy/dist/lib-python-2.3.4/test/test_charmapcodec.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_class.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cmath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codeccallbacks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codecs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codeop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_coercion.py (props changed) pypy/dist/lib-python-2.3.4/test/test_commands.py (props changed) pypy/dist/lib-python-2.3.4/test/test_compare.py (props changed) pypy/dist/lib-python-2.3.4/test/test_compile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_complex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_contains.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cookie.py (props changed) pypy/dist/lib-python-2.3.4/test/test_copy.py (props changed) pypy/dist/lib-python-2.3.4/test/test_copy_reg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cpickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_crypt.py (props changed) pypy/dist/lib-python-2.3.4/test/test_csv.py (props changed) pypy/dist/lib-python-2.3.4/test/test_curses.py (props changed) pypy/dist/lib-python-2.3.4/test/test_datetime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_descr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_descrtut.py (props changed) pypy/dist/lib-python-2.3.4/test/test_difflib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dircache.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dis.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_doctest.py (props changed) pypy/dist/lib-python-2.3.4/test/test_doctest2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dumbdbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dummy_thread.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dummy_threading.py (props changed) pypy/dist/lib-python-2.3.4/test/test_email.py (props changed) pypy/dist/lib-python-2.3.4/test/test_email_codecs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_enumerate.py (props changed) pypy/dist/lib-python-2.3.4/test/test_eof.py (props changed) pypy/dist/lib-python-2.3.4/test/test_errno.py (props changed) pypy/dist/lib-python-2.3.4/test/test_exceptions.py (props changed) pypy/dist/lib-python-2.3.4/test/test_extcall.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fcntl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_file.py (props changed) pypy/dist/lib-python-2.3.4/test/test_filecmp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fileinput.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fnmatch.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fork1.py (props changed) pypy/dist/lib-python-2.3.4/test/test_format.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fpformat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_frozen.py (props changed) pypy/dist/lib-python-2.3.4/test/test_funcattrs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future1.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future3.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gdbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_generators.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getargs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getargs2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getopt.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gettext.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_glob.py (props changed) pypy/dist/lib-python-2.3.4/test/test_global.py (props changed) pypy/dist/lib-python-2.3.4/test/test_grammar.py (props changed) pypy/dist/lib-python-2.3.4/test/test_grp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gzip.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hash.py (props changed) pypy/dist/lib-python-2.3.4/test/test_heapq.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hexoct.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hmac.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hotshot.py (props changed) pypy/dist/lib-python-2.3.4/test/test_htmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_htmlparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_httplib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imageop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imaplib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imgfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_import.py (props changed) pypy/dist/lib-python-2.3.4/test/test_importhooks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_inspect.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ioctl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_isinstance.py (props changed) pypy/dist/lib-python-2.3.4/test/test_iter.py (props changed) pypy/dist/lib-python-2.3.4/test/test_itertools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_largefile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_linuxaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_locale.py (props changed) pypy/dist/lib-python-2.3.4/test/test_logging.py (props changed) pypy/dist/lib-python-2.3.4/test/test_long.py (props changed) pypy/dist/lib-python-2.3.4/test/test_long_future.py (props changed) pypy/dist/lib-python-2.3.4/test/test_longexp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macfs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macostools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mailbox.py (props changed) pypy/dist/lib-python-2.3.4/test/test_marshal.py (props changed) pypy/dist/lib-python-2.3.4/test/test_math.py (props changed) pypy/dist/lib-python-2.3.4/test/test_md5.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mhlib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mimetools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mimetypes.py (props changed) pypy/dist/lib-python-2.3.4/test/test_minidom.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mmap.py (props changed) pypy/dist/lib-python-2.3.4/test/test_module.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mpz.py (props changed) pypy/dist/lib-python-2.3.4/test/test_multifile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mutants.py (props changed) pypy/dist/lib-python-2.3.4/test/test_netrc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_new.py (props changed) pypy/dist/lib-python-2.3.4/test/test_nis.py (props changed) pypy/dist/lib-python-2.3.4/test/test_normalization.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ntpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_opcodes.py (props changed) pypy/dist/lib-python-2.3.4/test/test_openpty.py (props changed) pypy/dist/lib-python-2.3.4/test/test_operations.py (props changed) pypy/dist/lib-python-2.3.4/test/test_operator.py (props changed) pypy/dist/lib-python-2.3.4/test/test_optparse.py (props changed) pypy/dist/lib-python-2.3.4/test/test_os.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ossaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_parser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep247.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep263.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep277.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pickletools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pkg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pkgimport.py (props changed) pypy/dist/lib-python-2.3.4/test/test_plistlib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_poll.py (props changed) pypy/dist/lib-python-2.3.4/test/test_popen.py (props changed) pypy/dist/lib-python-2.3.4/test/test_popen2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_posix.py (props changed) pypy/dist/lib-python-2.3.4/test/test_posixpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pow.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pprint.py (props changed) pypy/dist/lib-python-2.3.4/test/test_profile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_profilehooks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pty.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pwd.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pyclbr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pyexpat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_queue.py (props changed) pypy/dist/lib-python-2.3.4/test/test_quopri.py (props changed) pypy/dist/lib-python-2.3.4/test/test_random.py (props changed) pypy/dist/lib-python-2.3.4/test/test_re.py (props changed) pypy/dist/lib-python-2.3.4/test/test_regex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_repr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_resource.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rfc822.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rgbimg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_richcmp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_robotparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rotor.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sax.py (props changed) pypy/dist/lib-python-2.3.4/test/test_scope.py (props changed) pypy/dist/lib-python-2.3.4/test/test_scriptpackages.py (props changed) pypy/dist/lib-python-2.3.4/test/test_select.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sets.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sgmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sha.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shelve.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shlex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shutil.py (props changed) pypy/dist/lib-python-2.3.4/test/test_signal.py (props changed) pypy/dist/lib-python-2.3.4/test/test_slice.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socket.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socket_ssl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socketserver.py (props changed) pypy/dist/lib-python-2.3.4/test/test_softspace.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sort.py (props changed) pypy/dist/lib-python-2.3.4/test/test_str.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strftime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_string.py (props changed) pypy/dist/lib-python-2.3.4/test/test_stringprep.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strptime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_struct.py (props changed) pypy/dist/lib-python-2.3.4/test/test_structseq.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sunaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sundry.py (props changed) pypy/dist/lib-python-2.3.4/test/test_support.py (props changed) pypy/dist/lib-python-2.3.4/test/test_symtable.py (props changed) pypy/dist/lib-python-2.3.4/test/test_syntax.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sys.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tarfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_textwrap.py (props changed) pypy/dist/lib-python-2.3.4/test/test_thread.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threaded_import.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threadedtempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threading.py (props changed) pypy/dist/lib-python-2.3.4/test/test_time.py (props changed) pypy/dist/lib-python-2.3.4/test/test_timeout.py (props changed) pypy/dist/lib-python-2.3.4/test/test_timing.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tokenize.py (props changed) pypy/dist/lib-python-2.3.4/test/test_trace.py (props changed) pypy/dist/lib-python-2.3.4/test/test_traceback.py (props changed) pypy/dist/lib-python-2.3.4/test/test_types.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ucn.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unary.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicode.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicode_file.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicodedata.py (props changed) pypy/dist/lib-python-2.3.4/test/test_univnewlines.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unpack.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllib2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllibnet.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urlparse.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userdict.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userlist.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userstring.py (props changed) pypy/dist/lib-python-2.3.4/test/test_uu.py (props changed) pypy/dist/lib-python-2.3.4/test/test_warnings.py (props changed) pypy/dist/lib-python-2.3.4/test/test_wave.py (props changed) pypy/dist/lib-python-2.3.4/test/test_weakref.py (props changed) pypy/dist/lib-python-2.3.4/test/test_whichdb.py (props changed) pypy/dist/lib-python-2.3.4/test/test_winreg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_winsound.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xmlrpc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xpickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xreadline.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zipfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zipimport.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zlib.py (props changed) pypy/dist/lib-python-2.3.4/test/testall.py (props changed) pypy/dist/lib-python-2.3.4/test/testcodec.py (props changed) pypy/dist/lib-python-2.3.4/test/tf_inherit_check.py (props changed) pypy/dist/lib-python-2.3.4/test/tokenize_tests.txt (props changed) pypy/dist/lib-python-2.3.4/test/xmltests.py (props changed) pypy/dist/lib-python-2.3.4/textwrap.py (props changed) pypy/dist/lib-python-2.3.4/this.py (props changed) pypy/dist/lib-python-2.3.4/threading.py (props changed) pypy/dist/lib-python-2.3.4/timeit.py (props changed) pypy/dist/lib-python-2.3.4/toaiff.py (props changed) pypy/dist/lib-python-2.3.4/token.py (props changed) pypy/dist/lib-python-2.3.4/tokenize.py (props changed) pypy/dist/lib-python-2.3.4/trace.py (props changed) pypy/dist/lib-python-2.3.4/traceback.py (props changed) pypy/dist/lib-python-2.3.4/tty.py (props changed) pypy/dist/lib-python-2.3.4/types.py (props changed) pypy/dist/lib-python-2.3.4/tzparse.py (props changed) pypy/dist/lib-python-2.3.4/unittest.py (props changed) pypy/dist/lib-python-2.3.4/urllib.py (props changed) pypy/dist/lib-python-2.3.4/urllib2.py (props changed) pypy/dist/lib-python-2.3.4/urlparse.py (props changed) pypy/dist/lib-python-2.3.4/user.py (props changed) pypy/dist/lib-python-2.3.4/uu.py (props changed) pypy/dist/lib-python-2.3.4/warnings.py (props changed) pypy/dist/lib-python-2.3.4/wave.py (props changed) pypy/dist/lib-python-2.3.4/weakref.py (props changed) pypy/dist/lib-python-2.3.4/webbrowser.py (props changed) pypy/dist/lib-python-2.3.4/whichdb.py (props changed) pypy/dist/lib-python-2.3.4/whrandom.py (props changed) pypy/dist/lib-python-2.3.4/xdrlib.py (props changed) pypy/dist/lib-python-2.3.4/xml/ (props changed) pypy/dist/lib-python-2.3.4/xml/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/ (props changed) pypy/dist/lib-python-2.3.4/xml/dom/NodeFilter.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/domreg.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/expatbuilder.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/minicompat.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/minidom.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/pulldom.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/xmlbuilder.py (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/ (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/expat.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/ (props changed) pypy/dist/lib-python-2.3.4/xml/sax/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/_exceptions.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/expatreader.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/handler.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/saxutils.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/xmlreader.py (props changed) pypy/dist/lib-python-2.3.4/xmllib.py (props changed) pypy/dist/lib-python-2.3.4/xmlrpclib.py (props changed) pypy/dist/lib-python-2.3.4/zipfile.py (props changed) Log: copy the full Python 2.3.4 Lib hierarchy (including the regr-tests) into our svn/pypy/dist. We probably want to move the "appspace"-hacks to this new directory so that we can easily diff against the unmodified python2.3.4 library and find out what we needed to change in order to make PyPy work in a systematic manner. It is now probably a good idea to settle on going for python-2.3.4 implementations and features and only at some point later move to python-2.4. Modified: pypy/dist/lib-python-2.3.4/email/test/data/msg_26.txt ============================================================================== --- vendor/cpython/Python-r234/dist/src/Lib/email/test/data/msg_26.txt (original) +++ pypy/dist/lib-python-2.3.4/email/test/data/msg_26.txt Thu Jan 27 17:53:02 2005 @@ -1,45 +1,45 @@ -Received: from xcar [192.168.0.2] by jeeves.wooster.local - (SMTPD32-7.07 EVAL) id AFF92F0214; Sun, 12 May 2002 08:55:37 +0100 -Date: Sun, 12 May 2002 08:56:15 +0100 -From: Father Time -To: timbo at jeeves.wooster.local -Subject: IMAP file test -Message-ID: <6df65d354b.father.time at rpc.wooster.local> -X-Organization: Home -User-Agent: Messenger-Pro/2.50a (MsgServe/1.50) (RISC-OS/4.02) POPstar/2.03 -MIME-Version: 1.0 -Content-Type: multipart/mixed; boundary="1618492860--2051301190--113853680" -Status: R -X-UIDL: 319998302 - -This message is in MIME format which your mailer apparently does not support. -You either require a newer version of your software which supports MIME, or -a separate MIME decoding utility. Alternatively, ask the sender of this -message to resend it in a different format. - ---1618492860--2051301190--113853680 -Content-Type: text/plain; charset=us-ascii - -Simple email with attachment. - - ---1618492860--2051301190--113853680 -Content-Type: application/riscos; name="clock.bmp,69c"; type=BMP; load=&fff69c4b; exec=&355dd4d1; access=&03 -Content-Disposition: attachment; filename="clock.bmp" -Content-Transfer-Encoding: base64 - -Qk12AgAAAAAAAHYAAAAoAAAAIAAAACAAAAABAAQAAAAAAAAAAADXDQAA1w0AAAAAAAAA -AAAAAAAAAAAAiAAAiAAAAIiIAIgAAACIAIgAiIgAALu7uwCIiIgAERHdACLuIgAz//8A -zAAAAN0R3QDu7iIA////AAAAAAAAAAAAAAAAAAAAAAAAAAi3AAAAAAAAADeAAAAAAAAA -C3ADMzMzMANwAAAAAAAAAAAHMAAAAANwAAAAAAAAAACAMAd3zPfwAwgAAAAAAAAIAwd/ -f8x/f3AwgAAAAAAAgDB0x/f3//zPAwgAAAAAAAcHfM9////8z/AwAAAAAAiwd/f3//// -////A4AAAAAAcEx/f///////zAMAAAAAiwfM9////3///8zwOAAAAAcHf3////B///// -8DAAAAALB/f3///wd3d3//AwAAAABwTPf//wCQAAD/zAMAAAAAsEx/f///B////8wDAA -AAAHB39////wf/////AwAAAACwf39///8H/////wMAAAAIcHfM9///B////M8DgAAAAA -sHTH///wf///xAMAAAAACHB3f3//8H////cDgAAAAAALB3zH//D//M9wMAAAAAAAgLB0 -z39///xHAwgAAAAAAAgLB3d3RHd3cDCAAAAAAAAAgLAHd0R3cAMIAAAAAAAAgAgLcAAA -AAMwgAgAAAAACDAAAAu7t7cwAAgDgAAAAABzcIAAAAAAAAgDMwAAAAAAN7uwgAAAAAgH -MzMAAAAACH97tzAAAAALu3c3gAAAAAAL+7tzDABAu7f7cAAAAAAACA+3MA7EQAv/sIAA -AAAAAAAIAAAAAAAAAIAAAAAA - ---1618492860--2051301190--113853680-- +Received: from xcar [192.168.0.2] by jeeves.wooster.local + (SMTPD32-7.07 EVAL) id AFF92F0214; Sun, 12 May 2002 08:55:37 +0100 +Date: Sun, 12 May 2002 08:56:15 +0100 +From: Father Time +To: timbo at jeeves.wooster.local +Subject: IMAP file test +Message-ID: <6df65d354b.father.time at rpc.wooster.local> +X-Organization: Home +User-Agent: Messenger-Pro/2.50a (MsgServe/1.50) (RISC-OS/4.02) POPstar/2.03 +MIME-Version: 1.0 +Content-Type: multipart/mixed; boundary="1618492860--2051301190--113853680" +Status: R +X-UIDL: 319998302 + +This message is in MIME format which your mailer apparently does not support. +You either require a newer version of your software which supports MIME, or +a separate MIME decoding utility. Alternatively, ask the sender of this +message to resend it in a different format. + +--1618492860--2051301190--113853680 +Content-Type: text/plain; charset=us-ascii + +Simple email with attachment. + + +--1618492860--2051301190--113853680 +Content-Type: application/riscos; name="clock.bmp,69c"; type=BMP; load=&fff69c4b; exec=&355dd4d1; access=&03 +Content-Disposition: attachment; filename="clock.bmp" +Content-Transfer-Encoding: base64 + +Qk12AgAAAAAAAHYAAAAoAAAAIAAAACAAAAABAAQAAAAAAAAAAADXDQAA1w0AAAAAAAAA +AAAAAAAAAAAAiAAAiAAAAIiIAIgAAACIAIgAiIgAALu7uwCIiIgAERHdACLuIgAz//8A +zAAAAN0R3QDu7iIA////AAAAAAAAAAAAAAAAAAAAAAAAAAi3AAAAAAAAADeAAAAAAAAA +C3ADMzMzMANwAAAAAAAAAAAHMAAAAANwAAAAAAAAAACAMAd3zPfwAwgAAAAAAAAIAwd/ +f8x/f3AwgAAAAAAAgDB0x/f3//zPAwgAAAAAAAcHfM9////8z/AwAAAAAAiwd/f3//// +////A4AAAAAAcEx/f///////zAMAAAAAiwfM9////3///8zwOAAAAAcHf3////B///// +8DAAAAALB/f3///wd3d3//AwAAAABwTPf//wCQAAD/zAMAAAAAsEx/f///B////8wDAA +AAAHB39////wf/////AwAAAACwf39///8H/////wMAAAAIcHfM9///B////M8DgAAAAA +sHTH///wf///xAMAAAAACHB3f3//8H////cDgAAAAAALB3zH//D//M9wMAAAAAAAgLB0 +z39///xHAwgAAAAAAAgLB3d3RHd3cDCAAAAAAAAAgLAHd0R3cAMIAAAAAAAAgAgLcAAA +AAMwgAgAAAAACDAAAAu7t7cwAAgDgAAAAABzcIAAAAAAAAgDMwAAAAAAN7uwgAAAAAgH +MzMAAAAACH97tzAAAAALu3c3gAAAAAAL+7tzDABAu7f7cAAAAAAACA+3MA7EQAv/sIAA +AAAAAAAIAAAAAAAAAIAAAAAA + +--1618492860--2051301190--113853680-- Modified: pypy/dist/lib-python-2.3.4/plat-mac/Carbon/__init__.py ============================================================================== --- vendor/cpython/Python-r234/dist/src/Lib/plat-mac/Carbon/__init__.py (original) +++ pypy/dist/lib-python-2.3.4/plat-mac/Carbon/__init__.py Thu Jan 27 17:53:02 2005 @@ -1 +1,4 @@ -# Filter out warnings about signed/unsigned constants import warnings warnings.filterwarnings("ignore", "", FutureWarning, ".*Controls") warnings.filterwarnings("ignore", "", FutureWarning, ".*MacTextEditor") \ No newline at end of file +# Filter out warnings about signed/unsigned constants +import warnings +warnings.filterwarnings("ignore", "", FutureWarning, ".*Controls") +warnings.filterwarnings("ignore", "", FutureWarning, ".*MacTextEditor") \ No newline at end of file Modified: pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py ============================================================================== --- vendor/cpython/Python-r234/dist/src/Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py (original) +++ pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py Thu Jan 27 17:53:02 2005 @@ -1,4 +1,6 @@ -"""Suite Standard URL suite: Mac URL standard, supported by many apps +"""Suite Standard URL suite: Mac URL standard, supported by many apps + + Level 1, version 1 Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2 @@ -19,7 +21,7 @@ } def GetURL(self, _object, _attributes={}, **_arguments): - """GetURL: Loads the URL (optionally to disk) + """GetURL: Loads the URL (optionally to disk) Required argument: The url Keyword argument to: file the URL should be loaded into Keyword argument inside: Window the URL should be loaded to From ludal at codespeak.net Thu Jan 27 18:03:08 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Thu, 27 Jan 2005 18:03:08 +0100 (MET) Subject: [pypy-svn] r8640 - pypy/dist/pypy/interpreter Message-ID: <20050127170308.5AC7227B95@code1.codespeak.net> Author: ludal Date: Thu Jan 27 18:03:08 2005 New Revision: 8640 Modified: pypy/dist/pypy/interpreter/pycode.py pypy/dist/pypy/interpreter/pyopcode.py pypy/dist/pypy/interpreter/typedef.py Log: Changes PyCode.co_names to co_names_w which is now a list of w_StringObject Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Thu Jan 27 18:03:08 2005 @@ -54,7 +54,7 @@ self.co_flags = 0 # CO_..., see above self.co_code = None # string: instruction opcodes self.co_consts_w = () # tuple: constants used (wrapped!) - self.co_names = () # tuple of strings: names (for attrs,...) + self.co_names_w = [] # list of wrapped strings: names (for attrs,...) self.co_varnames = () # tuple of strings: local variable names self.co_freevars = () # tuple of strings: free variable names self.co_cellvars = () # tuple of strings: cell variable names @@ -87,7 +87,7 @@ self.co_code = x #self.co_consts = x = code.co_names; assert isinstance(x, tuple) - self.co_names = x + self.co_names_w = [ self.space.wrap(i) for i in x ] x = code.co_varnames; assert isinstance(x, tuple) self.co_varnames = x x = code.co_freevars; assert isinstance(x, tuple) @@ -153,6 +153,10 @@ def fget_co_consts(space, w_self): self = space.interpclass_w(w_self) return space.newtuple(self.co_consts_w) + + def fget_co_names(space, w_self): + self = space.interpclass_w(w_self) + return space.newtuple(self.co_names_w) def descr_code__new__(space, w_subtype, w_argcount, w_nlocals, w_stacksize, w_flags, @@ -168,7 +172,7 @@ code.co_flags = space.int_w(w_flags) code.co_code = space.str_w(w_codestring) code.co_consts_w = space.unpacktuple(w_constants) - code.co_names = unpack_str_tuple(space, w_names) + code.co_names_w = space.unpacktuple(w_names) code.co_varnames = unpack_str_tuple(space, w_varnames) code.co_filename = space.str_w(w_filename) code.co_name = space.str_w(w_name) Modified: pypy/dist/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/dist/pypy/interpreter/pyopcode.py (original) +++ pypy/dist/pypy/interpreter/pyopcode.py Thu Jan 27 18:03:08 2005 @@ -71,8 +71,9 @@ def getconstant_w(self, index): return self.code.co_consts_w[index] - def getname(self, index): - return self.code.co_names[index] + def getname_w(self, index): + varname = self.code.co_names_w[index] + return varname ################################################################ @@ -424,14 +425,12 @@ f.valuestack.push(w_newclass) def STORE_NAME(f, varindex): - varname = f.getname(varindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(varindex) w_newvalue = f.valuestack.pop() f.space.setitem(f.w_locals, w_varname, w_newvalue) def DELETE_NAME(f, varindex): - varname = f.getname(varindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(varindex) try: f.space.delitem(f.w_locals, w_varname) except OperationError, e: @@ -453,33 +452,28 @@ def STORE_ATTR(f, nameindex): "obj.attributename = newvalue" - attributename = f.getname(nameindex) - w_attributename = f.space.wrap(attributename) + w_attributename = f.getname_w(nameindex) w_obj = f.valuestack.pop() w_newvalue = f.valuestack.pop() f.space.setattr(w_obj, w_attributename, w_newvalue) def DELETE_ATTR(f, nameindex): "del obj.attributename" - attributename = f.getname(nameindex) - w_attributename = f.space.wrap(attributename) + w_attributename = f.getname_w(nameindex) w_obj = f.valuestack.pop() f.space.delattr(w_obj, w_attributename) def STORE_GLOBAL(f, nameindex): - varname = f.getname(nameindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(nameindex) w_newvalue = f.valuestack.pop() f.space.setitem(f.w_globals, w_varname, w_newvalue) def DELETE_GLOBAL(f, nameindex): - varname = f.getname(nameindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(nameindex) f.space.delitem(f.w_globals, w_varname) def LOAD_NAME(f, nameindex): - varname = f.getname(nameindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(nameindex) if f.w_globals is f.w_locals: try_list_w = [f.w_globals, f.w_builtins] @@ -497,7 +491,7 @@ except OperationError, e: if not e.match(f.space, f.space.w_KeyError): raise - message = "name '%s' is not defined" % varname + message = "name '%s' is not defined" % f.space.str_w(w_varname) w_exc_type = f.space.w_NameError w_exc_value = f.space.wrap(message) raise OperationError(w_exc_type, w_exc_value) @@ -511,8 +505,7 @@ def LOAD_GLOBAL(f, nameindex): assert f.w_globals is not None - varname = f.getname(nameindex) - w_varname = f.space.wrap(varname) + w_varname = f.getname_w(nameindex) try: w_value = f.space.getitem(f.w_globals, w_varname) except OperationError, e: @@ -526,7 +519,7 @@ # catch KeyErrors again if not e.match(f.space, f.space.w_KeyError): raise - message = "global name '%s' is not defined" % varname + message = "global name '%s' is not defined" % f.space.str_w(w_varname) w_exc_type = f.space.w_NameError w_exc_value = f.space.wrap(message) raise OperationError(w_exc_type, w_exc_value) @@ -559,8 +552,7 @@ def LOAD_ATTR(f, nameindex): "obj.attributename" - attributename = f.getname(nameindex) - w_attributename = f.space.wrap(attributename) + w_attributename = f.getname_w(nameindex) w_obj = f.valuestack.pop() w_value = f.space.getattr(w_obj, w_attributename) f.valuestack.push(w_value) @@ -608,7 +600,8 @@ def IMPORT_NAME(f, nameindex): space = f.space - modulename = f.getname(nameindex) + w_modulename = f.getname_w(nameindex) + modulename = f.space.str_w(w_modulename) w_fromlist = f.valuestack.pop() try: w_import = space.getitem(f.w_builtins, space.wrap("__import__")) @@ -631,8 +624,7 @@ f.setdictscope(w_locals) def IMPORT_FROM(f, nameindex): - name = f.getname(nameindex) - w_name = f.space.wrap(name) + w_name = f.getname_w(nameindex) w_module = f.valuestack.top() try: w_obj = f.space.getattr(w_module, w_name) @@ -640,7 +632,7 @@ if not e.match(f.space, f.space.w_AttributeError): raise raise OperationError(f.space.w_ImportError, - f.space.wrap("cannot import name '%s'" % name)) + f.space.wrap("cannot import name '%s'" % f.space.str_w(w_name) )) f.valuestack.push(w_obj) def JUMP_FORWARD(f, stepby): Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Thu Jan 27 18:03:08 2005 @@ -200,7 +200,7 @@ co_flags = interp_attrproperty('co_flags'), co_code = interp_attrproperty('co_code'), co_consts = GetSetProperty(PyCode.fget_co_consts), - co_names = interp_attrproperty('co_names'), + co_names = GetSetProperty(PyCode.fget_co_names), co_varnames = interp_attrproperty('co_varnames'), co_freevars = interp_attrproperty('co_freevars'), co_cellvars = interp_attrproperty('co_cellvars'), From ludal at codespeak.net Thu Jan 27 18:04:16 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Thu, 27 Jan 2005 18:04:16 +0100 (MET) Subject: [pypy-svn] r8641 - pypy/dist/pypy/objspace/std Message-ID: <20050127170416.F33F727B95@code1.codespeak.net> Author: ludal Date: Thu Jan 27 18:04:16 2005 New Revision: 8641 Modified: pypy/dist/pypy/objspace/std/dictobject.py Log: uses entry.w_key instead of w_value to be consistent with the rest of the function Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Thu Jan 27 18:04:16 2005 @@ -85,7 +85,7 @@ while 1: i = (i << 2) + i + perturb + 1 entry = self.data[i%len(self.data)] - if entry.w_value is None: + if entry.w_key is None: if freeslot: return freeslot else: From ludal at codespeak.net Thu Jan 27 18:06:27 2005 From: ludal at codespeak.net (ludal at codespeak.net) Date: Thu, 27 Jan 2005 18:06:27 +0100 (MET) Subject: [pypy-svn] r8642 - pypy/dist/pypy/objspace/std Message-ID: <20050127170627.09D1727B95@code1.codespeak.net> Author: ludal Date: Thu Jan 27 18:06:26 2005 New Revision: 8642 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: keep a cache of the hash value of strings like CPython does Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Thu Jan 27 18:06:26 2005 @@ -94,6 +94,7 @@ def __init__(w_self, space, str): W_Object.__init__(w_self, space) w_self._value = str + w_self.w_hash = None def __repr__(w_self): """ representation for debugging purposes """ @@ -771,7 +772,11 @@ return w_str._value def hash__String(space, w_str): - return W_IntObject(space, hash(w_str._value)) + w_hash = w_str.w_hash + if w_hash is None: + w_hash = W_IntObject(space, hash(w_str._value)) + w_str.w_hash = w_hash + return w_hash ##EQ = 1 From tismer at codespeak.net Thu Jan 27 18:34:25 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 27 Jan 2005 18:34:25 +0100 (MET) Subject: [pypy-svn] r8643 - in pypy/dist/pypy: appspace module objspace/std translator Message-ID: <20050127173425.5D91327B95@code1.codespeak.net> Author: tismer Date: Thu Jan 27 18:34:25 2005 New Revision: 8643 Added: pypy/dist/pypy/module/exceptionsinterp.py Removed: pypy/dist/pypy/appspace/exceptions.py Modified: pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/translator/geninterplevel.py Log: exceptions is a builtin module, now. Very hackish, but it works. Deleted: /pypy/dist/pypy/appspace/exceptions.py ============================================================================== --- /pypy/dist/pypy/appspace/exceptions.py Thu Jan 27 18:34:25 2005 +++ (empty file) @@ -1,298 +0,0 @@ -class Exception: - """Common base class for all exceptions.""" - - # auto-generated code, please check carefully! - def __getitem__(self, idx): - return self.args[idx] - - # auto-generated code, please check carefully! - def __init__(self, *args): - self.args = args - - # auto-generated code, please check carefully! - def __str__(self): - argc = len(self.args) - if argc == 0: - return '' - elif argc == 1: - return str(self.args[0]) - else: - return str(self.args) - -class StandardError(Exception): - """Base class for all standard Python exceptions.""" - -class ValueError(StandardError): - """Inappropriate argument value (of correct type).""" - -class ImportError(StandardError): - """Import can't find module, or can't find name in module.""" - -class RuntimeError(StandardError): - """Unspecified run-time error.""" - -class UnicodeError(ValueError): - """Unicode related error.""" - -class UnicodeTranslateError(UnicodeError): - """Unicode translation error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 4: - self.object = args[0] - self.start = args[1] - self.end = args[2] - self.reason = args[3] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'start=' + str(self.start), - 'reason=' + str(self.reason), - 'args=' + str(self.args), - 'end=' + str(self.end), - 'object=' + str(self.object), - ]) - return res - -class LookupError(StandardError): - """Base class for lookup errors.""" - -class KeyError(LookupError): - """Mapping key not found.""" - - # auto-generated code, please check carefully! - def __str__(self): - argc = len(self.args) - if argc == 0: - return '' - elif argc == 1: - return repr(self.args[0]) - else: - return str(self.args) - -class Warning(Exception): - """Base class for warning categories.""" - -class SyntaxWarning(Warning): - """Base class for warnings about dubious syntax.""" - -class StopIteration(Exception): - """Signal the end from iterator.next().""" - -class PendingDeprecationWarning(Warning): - """Base class for warnings about features which will be deprecated in the future.""" - -class EnvironmentError(StandardError): - """Base class for I/O related errors.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args - self.errno = None # default, hopefully - self.strerror = None # default, hopefully - self.filename = None # default, hopefully - if 2 <= argc <= 3: - self.errno = args[0] - self.strerror = args[1] - if argc == 3: - self.filename = args[2] - self.args = (args[0], args[1]) - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'errno=' + str(self.errno), - 'args=' + str(self.args), - 'strerror=' + str(self.strerror), - 'filename=' + str(self.filename), - ]) - return res - -class OSError(EnvironmentError): - """OS system call failed.""" - -class DeprecationWarning(Warning): - """Base class for warnings about deprecated features.""" - -class UnicodeEncodeError(UnicodeError): - """Unicode encoding error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 5: - self.encoding = args[0] - self.object = args[1] - self.start = args[2] - self.end = args[3] - self.reason = args[4] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), - ]) - return res - -class ArithmeticError(StandardError): - """Base class for arithmetic errors.""" - -class FloatingPointError(ArithmeticError): - """Floating point operation failed.""" - -class ReferenceError(StandardError): - """Weak ref proxy used after referent went away.""" - -class NameError(StandardError): - """Name not found globally.""" - -class OverflowWarning(Warning): - """Base class for warnings about numeric overflow.""" - -class IOError(EnvironmentError): - """I/O operation failed.""" - -class SyntaxError(StandardError): - """Invalid syntax.""" - filename = None - lineno = None - msg = '' - offset = None - print_file_and_line = None - text = None - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args - if argc >= 1: - self.msg = args[0] - if argc == 2: - self.filename = args[1][0] - self.lineno = args[1][1] - self.offset = args[1][2] - self.text = args[1][3] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'args=' + str(self.args), - ]) - return res - -class FutureWarning(Warning): - """Base class for warnings about constructs that will change semantically in the future.""" - -class SystemExit(Exception): - """Request to exit from the interpreter.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - if argc == 0: - self.code = None # default, hopefully - self.args = args - if argc == 1: - self.code = args[0] - if argc >= 2: - self.code = args - -class EOFError(StandardError): - """Read beyond end of file.""" - -class IndentationError(SyntaxError): - """Improper indentation.""" - -class TabError(IndentationError): - """Improper mixture of spaces and tabs.""" - -class ZeroDivisionError(ArithmeticError): - """Second argument to a division or modulo operation was zero.""" - -class SystemError(StandardError): - """Internal error in the Python interpreter. - -Please report this to the Python maintainer, along with the traceback, -the Python version, and the hardware/OS platform and version.""" - -class AssertionError(StandardError): - """Assertion failed.""" - -class UnicodeDecodeError(UnicodeError): - """Unicode decoding error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 5: - self.encoding = args[0] - self.object = args[1] - self.start = args[2] - self.end = args[3] - self.reason = args[4] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), - ]) - return res - -class TypeError(StandardError): - """Inappropriate argument type.""" - -class IndexError(LookupError): - """Sequence index out of range.""" - -class RuntimeWarning(Warning): - """Base class for warnings about dubious runtime behavior.""" - -class KeyboardInterrupt(StandardError): - """Program interrupted by user.""" - -class UserWarning(Warning): - """Base class for warnings generated by user code.""" - -class TaskletExit(SystemExit): - """Request to exit from a tasklet.""" - -class MemoryError(StandardError): - """Out of memory.""" - -class UnboundLocalError(NameError): - """Local name referenced but not bound to a value.""" - -class NotImplementedError(RuntimeError): - """Method or function hasn't been implemented yet.""" - -class AttributeError(StandardError): - """Attribute not found.""" - -class OverflowError(ArithmeticError): - """Result too large to be represented.""" - -class WindowsError(OSError): - """MS-Windows OS system call failed.""" - Added: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/module/exceptionsinterp.py Thu Jan 27 18:34:25 2005 @@ -0,0 +1,1603 @@ +#!/bin/env python +# -*- coding: LATIN-1 -*- +##SECTION## +## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' +## function 'test_exceptions' +## firstlineno 1253 +##SECTION## +# global declarations +# global object gfunc_test_exceptions +# global object gbltinmethod_keys +# global object g48dict +# global object gs_keys + +def test_exceptions(space, *args_w): + """ enumerate all exceptions """ + kwlist = [] + _args_w = args_w + defaults_w = () + funcname = "test_exceptions" + PyArg_ParseMini(space, funcname, 0, 0, _args_w, defaults_w) + return fastf_test_exceptions(space, ) +f_test_exceptions = globals().pop("test_exceptions") + +def test_exceptions(space, ): + """ enumerate all exceptions """ + + w_0=w_0=w_1=None + + goto = 1 # startblock + while True: + + if goto == 1: + _tup = space.newtuple([]) + w_0 = space.call(gbltinmethod_keys, _tup) + w_1 = w_0 + goto = 2 + + if goto == 2: + return w_1 +fastf_test_exceptions = globals().pop("test_exceptions") + +# global declarations +# global object gs_MemoryError +# global object gcls_MemoryError +# global object gcls_StandardError +# global object gcls_Exception +# global object gs___module__ +# global object gs_pypy_appspace__exceptions +# global object gs___doc__ +# global object gs_Exception +# global object gs_StandardError +# global object gs_ImportError +# global object gcls_ImportError +# global object gs_RuntimeError +# global object gcls_RuntimeError +# global object gs_UnicodeTranslateError +# global object gcls_UnicodeTranslateError +# global object gcls_UnicodeError +# global object gcls_ValueError +# global object gs_ValueError +# global object gs_UnicodeError +# global object gs_KeyError +# global object gcls_KeyError +# global object gcls_LookupError +# global object gs_LookupError +# global object gs_SyntaxWarning +# global object gcls_SyntaxWarning +# global object gcls_Warning +# global object gs_Warning +# global object gs_StopIteration +# global object gcls_StopIteration +# global object gs_PendingDeprecationWarning +# global object gcls_PendingDeprecationWarning +# global object gs_EnvironmentError +# global object gcls_EnvironmentError +# global object gs_SyntaxError +# global object gcls_SyntaxError +# global object gs_OSError +# global object gcls_OSError +# global object gs_DeprecationWarning +# global object gcls_DeprecationWarning +# global object gs_FloatingPointError +# global object gcls_FloatingPointError +# global object gcls_ArithmeticError +# global object gs_ArithmeticError +# global object gs_ReferenceError +# global object gcls_ReferenceError +# global object gs_NameError +# global object gcls_NameError +# global object gs_OverflowWarning +# global object gcls_OverflowWarning +# global object gs_IOError +# global object gcls_IOError +# global object gs_FutureWarning +# global object gcls_FutureWarning +# global object gs_SystemExit +# global object gcls_SystemExit +# global object gs_EOFError +# global object gcls_EOFError +# global object gs___file__ +# global object gs_D___pypy__dist__pypy__appspace__ +# global object gs_TabError +# global object gcls_TabError +# global object gcls_IndentationError +# global object gs_IndentationError +# global object gs_ZeroDivisionError +# global object gcls_ZeroDivisionError +# global object gs_UnicodeEncodeError +# global object gcls_UnicodeEncodeError +# global object gs_SystemError +# global object gcls_SystemError +# global object gs___name__ +# global object gs_AssertionError +# global object gcls_AssertionError +# global object gs_UnicodeDecodeError +# global object gcls_UnicodeDecodeError +# global object gs_TypeError +# global object gcls_TypeError +# global object gs_IndexError +# global object gcls_IndexError +# global object gs_RuntimeWarning +# global object gcls_RuntimeWarning +# global object gs_KeyboardInterrupt +# global object gcls_KeyboardInterrupt +# global object gs_UserWarning +# global object gcls_UserWarning +# global object gs_TaskletExit +# global object gcls_TaskletExit +# global object gs_UnboundLocalError +# global object gcls_UnboundLocalError +# global object gs_NotImplementedError +# global object gcls_NotImplementedError +# global object gs_AttributeError +# global object gcls_AttributeError +# global object gs_OverflowError +# global object gcls_OverflowError +# global object gs_WindowsError +# global object gcls_WindowsError +# global object gs___init__ +# global object gfunc_UnicodeDecodeError___init__ +# global object gs___str__ +# global object gfunc_UnicodeDecodeError___str__ +# global object gfunc_UnicodeEncodeError___init__ +# global object gfunc_UnicodeEncodeError___str__ +# global object gfunc_SystemExit___init__ +# global object gfunc_SyntaxError___init__ +# global object gfunc_SyntaxError___str__ +# global object gs_filename +# global object gs_lineno +# global object gs_msg +# global object gs__emptystr_ +# global object gs_offset +# global object gs_print_file_and_line +# global object gs_text +# global object gfunc_EnvironmentError___init__ +# global object gfunc_EnvironmentError___str__ +# global object gfunc_KeyError___str__ +# global object gfunc_UnicodeTranslateError___init__ +# global object gfunc_UnicodeTranslateError___str__ +# global object gs___getitem__ +# global object gfunc_Exception___getitem__ +# global object gfunc_Exception___init__ +# global object gfunc_Exception___str__ + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__getitem__' +## firstlineno 5 +##SECTION## +def __getitem__(space, *args_w): + kwlist = ["self", "idx"] + _args_w = args_w + defaults_w = () + funcname = "__getitem__" + w_self_1, w_idx_3 = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) + return fastf_Exception___getitem__(space, w_self_1, w_idx_3) +f_Exception___getitem__ = globals().pop("__getitem__") + +def __getitem__(space, w_self_1, w_idx_3): + + w_0=w_0=w_2=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_2 = space.getitem(w_0, w_idx_3) + w_4 = w_2 + goto = 2 + + if goto == 2: + return w_4 +fastf_Exception___getitem__ = globals().pop("__getitem__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 9 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_2 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___init__(space, w_self_1, w_args_2) +f_Exception___init__ = globals().pop("__init__") + +def __init__(space, w_self_1, w_args_2): + + w_0=w_0=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.setattr(w_self_1, gs_args, w_args_2) + w_3 = space.w_None + goto = 2 + + if goto == 2: + return w_3 +fastf_Exception___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 13 +##SECTION## +# global declarations +# global object gs_args +# global object gi_0 +# global object gi_1 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___str__(space, w_self_1) +f_Exception___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None + w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None + w_14=w_14=w_15=w_19=w_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_argc_2 = space.len(w_0) + w_3 = space.eq(w_argc_2, gi_0) + v4 = space.is_true(w_3) + if v4 == True: + w_5 = gs__emptystr_ + goto = 5 + else: + assert v4 == False + w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + goto = 2 + + if goto == 2: + w_9 = space.eq(w_argc_7, gi_1) + v10 = space.is_true(w_9) + if v10 == True: + (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, + w_8, w_9, v10) + goto = 3 + else: + assert v10 == False + w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + goto = 4 + + if goto == 3: + w_19 = space.getattr(w_self_11, gs_args) + w_20 = space.getitem(w_19, gi_0) + _tup = space.newtuple([w_20]) + w_21 = space.call(space.w_str, _tup) + w_5 = w_21 + goto = 5 + + if goto == 4: + w_22 = space.getattr(w_self_16, gs_args) + _tup = space.newtuple([w_22]) + w_23 = space.call(space.w_str, _tup) + w_5 = w_23 + goto = 5 + + if goto == 5: + return w_5 +fastf_Exception___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 41 +##SECTION## +# global declarations +# global object gi_4 +# global object gi_2 +# global object gi_3 + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___init__(space, w_self_3, w_args_1) +f_UnicodeTranslateError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_4) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_object, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_start, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_end, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_reason, w_19) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeTranslateError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 51 +##SECTION## +# global declarations +# global object gs_start +# global object gs_start_ +# global object gs_reason +# global object gs_reason_ +# global object gs_args_ +# global object gs_end +# global object gs_end_ +# global object gs_object +# global object gs_object_ +# global object gbltinmethod_join +# global object gs__ +# global object gs_join + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___str__(space, w_self_1) +f_UnicodeTranslateError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_res_17=w_18=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_start_, w_2) + w_4 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_reason_, w_5) + w_7 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_args_, w_8) + w_10 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_end_, w_11) + w_13 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_object_, w_14) + w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) + _tup = space.newtuple([w_16]) + w_res_17 = space.call(gbltinmethod_join, _tup) + w_18 = w_res_17 + goto = 2 + + if goto == 2: + return w_18 +fastf_UnicodeTranslateError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 69 +##SECTION## +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_KeyError___str__(space, w_self_1) +f_KeyError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None + w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None + w_14=w_14=w_15=w_19=w_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_argc_2 = space.len(w_0) + w_3 = space.eq(w_argc_2, gi_0) + v4 = space.is_true(w_3) + if v4 == True: + w_5 = gs__emptystr_ + goto = 5 + else: + assert v4 == False + w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + goto = 2 + + if goto == 2: + w_9 = space.eq(w_argc_7, gi_1) + v10 = space.is_true(w_9) + if v10 == True: + (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, + w_8, w_9, v10) + goto = 3 + else: + assert v10 == False + w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + goto = 4 + + if goto == 3: + w_19 = space.getattr(w_self_11, gs_args) + w_20 = space.getitem(w_19, gi_0) + w_21 = space.repr(w_20) + w_5 = w_21 + goto = 5 + + if goto == 4: + w_22 = space.getattr(w_self_16, gs_args) + _tup = space.newtuple([w_22]) + w_23 = space.call(space.w_str, _tup) + w_5 = w_23 + goto = 5 + + if goto == 5: + return w_5 +fastf_KeyError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 94 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___init__(space, w_self_3, w_args_1) +f_EnvironmentError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=None + w_argc_20=w_argc_20=w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=None + v37=v37=w_43=w_self_38=w_args_39=w_argc_40=w_41=w_42=w_44=w_45=None + w_46=w_46=w_47=w_48=w_49=w_self_24=w_args_25=w_argc_26=w_27=w_28=None + w_32=w_32=w_33=w_34=w_35=w_self_9=w_args_10=w_argc_11=w_12=w_13=None + w_14=w_14=w_15=w_16=w_17=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.setattr(w_self_3, gs_errno, space.w_None) + w_5 = space.setattr(w_self_3, gs_strerror, space.w_None) + w_6 = space.setattr(w_self_3, gs_filename, space.w_None) + w_7 = space.le(gi_2, w_argc_0) + v8 = space.is_true(w_7) + if v8 == True: + (w_self_9, w_args_10, w_argc_11, w_12, w_13, w_14, w_15, w_16, + w_17) = (w_self_3, w_args_1, w_argc_0, w_2, w_4, w_5, w_6, w_7, + v8) + goto = 2 + else: + assert v8 == False + (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_3, w_args_1, + w_argc_0, w_7) + goto = 3 + + if goto == 2: + w_22 = space.le(w_argc_11, gi_3) + (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_9, w_args_10, + w_argc_11, w_22) + goto = 3 + + if goto == 3: + v23 = space.is_true(w_21) + if v23 == True: + (w_self_24, w_args_25, w_argc_26, w_27, w_28) = (w_self_18, + w_args_19, w_argc_20, w_21, v23) + goto = 4 + else: + assert v23 == False + w_self_29, w_args_30, w_argc_31 = w_self_18, w_args_19, w_argc_20 + goto = 5 + + if goto == 4: + w_32 = space.getitem(w_args_25, gi_0) + w_33 = space.setattr(w_self_24, gs_errno, w_32) + w_34 = space.getitem(w_args_25, gi_1) + w_35 = space.setattr(w_self_24, gs_strerror, w_34) + w_self_29, w_args_30, w_argc_31 = w_self_24, w_args_25, w_argc_26 + goto = 5 + + if goto == 5: + w_36 = space.eq(w_argc_31, gi_3) + v37 = space.is_true(w_36) + if v37 == True: + (w_self_38, w_args_39, w_argc_40, w_41, w_42) = (w_self_29, + w_args_30, w_argc_31, w_36, v37) + goto = 6 + else: + assert v37 == False + w_43 = space.w_None + goto = 7 + + if goto == 6: + w_44 = space.getitem(w_args_39, gi_2) + w_45 = space.setattr(w_self_38, gs_filename, w_44) + w_46 = space.getitem(w_args_39, gi_0) + w_47 = space.getitem(w_args_39, gi_1) + w_48 = space.newtuple([w_46, w_47]) + w_49 = space.setattr(w_self_38, gs_args, w_48) + w_43 = space.w_None + goto = 7 + + if goto == 7: + return w_43 +fastf_EnvironmentError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 108 +##SECTION## +# global declarations +# global object gs_errno +# global object gs_errno_ +# global object gs_strerror +# global object gs_strerror_ +# global object gs_filename_ +# global object gbltinmethod_join_1 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___str__(space, w_self_1) +f_EnvironmentError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None + w_15=w_15=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_errno) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_errno_, w_2) + w_4 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_args_, w_5) + w_7 = space.getattr(w_self_1, gs_strerror) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_strerror_, w_8) + w_10 = space.getattr(w_self_1, gs_filename) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_filename_, w_11) + w_13 = space.newlist([w_3, w_6, w_9, w_12]) + _tup = space.newtuple([w_13]) + w_res_14 = space.call(gbltinmethod_join_1, _tup) + w_15 = w_res_14 + goto = 2 + + if goto == 2: + return w_15 +fastf_EnvironmentError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 128 +##SECTION## +# global declaration +# global object gi_5 + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) +f_UnicodeEncodeError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None + w_22=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_5) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_encoding, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_object, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_start, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_end, w_19) + w_21 = space.getitem(w_args_7, gi_4) + w_22 = space.setattr(w_self_6, gs_reason, w_21) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeEncodeError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 139 +##SECTION## +# global declarations +# global object gs_encoding +# global object gs_encoding_ +# global object gbltinmethod_join_3 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___str__(space, w_self_1) +f_UnicodeEncodeError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_object_, w_2) + w_4 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_end_, w_5) + w_7 = space.getattr(w_self_1, gs_encoding) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_encoding_, w_8) + w_10 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_args_, w_11) + w_13 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_start_, w_14) + w_16 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_16]) + w_17 = space.call(space.w_str, _tup) + w_18 = space.add(gs_reason_, w_17) + w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) + _tup = space.newtuple([w_19]) + w_res_20 = space.call(gbltinmethod_join_3, _tup) + w_21 = w_res_20 + goto = 2 + + if goto == 2: + return w_21 +fastf_UnicodeEncodeError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 179 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___init__(space, w_self_3, w_args_1) +f_SyntaxError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=None + v18=v18=w_24=w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=None + w_27=w_27=w_28=w_29=w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=None + w_args_7=w_args_7=w_argc_8=w_9=w_10=w_11=w_15=w_16=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.ge(w_argc_0, gi_1) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_self_12, w_args_13, w_argc_14 = w_self_3, w_args_1, w_argc_0 + goto = 3 + + if goto == 2: + w_15 = space.getitem(w_args_7, gi_0) + w_16 = space.setattr(w_self_6, gs_msg, w_15) + w_self_12, w_args_13, w_argc_14 = w_self_6, w_args_7, w_argc_8 + goto = 3 + + if goto == 3: + w_17 = space.eq(w_argc_14, gi_2) + v18 = space.is_true(w_17) + if v18 == True: + (w_self_19, w_args_20, w_argc_21, w_22, w_23) = (w_self_12, + w_args_13, w_argc_14, w_17, v18) + goto = 4 + else: + assert v18 == False + w_24 = space.w_None + goto = 5 + + if goto == 4: + w_25 = space.getitem(w_args_20, gi_1) + w_26 = space.getitem(w_25, gi_0) + w_27 = space.setattr(w_self_19, gs_filename, w_26) + w_28 = space.getitem(w_args_20, gi_1) + w_29 = space.getitem(w_28, gi_1) + w_30 = space.setattr(w_self_19, gs_lineno, w_29) + w_31 = space.getitem(w_args_20, gi_1) + w_32 = space.getitem(w_31, gi_2) + w_33 = space.setattr(w_self_19, gs_offset, w_32) + w_34 = space.getitem(w_args_20, gi_1) + w_35 = space.getitem(w_34, gi_3) + w_36 = space.setattr(w_self_19, gs_text, w_35) + w_24 = space.w_None + goto = 5 + + if goto == 5: + return w_24 +fastf_SyntaxError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 191 +##SECTION## +# global declaration +# global object gbltinmethod_join_2 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___str__(space, w_self_1) +f_SyntaxError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_res_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_args_, w_2) + w_4 = space.newlist([w_3]) + _tup = space.newtuple([w_4]) + w_res_5 = space.call(gbltinmethod_join_2, _tup) + w_6 = w_res_5 + goto = 2 + + if goto == 2: + return w_6 +fastf_SyntaxError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 205 +##SECTION## +# global declaration +# global object gs_code + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_4, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SystemExit___init__(space, w_self_4, w_args_1) +f_SystemExit___init__ = globals().pop("__init__") + +def __init__(space, w_self_4, w_args_1): + + w_argc_0=w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=None + v16=v16=w_self_23=w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=None + w_args_31=w_args_31=w_argc_32=w_33=w_34=w_36=w_self_17=w_args_18=None + w_argc_19=w_argc_19=w_20=w_21=w_22=w_26=w_27=w_self_5=w_args_6=None + w_argc_7=w_argc_7=w_8=w_9=w_13=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.eq(w_argc_0, gi_0) + v3 = space.is_true(w_2) + if v3 == True: + (w_self_5, w_args_6, w_argc_7, w_8, w_9) = (w_self_4, w_args_1, + w_argc_0, w_2, v3) + goto = 2 + else: + assert v3 == False + w_self_10, w_args_11, w_argc_12 = w_self_4, w_args_1, w_argc_0 + goto = 3 + + if goto == 2: + w_13 = space.setattr(w_self_5, gs_code, space.w_None) + w_self_10, w_args_11, w_argc_12 = w_self_5, w_args_6, w_argc_7 + goto = 3 + + if goto == 3: + w_14 = space.setattr(w_self_10, gs_args, w_args_11) + w_15 = space.eq(w_argc_12, gi_1) + v16 = space.is_true(w_15) + if v16 == True: + (w_self_17, w_args_18, w_argc_19, w_20, w_21, w_22) = (w_self_10, + w_args_11, w_argc_12, w_14, w_15, v16) + goto = 4 + else: + assert v16 == False + w_self_23, w_args_24, w_argc_25 = w_self_10, w_args_11, w_argc_12 + goto = 5 + + if goto == 4: + w_26 = space.getitem(w_args_18, gi_0) + w_27 = space.setattr(w_self_17, gs_code, w_26) + w_self_23, w_args_24, w_argc_25 = w_self_17, w_args_18, w_argc_19 + goto = 5 + + if goto == 5: + w_28 = space.ge(w_argc_25, gi_2) + v29 = space.is_true(w_28) + if v29 == True: + (w_self_30, w_args_31, w_argc_32, w_33, w_34) = (w_self_23, + w_args_24, w_argc_25, w_28, v29) + goto = 6 + else: + assert v29 == False + w_35 = space.w_None + goto = 7 + + if goto == 6: + w_36 = space.setattr(w_self_30, gs_code, w_args_31) + w_35 = space.w_None + goto = 7 + + if goto == 7: + return w_35 +fastf_SystemExit___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__init__' +## firstlineno 240 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___init__(space, w_self_3, w_args_1) +f_UnicodeDecodeError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None + w_22=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_5) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_encoding, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_object, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_start, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_end, w_19) + w_21 = space.getitem(w_args_7, gi_4) + w_22 = space.setattr(w_self_6, gs_reason, w_21) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeDecodeError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' +## function '__str__' +## firstlineno 251 +##SECTION## +# global declaration +# global object gbltinmethod_join_4 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___str__(space, w_self_1) +f_UnicodeDecodeError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_object_, w_2) + w_4 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_end_, w_5) + w_7 = space.getattr(w_self_1, gs_encoding) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_encoding_, w_8) + w_10 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_args_, w_11) + w_13 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_start_, w_14) + w_16 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_16]) + w_17 = space.call(space.w_str, _tup) + w_18 = space.add(gs_reason_, w_17) + w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) + _tup = space.newtuple([w_19]) + w_res_20 = space.call(gbltinmethod_join_4, _tup) + w_21 = w_res_20 + goto = 2 + + if goto == 2: + return w_21 +fastf_UnicodeDecodeError___str__ = globals().pop("__str__") + +##SECTION## +#************************************************************* + +def inittest_exceptions_1(space): + """NOT_RPYTHON""" + class m: pass # fake module + m.__dict__ = globals() + + from pypy.interpreter.gateway import interp2app + m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) + m.g48dict = space.newdict([]) + m.gs_keys = space.wrap('keys') + m.gbltinmethod_keys = space.getattr(g48dict, gs_keys) + from pypy.translator.geninterplevel import PyArg_ParseMini + m.PyArg_ParseMini = PyArg_ParseMini + from pypy.interpreter.error import OperationError + m.OperationError = OperationError + m.gs_MemoryError = space.wrap('MemoryError') + _dic = space.newdict([]) + m.gs___module__ = space.wrap('__module__') + m.gs_pypy_appspace__exceptions = space.wrap('pypy.appspace._exceptions') + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + m.gs___doc__ = space.wrap('__doc__') + _doc = space.wrap("""Common base class for all exceptions.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_Exception = space.wrap('Exception') + _bases = space.newtuple([]) + _args = space.newtuple([gs_Exception, _bases, _dic]) + m.gcls_Exception = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for all standard Python exceptions.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_StandardError = space.wrap('StandardError') + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_StandardError, _bases, _dic]) + m.gcls_StandardError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Out of memory.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_MemoryError, _bases, _dic]) + m.gcls_MemoryError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_MemoryError, gcls_MemoryError) + m.gs_ImportError = space.wrap('ImportError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Import can't find module, or can't find name in module.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ImportError, _bases, _dic]) + m.gcls_ImportError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_ImportError, gcls_ImportError) + m.gs_RuntimeError = space.wrap('RuntimeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unspecified run-time error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_RuntimeError, _bases, _dic]) + m.gcls_RuntimeError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_RuntimeError, gcls_RuntimeError) + m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Inappropriate argument value (of correct type).""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_ValueError = space.wrap('ValueError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ValueError, _bases, _dic]) + m.gcls_ValueError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode related error.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_UnicodeError = space.wrap('UnicodeError') + _bases = space.newtuple([gcls_ValueError]) + _args = space.newtuple([gs_UnicodeError, _bases, _dic]) + m.gcls_UnicodeError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode translation error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeTranslateError, _bases, _dic]) + m.gcls_UnicodeTranslateError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) + m.gs_KeyError = space.wrap('KeyError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for lookup errors.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_LookupError = space.wrap('LookupError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_LookupError, _bases, _dic]) + m.gcls_LookupError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Mapping key not found.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_LookupError]) + _args = space.newtuple([gs_KeyError, _bases, _dic]) + m.gcls_KeyError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_KeyError, gcls_KeyError) + m.gs_SyntaxWarning = space.wrap('SyntaxWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warning categories.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_Warning = space.wrap('Warning') + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_Warning, _bases, _dic]) + m.gcls_Warning = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about dubious syntax.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) + m.gcls_SyntaxWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_SyntaxWarning, gcls_SyntaxWarning) + m.gs_StopIteration = space.wrap('StopIteration') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Signal the end from iterator.next().""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_StopIteration, _bases, _dic]) + m.gcls_StopIteration = space.call(space.w_type, _args) + space.setitem(g48dict, gs_StopIteration, gcls_StopIteration) + m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) + m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) + m.gs_EnvironmentError = space.wrap('EnvironmentError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for I/O related errors.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_EnvironmentError, _bases, _dic]) + m.gcls_EnvironmentError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_EnvironmentError, gcls_EnvironmentError) + m.gs_SyntaxError = space.wrap('SyntaxError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Invalid syntax.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_SyntaxError, _bases, _dic]) + m.gcls_SyntaxError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_SyntaxError, gcls_SyntaxError) + space.setitem(g48dict, gs_LookupError, gcls_LookupError) + m.gs_OSError = space.wrap('OSError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""OS system call failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_EnvironmentError]) + _args = space.newtuple([gs_OSError, _bases, _dic]) + m.gcls_OSError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_OSError, gcls_OSError) + m.gs_DeprecationWarning = space.wrap('DeprecationWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about deprecated features.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_DeprecationWarning, _bases, _dic]) + m.gcls_DeprecationWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_DeprecationWarning, gcls_DeprecationWarning) + space.setitem(g48dict, gs_UnicodeError, gcls_UnicodeError) + m.gs_FloatingPointError = space.wrap('FloatingPointError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for arithmetic errors.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_ArithmeticError = space.wrap('ArithmeticError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ArithmeticError, _bases, _dic]) + m.gcls_ArithmeticError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Floating point operation failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_FloatingPointError, _bases, _dic]) + m.gcls_FloatingPointError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_FloatingPointError, gcls_FloatingPointError) + m.gs_ReferenceError = space.wrap('ReferenceError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Weak ref proxy used after referent went away.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ReferenceError, _bases, _dic]) + m.gcls_ReferenceError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_ReferenceError, gcls_ReferenceError) + m.gs_NameError = space.wrap('NameError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Name not found globally.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_NameError, _bases, _dic]) + m.gcls_NameError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_NameError, gcls_NameError) + m.gs_OverflowWarning = space.wrap('OverflowWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about numeric overflow.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_OverflowWarning, _bases, _dic]) + m.gcls_OverflowWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_OverflowWarning, gcls_OverflowWarning) + m.gs_IOError = space.wrap('IOError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""I/O operation failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_EnvironmentError]) + _args = space.newtuple([gs_IOError, _bases, _dic]) + m.gcls_IOError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_IOError, gcls_IOError) + space.setitem(g48dict, gs_ValueError, gcls_ValueError) + m.gs_FutureWarning = space.wrap('FutureWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about constructs that will change semantically in the future.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_FutureWarning, _bases, _dic]) + m.gcls_FutureWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_FutureWarning, gcls_FutureWarning) + m.gs_SystemExit = space.wrap('SystemExit') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Request to exit from the interpreter.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_SystemExit, _bases, _dic]) + m.gcls_SystemExit = space.call(space.w_type, _args) + space.setitem(g48dict, gs_SystemExit, gcls_SystemExit) + space.setitem(g48dict, gs_Exception, gcls_Exception) + m.gs_EOFError = space.wrap('EOFError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Read beyond end of file.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_EOFError, _bases, _dic]) + m.gcls_EOFError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_EOFError, gcls_EOFError) + space.setitem(g48dict, gs_StandardError, gcls_StandardError) + m.gs___file__ = space.wrap('__file__') + m.gs_D___pypy__dist__pypy__appspace__ = space.wrap('D:\\pypy\\dist\\pypy\\appspace\\_exceptions.pyc') + space.setitem(g48dict, gs___file__, gs_D___pypy__dist__pypy__appspace__) + m.gs_TabError = space.wrap('TabError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Improper indentation.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_IndentationError = space.wrap('IndentationError') + _bases = space.newtuple([gcls_SyntaxError]) + _args = space.newtuple([gs_IndentationError, _bases, _dic]) + m.gcls_IndentationError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Improper mixture of spaces and tabs.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_IndentationError]) + _args = space.newtuple([gs_TabError, _bases, _dic]) + m.gcls_TabError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_TabError, gcls_TabError) + m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Second argument to a division or modulo operation was zero.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_ZeroDivisionError, _bases, _dic]) + m.gcls_ZeroDivisionError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) + m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode encoding error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeEncodeError, _bases, _dic]) + m.gcls_UnicodeEncodeError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) + m.gs_SystemError = space.wrap('SystemError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Internal error in the Python interpreter. + + Please report this to the Python maintainer, along with the traceback, + the Python version, and the hardware/OS platform and version.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_SystemError, _bases, _dic]) + m.gcls_SystemError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_SystemError, gcls_SystemError) + m.gs___name__ = space.wrap('__name__') + space.setitem(g48dict, gs___name__, gs_pypy_appspace__exceptions) + space.setitem(g48dict, gs_IndentationError, gcls_IndentationError) + m.gs_AssertionError = space.wrap('AssertionError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Assertion failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_AssertionError, _bases, _dic]) + m.gcls_AssertionError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_AssertionError, gcls_AssertionError) + m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode decoding error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeDecodeError, _bases, _dic]) + m.gcls_UnicodeDecodeError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) + m.gs_TypeError = space.wrap('TypeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Inappropriate argument type.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_TypeError, _bases, _dic]) + m.gcls_TypeError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_TypeError, gcls_TypeError) + m.gs_IndexError = space.wrap('IndexError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Sequence index out of range.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_LookupError]) + _args = space.newtuple([gs_IndexError, _bases, _dic]) + m.gcls_IndexError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_IndexError, gcls_IndexError) + m.gs_RuntimeWarning = space.wrap('RuntimeWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about dubious runtime behavior.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_RuntimeWarning, _bases, _dic]) + m.gcls_RuntimeWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_RuntimeWarning, gcls_RuntimeWarning) + m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Program interrupted by user.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_KeyboardInterrupt, _bases, _dic]) + m.gcls_KeyboardInterrupt = space.call(space.w_type, _args) + space.setitem(g48dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) + space.setitem(g48dict, gs___doc__, space.w_None) + m.gs_UserWarning = space.wrap('UserWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings generated by user code.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_UserWarning, _bases, _dic]) + m.gcls_UserWarning = space.call(space.w_type, _args) + space.setitem(g48dict, gs_UserWarning, gcls_UserWarning) + m.gs_TaskletExit = space.wrap('TaskletExit') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Request to exit from a tasklet.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_SystemExit]) + _args = space.newtuple([gs_TaskletExit, _bases, _dic]) + m.gcls_TaskletExit = space.call(space.w_type, _args) + space.setitem(g48dict, gs_TaskletExit, gcls_TaskletExit) + m.gs_UnboundLocalError = space.wrap('UnboundLocalError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Local name referenced but not bound to a value.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_NameError]) + _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) + m.gcls_UnboundLocalError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_UnboundLocalError, gcls_UnboundLocalError) + space.setitem(g48dict, gs_ArithmeticError, gcls_ArithmeticError) + space.setitem(g48dict, gs_Warning, gcls_Warning) + m.gs_NotImplementedError = space.wrap('NotImplementedError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Method or function hasn't been implemented yet.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_RuntimeError]) + _args = space.newtuple([gs_NotImplementedError, _bases, _dic]) + m.gcls_NotImplementedError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_NotImplementedError, gcls_NotImplementedError) + m.gs_AttributeError = space.wrap('AttributeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Attribute not found.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_AttributeError, _bases, _dic]) + m.gcls_AttributeError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_AttributeError, gcls_AttributeError) + m.gs_OverflowError = space.wrap('OverflowError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Result too large to be represented.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_OverflowError, _bases, _dic]) + m.gcls_OverflowError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_OverflowError, gcls_OverflowError) + m.gs_WindowsError = space.wrap('WindowsError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""MS-Windows OS system call failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_OSError]) + _args = space.newtuple([gs_WindowsError, _bases, _dic]) + m.gcls_WindowsError = space.call(space.w_type, _args) + space.setitem(g48dict, gs_WindowsError, gcls_WindowsError) + m.gs___init__ = space.wrap('__init__') + m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) + space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) + m.gs___str__ = space.wrap('__str__') + m.gfunc_UnicodeDecodeError___str__ = space.wrap(interp2app(f_UnicodeDecodeError___str__)) + space.setattr(gcls_UnicodeDecodeError, gs___str__, gfunc_UnicodeDecodeError___str__) + m.gfunc_UnicodeEncodeError___init__ = space.wrap(interp2app(f_UnicodeEncodeError___init__)) + space.setattr(gcls_UnicodeEncodeError, gs___init__, gfunc_UnicodeEncodeError___init__) + m.gfunc_UnicodeEncodeError___str__ = space.wrap(interp2app(f_UnicodeEncodeError___str__)) + space.setattr(gcls_UnicodeEncodeError, gs___str__, gfunc_UnicodeEncodeError___str__) + m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) + space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) + m.gfunc_SyntaxError___init__ = space.wrap(interp2app(f_SyntaxError___init__)) + space.setattr(gcls_SyntaxError, gs___init__, gfunc_SyntaxError___init__) + m.gfunc_SyntaxError___str__ = space.wrap(interp2app(f_SyntaxError___str__)) + space.setattr(gcls_SyntaxError, gs___str__, gfunc_SyntaxError___str__) + m.gs_filename = space.wrap('filename') + space.setattr(gcls_SyntaxError, gs_filename, space.w_None) + m.gs_lineno = space.wrap('lineno') + space.setattr(gcls_SyntaxError, gs_lineno, space.w_None) + m.gs_msg = space.wrap('msg') + m.gs__emptystr_ = space.wrap('') + space.setattr(gcls_SyntaxError, gs_msg, gs__emptystr_) + m.gs_offset = space.wrap('offset') + space.setattr(gcls_SyntaxError, gs_offset, space.w_None) + m.gs_print_file_and_line = space.wrap('print_file_and_line') + space.setattr(gcls_SyntaxError, gs_print_file_and_line, space.w_None) + m.gs_text = space.wrap('text') + space.setattr(gcls_SyntaxError, gs_text, space.w_None) + m.gfunc_EnvironmentError___init__ = space.wrap(interp2app(f_EnvironmentError___init__)) + space.setattr(gcls_EnvironmentError, gs___init__, gfunc_EnvironmentError___init__) + m.gfunc_EnvironmentError___str__ = space.wrap(interp2app(f_EnvironmentError___str__)) + space.setattr(gcls_EnvironmentError, gs___str__, gfunc_EnvironmentError___str__) + m.gfunc_KeyError___str__ = space.wrap(interp2app(f_KeyError___str__)) + space.setattr(gcls_KeyError, gs___str__, gfunc_KeyError___str__) + m.gfunc_UnicodeTranslateError___init__ = space.wrap(interp2app(f_UnicodeTranslateError___init__)) + space.setattr(gcls_UnicodeTranslateError, gs___init__, gfunc_UnicodeTranslateError___init__) + m.gfunc_UnicodeTranslateError___str__ = space.wrap(interp2app(f_UnicodeTranslateError___str__)) + space.setattr(gcls_UnicodeTranslateError, gs___str__, gfunc_UnicodeTranslateError___str__) + m.gs___getitem__ = space.wrap('__getitem__') + m.gfunc_Exception___getitem__ = space.wrap(interp2app(f_Exception___getitem__)) + space.setattr(gcls_Exception, gs___getitem__, gfunc_Exception___getitem__) + m.gfunc_Exception___init__ = space.wrap(interp2app(f_Exception___init__)) + space.setattr(gcls_Exception, gs___init__, gfunc_Exception___init__) + m.gfunc_Exception___str__ = space.wrap(interp2app(f_Exception___str__)) + space.setattr(gcls_Exception, gs___str__, gfunc_Exception___str__) + m.gs_args = space.wrap('args') + m.gi_0 = space.newint(0) + m.gi_1 = space.newint(1) + m.gs_start = space.wrap('start') + m.gs_start_ = space.wrap('start=') + m.gs_reason = space.wrap('reason') + m.gs_reason_ = space.wrap('reason=') + m.gs_args_ = space.wrap('args=') + m.gs_end = space.wrap('end') + m.gs_end_ = space.wrap('end=') + m.gs_object = space.wrap('object') + m.gs_object_ = space.wrap('object=') + m.gs__ = space.wrap(' ') + m.gs_join = space.wrap('join') + m.gbltinmethod_join = space.getattr(gs__, gs_join) + m.gi_4 = space.newint(4) + m.gi_2 = space.newint(2) + m.gi_3 = space.newint(3) + m.gs_errno = space.wrap('errno') + m.gs_errno_ = space.wrap('errno=') + m.gs_strerror = space.wrap('strerror') + m.gs_strerror_ = space.wrap('strerror=') + m.gs_filename_ = space.wrap('filename=') + m.gbltinmethod_join_1 = space.getattr(gs__, gs_join) + m.gbltinmethod_join_2 = space.getattr(gs__, gs_join) + m.gs_code = space.wrap('code') + m.gs_encoding = space.wrap('encoding') + m.gs_encoding_ = space.wrap('encoding=') + m.gbltinmethod_join_3 = space.getattr(gs__, gs_join) + m.gi_5 = space.newint(5) + m.gbltinmethod_join_4 = space.getattr(gs__, gs_join) + +# entry point: test_exceptions, gfunc_test_exceptions) +if __name__ == "__main__": + from pypy.objspace.std import StdObjSpace + space = StdObjSpace() + inittest_exceptions_1(space) + print space.unwrap(space.call( + gfunc_test_exceptions, space.newtuple([]))) + Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Thu Jan 27 18:34:25 2005 @@ -25,7 +25,7 @@ # # List of built-in modules. # It should contain the name of all the files 'module/*module.py'. -builtin_module_names = ['__builtin__', 'sys', +builtin_module_names = ['__builtin__', 'sys', 'exceptions' ] # Create the builtin_modules dictionary, mapping names to Module instances Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Thu Jan 27 18:34:25 2005 @@ -204,9 +204,42 @@ for_builtins[typedef.name] = w_type # exceptions - for_builtins.update(self.clone_exception_hierarchy()) + ##for_builtins.update(self.clone_exception_hierarchy()) + ## hacking things in + from pypy.module import exceptionsinterp as ex + hold = self.call + def call(w_type, w_args): + space = self + # too early for unpackiterable as well :-( + name = space.unwrap(space.getitem(w_args, space.wrap(0))) + bases = space.unpacktuple(space.getitem(w_args, space.wrap(1))) + dic = space.unwrap(space.getitem(w_args, space.wrap(2))) + dic = dict([(key,space.wrap(value)) for (key, value) in dic.items()]) + bases = list(bases) + if not bases: + bases = [space.w_object] + res = W_TypeObject(space, name, bases, dic) + return res + w_dic = self.newdict([]) + try: + self.call = call + ex.inittest_exceptions_1(self) + for name, w_obj in ex.__dict__.items(): + if name.startswith("gcls_"): + excname = name[5:] + setattr(self, "w_"+excname, w_obj) # into space + for_builtins[excname] = w_obj # into builtins + self.setitem(w_dic, self.wrap(excname), w_obj) # into exc + finally: + self.call = hold self.make_builtins(for_builtins) + # XXX refine things,clean up, create a builtin module... + # but for now, we do a regular one. + from pypy.interpreter.module import Module + m = Module(self, self.wrap("exceptions"), w_dic) + w_exceptions = self.wrap(m) + self.sys.setbuiltinmodule(w_exceptions, 'exceptions') def gettypeobject(self, typedef): # types_w maps each StdTypeDef instance to its Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Jan 27 18:34:25 2005 @@ -559,15 +559,22 @@ name, self.nameof(key), self.nameof(value)) baseargs = ", ".join(basenames) + self.initcode.appendnew('_dic = space.newdict([])') + for key, value in cls.__dict__.items(): + if key.startswith('__'): + if key in ['__module__', '__metaclass__']: + keyname = self.nameof(key) + valname = self.nameof(value) + self.initcode.appendnew("space.setitem(_dic, %s, %s)" % ( + keyname, valname)) + if cls.__doc__ is not None: sdoc = self.nameof("__doc__") lines = list(self.render_docstr(cls, "_doc = space.wrap(")) lines[-1] +=")" self.initcode.extend(lines) - self.initcode.appendnew('_dic = space.newdict([(%s, %s)])' % ( - self.nameof("__doc__"), "_doc") ) - else: - self.initcode.appendnew('_dic = space.newdict([])') + self.initcode.appendnew("space.setitem(_dic, %s, _doc)" % ( + self.nameof("__doc__"),)) self.initcode.append('_bases = space.newtuple([%(bases)s])\n' '_args = space.newtuple([%(name)s, _bases, _dic])\n' 'm.%(klass)s = space.call(%(meta)s, _args)' From hpk at codespeak.net Thu Jan 27 23:37:41 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 27 Jan 2005 23:37:41 +0100 (MET) Subject: [pypy-svn] r8645 - pypy/dist/lib-python-2.3.4 Message-ID: <20050127223741.9652627B8A@code1.codespeak.net> Author: hpk Date: Thu Jan 27 23:37:41 2005 New Revision: 8645 Added: pypy/dist/lib-python-2.3.4/conftest.py pypy/dist/lib-python-2.3.4/pypy_unittest.py Log: (anders, holger) preliminary support for running regrtests at app-level against PyPy with py.test. for example: py.test lib-python-2.3.4/test/test_urlparse.py passes nicely! This only works for unittest-based ones and it's really only preliminary. Don't try that at home. Added: pypy/dist/lib-python-2.3.4/conftest.py ============================================================================== --- (empty file) +++ pypy/dist/lib-python-2.3.4/conftest.py Thu Jan 27 23:37:41 2005 @@ -0,0 +1,134 @@ +import py +import sys +from pypy.interpreter.gateway import app2interp_temp +from pypy.interpreter.error import OperationError +from pypy.tool import pytestsupport +from pypy.conftest import gettestobjspace, options +from pypy.interpreter.module import Module as PyPyModule + +# +# PyPy's command line extra options (these are added +# to py.test's standard options) +# +#Option = py.test.Option +#options = ('pypy options', [ +# Option('-o', '--objspace', action="store", default=None, +# type="string", dest="objspacename", +# help="object space to run tests on."), +##]) + +# +# Interfacing/Integrating with py.test's collection process +# + +mydir = py.magic.autopath().dirpath() + + +def make_module(space, dottedname, filepath): + #print "making module", dottedname, "from", filepath + w_dottedname = space.wrap(dottedname) + mod = PyPyModule(space, w_dottedname) + w_globals = mod.w_dict + w_filename = space.wrap(str(filepath)) + space.builtin.execfile(w_filename, w_globals, w_globals) + w_mod = space.wrap(mod) + w_modules = space.getitem(space.sys.w_dict, space.wrap('modules')) + space.setitem(w_modules, w_dottedname, w_mod) + return w_mod + +class Directory(py.test.collect.Directory): + def __iter__(self): + for x in self.fspath.listdir('test_*.py'): + if x.read().find('unittest') != -1: + # we can try to run ... + if x.basename != 'test_urlparse.py': + continue + yield Module(x) + +def app_list_testmethods(mod, testcaseclass): + """ return [(instance.setUp, instance.tearDown, + [instance.testmethod1, ...]), + ...] + """ + #print "entering list_testmethods" + l = [] + for clsname, cls in mod.__dict__.items(): + if hasattr(cls, '__bases__') and \ + issubclass(cls, testcaseclass): + instance = cls() + #print "checking", instance + methods = [] + for methodname in dir(cls): + if methodname.startswith('test_'): + name = clsname + '.' + methodname + methods.append((name, getattr(instance, methodname))) + l.append((instance.setUp, instance.tearDown, methods)) + return l +list_testmethods = app2interp_temp(app_list_testmethods) + + +class Module(py.test.collect.Module): + def __init__(self, fspath): + super(Module, self).__init__(fspath) + + def _prepare(self): + if hasattr(self, 'space'): + return + self.space = space = gettestobjspace('std') + #try: + w_mod = make_module(space, 'unittest', mydir.join('pypy_unittest.py')) + self.w_TestCase = space.getattr(w_mod, space.wrap('TestCase')) + #except OperationError, e: + # raise py.test.Item.Failed( + # excinfo=pytestsupport.AppExceptionInfo(self.space, e)) + + def __iter__(self): + self._prepare() + try: + iterable = self._cache + except AttributeError: + iterable = self._cache = list(self._iterapplevel()) + for x in iterable: + yield x + + def _iterapplevel(self): + name = self.fspath.purebasename + space = self.space + w_mod = make_module(space, name, self.fspath) + w_tlist = list_testmethods(space, w_mod, self.w_TestCase) + tlist_w = space.unpackiterable(w_tlist) + for item_w in tlist_w: + w_setup, w_teardown, w_methods = space.unpacktuple(item_w) + methoditems_w = space.unpackiterable(w_methods) + for w_methoditem in methoditems_w: + w_name, w_method = space.unpacktuple(w_methoditem) + yield AppTestCaseMethod(self.fspath, space, w_name, w_method, + w_setup, w_teardown) + +class AppTestCaseMethod(py.test.Item): + def __init__(self, fspath, space, w_name, w_method, w_setup, w_teardown): + self.space = space + name = space.str_w(w_name) + extpy = py.path.extpy(fspath, name) + super(AppTestCaseMethod, self).__init__(extpy) + self.w_method = w_method + self.w_setup = w_setup + self.w_teardown = w_teardown + + def run(self, driver): + #if sys.version_info < (2,4): + # py.test.skip("CPython 2.4 required for " + # "running CPython 2.4 regrtests") + try: + self.space.call_function(self.w_setup) + try: + self.execute() + finally: + self.space.call_function(self.w_teardown) + except OperationError, e: + raise self.Failed( + excinfo=pytestsupport.AppExceptionInfo(self.space, e)) + + def execute(self): + self.space.call_function(self.w_method) + Added: pypy/dist/lib-python-2.3.4/pypy_unittest.py ============================================================================== --- (empty file) +++ pypy/dist/lib-python-2.3.4/pypy_unittest.py Thu Jan 27 23:37:41 2005 @@ -0,0 +1,29 @@ +class TestCase: + """compatibility class of unittest's TestCase. """ + def setUp(self): + pass + + def tearDown(self): + pass + + def assertEqual(self, x, y, msg=None): + if msg: + assert x == y, msg + else: + assert x == y + def assertNotEqual(self, x, y, msg=None): + if msg: + assert x != y, msg + else: + assert x != y + + def assertRaises(self, exc, call, *args, **kwargs): + raises(exc, call, *args, **kwargs) + + assertEquals = assertEqual + assertNotEquals = assertNotEqual + def assert_(self, expr, msg=None): + if msg: + assert expr, msg + else: + assert expr From hpk at codespeak.net Thu Jan 27 23:35:30 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 27 Jan 2005 23:35:30 +0100 (MET) Subject: [pypy-svn] r8644 - in pypy/dist: lib-python-2.3.4 lib-python-2.3.4/test pypy/appspace pypy/appspace/compiler pypy/appspace/test pypy/module pypy/module/test Message-ID: <20050127223530.52C8F27B8A@code1.codespeak.net> Author: hpk Date: Thu Jan 27 23:35:29 2005 New Revision: 8644 Added: pypy/dist/lib-python-2.3.4/_exceptions.py - copied unchanged from r8637, pypy/dist/pypy/appspace/_exceptions.py pypy/dist/lib-python-2.3.4/_file.py - copied unchanged from r8637, pypy/dist/pypy/appspace/_file.py pypy/dist/lib-python-2.3.4/_float_formatting.py - copied unchanged from r8637, pypy/dist/pypy/appspace/_float_formatting.py pypy/dist/lib-python-2.3.4/_formatting.py - copied unchanged from r8637, pypy/dist/pypy/appspace/_formatting.py pypy/dist/lib-python-2.3.4/_types.py - copied unchanged from r8637, pypy/dist/pypy/appspace/_types.py pypy/dist/lib-python-2.3.4/cStringIO.py - copied unchanged from r8637, pypy/dist/pypy/appspace/cStringIO.py pypy/dist/lib-python-2.3.4/cmath.py - copied unchanged from r8637, pypy/dist/pypy/appspace/cmathmodule.py pypy/dist/lib-python-2.3.4/dumbre.py - copied unchanged from r8637, pypy/dist/pypy/appspace/dumbre.py pypy/dist/lib-python-2.3.4/imp.py - copied unchanged from r8637, pypy/dist/pypy/appspace/imp.py pypy/dist/lib-python-2.3.4/md5.py - copied unchanged from r8637, pypy/dist/pypy/appspace/md5.py pypy/dist/lib-python-2.3.4/operator.py - copied unchanged from r8637, pypy/dist/pypy/appspace/operator.py pypy/dist/lib-python-2.3.4/plexre.py - copied unchanged from r8637, pypy/dist/pypy/appspace/plexre.py pypy/dist/lib-python-2.3.4/sha.py - copied unchanged from r8637, pypy/dist/pypy/appspace/sha.py pypy/dist/lib-python-2.3.4/sio.py - copied unchanged from r8637, pypy/dist/pypy/appspace/sio.py pypy/dist/lib-python-2.3.4/struct.py - copied unchanged from r8637, pypy/dist/pypy/appspace/struct.py pypy/dist/lib-python-2.3.4/test/test_sio.py - copied unchanged from r8643, pypy/dist/pypy/appspace/test/test_sio.py pypy/dist/pypy/appspace/DEPRECATED_WORK_IN_lib-python-2.3.4 Removed: pypy/dist/pypy/appspace/_exceptions.py pypy/dist/pypy/appspace/_file.py pypy/dist/pypy/appspace/_float_formatting.py pypy/dist/pypy/appspace/_formatting.py pypy/dist/pypy/appspace/_types.py pypy/dist/pypy/appspace/cStringIO.py pypy/dist/pypy/appspace/cmathmodule.py pypy/dist/pypy/appspace/compiler/ pypy/dist/pypy/appspace/dumbre.py pypy/dist/pypy/appspace/imp.py pypy/dist/pypy/appspace/md5.py pypy/dist/pypy/appspace/operator.py pypy/dist/pypy/appspace/plexre.py pypy/dist/pypy/appspace/pystone.py pypy/dist/pypy/appspace/sha.py pypy/dist/pypy/appspace/sio.py pypy/dist/pypy/appspace/sre_parse.py pypy/dist/pypy/appspace/struct.py pypy/dist/pypy/appspace/test/test_sio.py pypy/dist/pypy/appspace/traceback.py pypy/dist/pypy/appspace/types.py Modified: pypy/dist/lib-python-2.3.4/test/pystone.py pypy/dist/lib-python-2.3.4/traceback.py pypy/dist/lib-python-2.3.4/types.py pypy/dist/pypy/appspace/test/conftest.py pypy/dist/pypy/appspace/test/test_exceptions.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/test/test_zip.py Log: port all appspace hacks/modules/ports from C to the new lib-python-2.3.4 (we actually need to do a detailed check on all changes we did and that they really refer to python-2.3.4) please note that the currently failing tests were failing before this commit here and seem to relate to Christian's exception-changes (which are nice, but they do seem to break things in ways i can't directly figure out at this point in the night) Modified: pypy/dist/lib-python-2.3.4/test/pystone.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/pystone.py (original) +++ pypy/dist/lib-python-2.3.4/test/pystone.py Thu Jan 27 23:35:29 2005 @@ -57,10 +57,10 @@ TRUE = 1 FALSE = 0 -def main(): - benchtime, stones = pystones() +def main(loops=LOOPS): + benchtime, stones = pystones(loops) print "Pystone(%s) time for %d passes = %g" % \ - (__version__, LOOPS, benchtime) + (__version__, loops, benchtime) print "This machine benchmarks at %g pystones/second" % stones @@ -249,4 +249,19 @@ return FALSE if __name__ == '__main__': - main() + import sys + def error(msg): + print >>sys.stderr, msg, + print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0] + sys.exit(100) + nargs = len(sys.argv) - 1 + if nargs > 1: + error("%d arguments are too many;" % nargs) + elif nargs == 1: + try: loops = int(sys.argv[1]) + except ValueError: + error("Invalid argument %r;" % sys.argv[1]) + else: + loops = LOOPS + main(loops) + Modified: pypy/dist/lib-python-2.3.4/traceback.py ============================================================================== --- pypy/dist/lib-python-2.3.4/traceback.py (original) +++ pypy/dist/lib-python-2.3.4/traceback.py Thu Jan 27 23:35:29 2005 @@ -155,7 +155,9 @@ which exception occurred is the always last string in the list. """ list = [] - if type(etype) == types.ClassType: + # the following line is the only change against Py 2.3.3 + # Python will change here, anyway. Drop this file, then. + if isinstance(etype, (types.ClassType, type)): stype = etype.__name__ else: stype = etype Modified: pypy/dist/lib-python-2.3.4/types.py ============================================================================== --- pypy/dist/lib-python-2.3.4/types.py (original) +++ pypy/dist/lib-python-2.3.4/types.py Thu Jan 27 23:35:29 2005 @@ -1,7 +1,14 @@ -"""Define names for all type symbols known in the standard interpreter. +"""Appspace types module. + +!! This file has been copied practicaly verbatim from the CPython source. +!! See http://www.python.org/2.3.2/license.html for licensing info. + +Define names for all type symbols known in the standard interpreter. Types that are part of optional modules (e.g. array) are not listed. """ +from __future__ import generators + import sys # Iterators in Python aren't a matter of type but of protocol. A large @@ -14,26 +21,31 @@ ObjectType = object IntType = int -LongType = long +try: + LongType = long +except NameError: + pass FloatType = float -BooleanType = bool +try: + BooleanType = bool +except NameError: + pass try: ComplexType = complex except NameError: pass StringType = str - -# StringTypes is already outdated. Instead of writing "type(x) in -# types.StringTypes", you should use "isinstance(x, basestring)". But -# we keep around for compatibility with Python 2.2. try: UnicodeType = unicode StringTypes = (StringType, UnicodeType) except NameError: StringTypes = (StringType,) -BufferType = buffer +try: + BufferType = buffer +except NameError: + pass TupleType = tuple ListType = list @@ -50,13 +62,25 @@ def g(): yield 1 -GeneratorType = type(g()) +try: + GeneratorType = type(g()) +except: + # Refusing generators + pass del g +# checking whether we can make copy_reg happy +##class _C: +## def _m(self): pass +##ClassType = type(_C) +class ClassType: pass class _C: - def _m(self): pass -ClassType = type(_C) -UnboundMethodType = type(_C._m) # Same as MethodType + def _m(self):pass +## end of testing hack +try: + UnboundMethodType = type(_C._m) # Same as MethodType +except AttributeError: + pass _x = _C() InstanceType = type(_x) MethodType = type(_x._m) @@ -65,8 +89,14 @@ BuiltinMethodType = type([].append) # Same as BuiltinFunctionType ModuleType = type(sys) -FileType = file -XRangeType = xrange +try: + FileType = file +except NameError: + pass +try: + XRangeType = type(xrange(0)) +except NameError: + pass try: raise TypeError @@ -81,10 +111,13 @@ pass tb = None; del tb -SliceType = slice +SliceType = type(slice(0)) EllipsisType = type(Ellipsis) -DictProxyType = type(TypeType.__dict__) -NotImplementedType = type(NotImplemented) +#DictProxyType = type(TypeType.__dict__) +try: + NotImplementedType = type(NotImplemented) +except NameError: + pass -del sys, _f, _C, _x # Not for export +del sys, _f, _C, _x#, generators # Not for export Added: pypy/dist/pypy/appspace/DEPRECATED_WORK_IN_lib-python-2.3.4 ============================================================================== --- (empty file) +++ pypy/dist/pypy/appspace/DEPRECATED_WORK_IN_lib-python-2.3.4 Thu Jan 27 23:35:29 2005 @@ -0,0 +1,6 @@ +most appspace libraries have been moved to the version specific +svn/pypy/dist/lib-python-2.3.4, please work and modify files +there so that we can track what changes and ports of C-modules +we do to the python-2.3.4 baseline. the appspace directory +is going to vanish completly soon ... + Deleted: /pypy/dist/pypy/appspace/_exceptions.py ============================================================================== --- /pypy/dist/pypy/appspace/_exceptions.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,298 +0,0 @@ -class Exception: - """Common base class for all exceptions.""" - - # auto-generated code, please check carefully! - def __getitem__(self, idx): - return self.args[idx] - - # auto-generated code, please check carefully! - def __init__(self, *args): - self.args = args - - # auto-generated code, please check carefully! - def __str__(self): - argc = len(self.args) - if argc == 0: - return '' - elif argc == 1: - return str(self.args[0]) - else: - return str(self.args) - -class StandardError(Exception): - """Base class for all standard Python exceptions.""" - -class ValueError(StandardError): - """Inappropriate argument value (of correct type).""" - -class ImportError(StandardError): - """Import can't find module, or can't find name in module.""" - -class RuntimeError(StandardError): - """Unspecified run-time error.""" - -class UnicodeError(ValueError): - """Unicode related error.""" - -class UnicodeTranslateError(UnicodeError): - """Unicode translation error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 4: - self.object = args[0] - self.start = args[1] - self.end = args[2] - self.reason = args[3] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'start=' + str(self.start), - 'reason=' + str(self.reason), - 'args=' + str(self.args), - 'end=' + str(self.end), - 'object=' + str(self.object), - ]) - return res - -class LookupError(StandardError): - """Base class for lookup errors.""" - -class KeyError(LookupError): - """Mapping key not found.""" - - # auto-generated code, please check carefully! - def __str__(self): - argc = len(self.args) - if argc == 0: - return '' - elif argc == 1: - return repr(self.args[0]) - else: - return str(self.args) - -class Warning(Exception): - """Base class for warning categories.""" - -class SyntaxWarning(Warning): - """Base class for warnings about dubious syntax.""" - -class StopIteration(Exception): - """Signal the end from iterator.next().""" - -class PendingDeprecationWarning(Warning): - """Base class for warnings about features which will be deprecated in the future.""" - -class EnvironmentError(StandardError): - """Base class for I/O related errors.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args - self.errno = None # default, hopefully - self.strerror = None # default, hopefully - self.filename = None # default, hopefully - if 2 <= argc <= 3: - self.errno = args[0] - self.strerror = args[1] - if argc == 3: - self.filename = args[2] - self.args = (args[0], args[1]) - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'errno=' + str(self.errno), - 'args=' + str(self.args), - 'strerror=' + str(self.strerror), - 'filename=' + str(self.filename), - ]) - return res - -class OSError(EnvironmentError): - """OS system call failed.""" - -class DeprecationWarning(Warning): - """Base class for warnings about deprecated features.""" - -class UnicodeEncodeError(UnicodeError): - """Unicode encoding error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 5: - self.encoding = args[0] - self.object = args[1] - self.start = args[2] - self.end = args[3] - self.reason = args[4] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), - ]) - return res - -class ArithmeticError(StandardError): - """Base class for arithmetic errors.""" - -class FloatingPointError(ArithmeticError): - """Floating point operation failed.""" - -class ReferenceError(StandardError): - """Weak ref proxy used after referent went away.""" - -class NameError(StandardError): - """Name not found globally.""" - -class OverflowWarning(Warning): - """Base class for warnings about numeric overflow.""" - -class IOError(EnvironmentError): - """I/O operation failed.""" - -class SyntaxError(StandardError): - """Invalid syntax.""" - filename = None - lineno = None - msg = '' - offset = None - print_file_and_line = None - text = None - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args - if argc >= 1: - self.msg = args[0] - if argc == 2: - self.filename = args[1][0] - self.lineno = args[1][1] - self.offset = args[1][2] - self.text = args[1][3] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'args=' + str(self.args), - ]) - return res - -class FutureWarning(Warning): - """Base class for warnings about constructs that will change semantically in the future.""" - -class SystemExit(Exception): - """Request to exit from the interpreter.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - if argc == 0: - self.code = None # default, hopefully - self.args = args - if argc == 1: - self.code = args[0] - if argc >= 2: - self.code = args - -class EOFError(StandardError): - """Read beyond end of file.""" - -class IndentationError(SyntaxError): - """Improper indentation.""" - -class TabError(IndentationError): - """Improper mixture of spaces and tabs.""" - -class ZeroDivisionError(ArithmeticError): - """Second argument to a division or modulo operation was zero.""" - -class SystemError(StandardError): - """Internal error in the Python interpreter. - -Please report this to the Python maintainer, along with the traceback, -the Python version, and the hardware/OS platform and version.""" - -class AssertionError(StandardError): - """Assertion failed.""" - -class UnicodeDecodeError(UnicodeError): - """Unicode decoding error.""" - - # auto-generated code, please check carefully! - def __init__(self, *args): - argc = len(args) - self.args = args # modified: always assign args, no error check - if argc == 5: - self.encoding = args[0] - self.object = args[1] - self.start = args[2] - self.end = args[3] - self.reason = args[4] - - # auto-generated code, please check carefully! - def __str__(self): - # this is a bad hack, please supply an implementation - res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), - ]) - return res - -class TypeError(StandardError): - """Inappropriate argument type.""" - -class IndexError(LookupError): - """Sequence index out of range.""" - -class RuntimeWarning(Warning): - """Base class for warnings about dubious runtime behavior.""" - -class KeyboardInterrupt(StandardError): - """Program interrupted by user.""" - -class UserWarning(Warning): - """Base class for warnings generated by user code.""" - -class TaskletExit(SystemExit): - """Request to exit from a tasklet.""" - -class MemoryError(StandardError): - """Out of memory.""" - -class UnboundLocalError(NameError): - """Local name referenced but not bound to a value.""" - -class NotImplementedError(RuntimeError): - """Method or function hasn't been implemented yet.""" - -class AttributeError(StandardError): - """Attribute not found.""" - -class OverflowError(ArithmeticError): - """Result too large to be represented.""" - -class WindowsError(OSError): - """MS-Windows OS system call failed.""" - Deleted: /pypy/dist/pypy/appspace/_file.py ============================================================================== --- /pypy/dist/pypy/appspace/_file.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,118 +0,0 @@ -import sio - -class file_(object): - """An implementation of file objects in Python. it relies on Guido's - sio.py implementation. - """ - - - def __init__(self, name, mode='r', bufsize=None): - self.reading = False - self.writing = False - - if not mode: - raise IOError('invalid mode : ') - if mode[0] not in ['r', 'w', 'a', 'U']: - raise IOError('invalid mode : %s' % mode) - else: - if mode[0] in ['r', 'U']: - self.reading = True - else: - self.writing = True - try: - if mode[1] == 'b': - plus = mode[2] - else: - plus = mode[1] - if plus == '+': - self.reading = self.writing = True - except IndexError: - pass - - self._mode = mode - self._name = name - self._closed = False - self.softspace = 0 # Required according to file object docs - self._encoding = None # Fix when we find out how encoding should be - self.fd = sio.DiskFile(name, mode) - if mode in ['U', 'rU']: - # Wants universal newlines - self.fd = sio.TextInputFilter(self.fd) - if bufsize < 0: - bufsize = None - if not self.writing and (bufsize is None or bufsize > 0): - "Read only buffered stream." - self.fd = sio.BufferingInputStream(self.fd, bufsize) - if not self.reading: - if bufsize is None or bufsize > 1: - "Write only buffered stream." - self.fd = sio.BufferingOutputStream(self.fd, bufsize) - elif bufsize == 1: - self.fd = sio.LineBufferingOutputStream(self.fd) - if self.reading and self.writing: - if bufsize > 2: - "Read and write buffered stream." - self.fd = sio.BufferingInputOutputStream(self.fd, bufsize) - - def __iter__(self): - """ - Return an iterator for the file. - """ - if self._closed: - raise ValueError('I/O operation on closed file') - return self - xreadlines = __iter__ - - def next(self): - if self._closed: - raise ValueError('I/O operation on closed file') - line = self.fd.readline() - if line == '': - raise StopIteration - return line - - def close(self): - """ - Close the file - """ - self._closed = True - try: - self.fd.close() - except AttributeError: - pass - - def __getattr__(self, attr): - """ - Handle the readonly attributes and then delegate the other - methods to the underlying file object, setting the 'closed' - attribute if you close the file. - """ - if attr in ['fd', 'softspace', 'reading', 'writing']: - return self.__dict__[attr] - elif attr in ['mode', 'name', 'closed', 'encoding']: - return self.__dict__['_' + attr] - - return getattr(self.fd, attr) - - def __setattr__(self, attr, val): - "Make some attributes readonly." - if attr in ['mode', 'name', 'closed', 'encoding']: - raise TypeError, "readonly attribute:'%s'" % attr - self.__dict__[attr] = val - - def seek(self, *args, **kw): - if self._closed: - raise ValueError('I/O operation on closed file') - self.fd.seek(*args, **kw) - - def write(self, *args, **kw): - if self._closed: - raise ValueError('I/O operation on closed file') - self.fd.write(*args, **kw) - - def writelines(self, seq = ()): - if self._closed: - raise ValueError('I/O operation on closed file') - for line in seq: - self.write(line) - Deleted: /pypy/dist/pypy/appspace/_float_formatting.py ============================================================================== --- /pypy/dist/pypy/appspace/_float_formatting.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,110 +0,0 @@ -import math - -# from the excessive effort department, routines for printing floating -# point numbers from - -# "Printing Floating-Point Numbers Quickly and Accurately" by Burger & -# Dybvig, Proceedings of the SIGPLAN '96 Conference on Programming -# Language Design and Implementation. - -# The paper contains scheme code which has been specialized for IEEE -# doubles and converted into Python by Michael Hudson. - -# XXX unfortunately, we need the fixed-format output routines, the source -# for which is not included in the paper... for now, just put up with -# occasionally incorrectly rounded final digits. I'll get to it. - -# XXX should run this at interpreter level, really.... - -def decode_float(f): - """decode_float(float) -> int, int - - Return (m, e), the mantissa and exponent respectively of - f (assuming f is an IEEE double), i.e. f == m * 2**e and - 2**52 <= m < 2**53.""" - m, e = math.frexp(f) - m = long(m*2.0**53) - e -= 53 - return m, e - -def decompose(f): - """decompose(float) -> int, int, int, int - - Return r, s, m_plus, m_minus for f, in the terms of - Burger and Dybvig's paper (see Table 1). - - To spell this out: f = r/s, (r+m+)/s is halfway to the - next largest floating point number, (r-m-) halfway to - the next smallest.""" - m, e = decode_float(f) - if e >= 0: - if not m != 2**52: - be = 2**e - return m*be*2, 2, be, be - else: - be = 2**e - be1 = 2*be - return m*be1*2, 4, be1, be - else: - if e == -1075 or m != 2**52: - return m*2, 2**(-e+1), 1, 1 - else: - return m*4, 2**(-e+2), 2, 1 - - -def flonum2digits(f): - """flonum2digits(float) -> [int], int - - Given a float f return [d1, ..., dn], k such that - - 0.[d1][d2]...[dn] * 10**k - - is the shortest decimal representation that will - reproduce f when read in by a correctly rounding input - routine (under any strategy for breaking ties).""" - - assert f >= 0 - if f == 0.0: - return ['0'], 1 - - # See decompose's docstring for what these mean. - r, s, m_plus, m_minus = decompose(f) - - # k is the index, relative to the radix point of the - # most-significant non-zero digit of the infinite - # decimal expansion of f. This calculation has the - # potential to underestimate by one (handled below). - k = long(math.ceil(math.log10(f) - 1e-10)) - - if k >= 0: - s *= 10 ** k - else: - scale = 10 ** -k - r *= scale - m_plus *= scale - m_minus *= scale - - # Check that we got k right above. - if r + m_plus > s: - s *= 10 - k += 1 - - # Generate the digits. - rr = [] - while 1: - d, r = divmod(r*10, s) - m_plus *= 10 - m_minus *= 10 - tc1 = r < m_minus - tc2 = (r + m_plus) > s - if tc2: - rr.append(d+1) - else: - rr.append(d) - if tc1 or tc2: - break - - assert max(rr) < 10 - assert min(rr) >= 0 - - return map(str, rr), k Deleted: /pypy/dist/pypy/appspace/_formatting.py ============================================================================== --- /pypy/dist/pypy/appspace/_formatting.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,409 +0,0 @@ -# Application level implementation of string formatting. - -# There's some insane stuff in here. Blame CPython. Please. - -# Known problems: -# (1) rounding isn't always right (see comments in _float_formatting). -# (2) something goes wrong in the f_alt case of %g handling. -# (3) it's really, really slow. - -class _Flags(object): - def __repr__(self): - return "<%s>"%(', '.join([f for f in self.__dict__ - if f[0] == 'f' and getattr(self, f)]),) - f_ljust = 0 - f_sign = 0 - f_blank = 0 - f_alt = 0 - f_zero = 0 - - -def value_next(valueiter): - try: - return valueiter.next() - except StopIteration: - raise TypeError('not enough arguments for format string') - - -def peel_num(c, fmtiter, valueiter): - if c == '*': - v = value_next(valueiter) - if not isinstance(v, int): - raise TypeError, "* wants int" - return fmtiter.next(), v - n = '' - while c in '0123456789': - n += c - c = fmtiter.next() - if n: - return c, int(n) - else: - return c, 0 - - -def peel_flags(c, fmtiter): - flags = _Flags() - while 1: - if c == '-': - flags.f_ljust = True - elif c == '+': - flags.f_sign = True - elif c == ' ': - flags.f_blank = True - elif c == '#': - flags.f_alt = True - elif c == '0': - flags.f_zero = True - else: - break - c = fmtiter.next() - return c, flags - - -def parse_fmt(fmtiter, valueiter, valuedict): - """return (char, flags, width, prec, value) - partially consumes fmtiter & valueiter""" - c = fmtiter.next() - gotvalue = False - if c == '(': - n = '' - pcount = 1 - while 1: - c = fmtiter.next() - if c == ')': - pcount -= 1 - if pcount == 0: - break - elif c == '(': - pcount += 1 - n += c - value = valuedict[n] - gotvalue = True - c = fmtiter.next() - c, flags = peel_flags(c, fmtiter) - c, width = peel_num(c, fmtiter, valueiter) - if c == '.': - c, prec = peel_num(fmtiter.next(), fmtiter, valueiter) - else: - prec = None - if c in 'hlL': - c = fmtiter.next() - if width and width < 0: - # this can happen with *-args - flags.f_ljust = True - width = -width - if not gotvalue: - if c == '%': - # did YOU realize that "%4%"%() == ' %'?? - value = '%' - c = 's' - else: - value = value_next(valueiter) - return (c, flags, width, prec, value) - - -class Formatter(object): - def __init__(self, char, flags, width, prec, value): - self.char = char - self.flags = flags - self.width = width - self.prec = prec - self.value = value - - def numeric_preprocess(self, v): - # negative zeroes? - # * mwh giggles, falls over - # still, if we can recognize them, here's the place to do it. - import math - if v < 0 or v == 0 and math.atan2(0, v) != 0: - sign = '-' - v = -v - else: - if self.flags.f_sign: - sign = '+' - elif self.flags.f_blank: - sign = ' ' - else: - sign = '' - return v, sign - - def numeric_postprocess(self, r, sign,prefix=""): - assert self.char in 'iduoxXeEfFgG' - padchar = ' ' - if self.flags.f_zero: - padchar = '0' - if self.width is not None: - p = self.width - len(r) - len(sign) -len(prefix) - if self.flags.f_ljust: - r = sign + prefix + r + ' '*p - else: - if self.flags.f_zero: - r = sign+prefix+padchar*p + r - else: - r = padchar*p + sign + prefix + r - else: - r = sign + prefix + r - return r - - def format(self): - raise NotImplementedError - - def std_wp(self, r): - assert self.char not in 'iduoxXeEfFgG' - if self.prec is not None: - r = r[:self.prec] - if self.width is not None: - p = self.width - len(r) - if self.flags.f_ljust: - r = r + ' '*p - else: - r = ' '*p + r - return r - - -def funcFormatter(*funcs): - class _F(Formatter): - def format(self): - r = self.value - for f in funcs: - r = f(r) - return self.std_wp(r) - return _F - - -def maybe_int(value): - try: - inter = value.__int__ - except AttributeError: - raise TypeError, "int argument required" - return inter() - - -def maybe_float(value): - try: - floater = value.__float__ - except AttributeError: - raise TypeError, "float argument required" - return floater() - - -from _float_formatting import flonum2digits - -class FloatFormatter(Formatter): - def eDigits(self, ds): - ds = ds[:self.prec + 1] + ['0'] * (self.prec + 1 - len(ds)) - if self.prec > 0 or self.flags.f_alt: - ds[1:1] = ['.'] - return ''.join(ds) - - def fDigits(self, ds, k): - p = max(self.prec, 0) - if 0 < k < len(ds): - if len(ds) - k < p: - ds.extend(['0'] * (p - (len(ds) - k))) - else: - ds = ds[:p + k] - ds[k:k] = ['.'] - elif k <= 0: - ds[0:0] = ['0']*(-k) - ds = ds[:p] - ds.extend(['0'] * (p - len(ds))) - ds[0:0]= ['0', '.'] - elif k >= len(ds): - ds.extend((k-len(ds))*['0'] + ['.'] + ['0']*p) - return ''.join(ds) - - def format(self): - v = maybe_float(self.value) - v, sign = self.numeric_preprocess(v) - if self.prec is None: - self.prec = 6 - r = self._format(v) - return self.numeric_postprocess(r, sign) - - -class FloatFFormatter(FloatFormatter): - def _format(self, v): - if v/1e25 > 1e25: - return FloatGFormatter('g', self.flags, self.width, - self.prec, self.value).format() - ds, k = flonum2digits(v) - digits = self.fDigits(ds, k) - if not self.flags.f_alt: - digits = digits.rstrip('.') - return digits - - -class FloatEFormatter(FloatFormatter): - def _format(self, v): - ds, k = flonum2digits(v) - digits = self.eDigits(ds) - return "%s%c%+03d"%(digits, self.char, k-1) - - -class FloatGFormatter(FloatFormatter): - # The description of %g in the Python documentation lies - # in a variety of minor ways. - # Gah, this still isn't quite right in the f_alt case. - # (One has to wonder who might care). - def _format(self, v): - ds, k = flonum2digits(v) - ds = ds[:self.prec] # XXX rounding! - if -4 < k <= self.prec: - digits = self.fDigits(ds, k) - if not self.flags.f_alt: - digits = digits.rstrip('0').rstrip('.') - r = digits - else: - digits = self.eDigits(ds) - if not self.flags.f_alt: - digits = digits.rstrip('0').rstrip('.') - r = "%se%+03d"%(digits, k-1) - return r - - -class HexFormatter(Formatter): - # NB: this has 2.4 semantics wrt. negative values - def format(self): - v, sign = self.numeric_preprocess(maybe_int(self.value)) - r = hex(v)[2:] - if r[-1]=="L": - # workaround weird behavior of CPython's hex - r = r[:-1].lower() - if self.prec is not None and len(r) < self.prec: - r = '0'*(self.prec - len(r)) + r - if self.flags.f_alt: - prefix = '0x' - else: - prefix = '' - if self.char == 'X': - r = r.upper() - prefix = prefix.upper() - return self.numeric_postprocess(r, sign, prefix) - - -class OctFormatter(Formatter): - # NB: this has 2.4 semantics wrt. negative values - def format(self): - v, sign = self.numeric_preprocess(maybe_int(self.value)) - r = oct(v) - if r[-1] == "L": - r = r[:-1] - if v and not self.flags.f_alt: - r = r[1:] - if self.prec is not None and len(r) < self.prec: - r = '0'*(self.prec - len(r)) + r - return self.numeric_postprocess(r, sign) - - -class IntFormatter(Formatter): - # NB: this has 2.4 semantics wrt. negative values (for %u) - def format(self): - v, sign = self.numeric_preprocess(maybe_int(self.value)) - r = str(v) - if self.prec is not None and len(r) < self.prec: - r = '0'*(self.prec - len(r)) + r - return self.numeric_postprocess(r, sign) - - -class CharFormatter(Formatter): - def format(self): - if isinstance(self.value, str): - v = self.value - if len(v) != 1: - raise TypeError, "%c requires int or char" - else: - i = maybe_int(self.value) - if not 0 <= i <= 255: - raise OverflowError("OverflowError: unsigned byte " - "integer is greater than maximum") - v = chr(i) - self.prec = None - return self.std_wp(v) - - -format_registry = { - 'd':IntFormatter, - 'i':IntFormatter, - 'o':OctFormatter, - 'u':IntFormatter, - 'x':HexFormatter, - 'X':HexFormatter, - 'e':FloatEFormatter, - 'E':FloatEFormatter, - 'f':FloatFFormatter, - 'F':FloatFFormatter, - 'g':FloatGFormatter, - 'G':FloatGFormatter, - 'c':CharFormatter, - 's':funcFormatter(str), - 'r':funcFormatter(repr), - # this *can* get accessed, by e.g. '%()4%'%{'':1}. - # The usual %% case has to be handled specially as it - # doesn't consume a value. - '%':funcFormatter(lambda x:'%'), - } - - -class FmtIter(object): - def __init__(self, fmt): - self.fmt = fmt - self.i = 0 - - def __iter__(self): - return self - - def next(self): - try: - c = self.fmt[self.i] - except IndexError: - raise StopIteration - self.i += 1 - return c - - def skip_to_fmt(self): - i = self.i - j = self.fmt.find('%', i) - if j < 0: - self.i = len(self.fmt) - return self.fmt[i:] - else: - self.i = j - return self.fmt[i:j] - - -def format(fmt, values, valuedict=None): - fmtiter = FmtIter(fmt) - valueiter = iter(values) - r = [] - try: - for c in fmtiter: - if c == '%': - t = parse_fmt(fmtiter, valueiter, valuedict) - try: - f = format_registry[t[0]] - except KeyError: - raise ValueError("unsupported format character " - "'%s' (0x%x) at index %d" - %(t[0], ord(t[0]), fmtiter.i-1)) - # Trying to translate this using the flow space. - # Currently, star args give a problem there, - # so let's be explicit about the args: - # r.append(f(*t).format()) - char, flags, width, prec, value = t - r.append(f(char, flags, width, prec, value).format()) - else: - # efficiency hack: - r.append(c + fmtiter.skip_to_fmt()) - except StopIteration: - raise ValueError, "incomplete format" - try: - valueiter.next() - except StopIteration: - pass - else: - if valuedict is None: - raise TypeError('not all arguments converted ' - 'during string formatting') - return ''.join(r) - Deleted: /pypy/dist/pypy/appspace/_types.py ============================================================================== --- /pypy/dist/pypy/appspace/_types.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,551 +0,0 @@ -""" -Definition of the standard Python types. -""" - -# XXX we can't do this import yet -from sys import pypy -import __builtin__ -import _types - -__all__ = ['BooleanType', 'BufferType', 'BuiltinFunctionType', - 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', - 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', - 'FileType', 'FloatType', 'FrameType', 'FunctionType', - 'GeneratorType', 'InstanceType', 'IntType', 'LambdaType', - 'ListType', 'LongType', 'MethodType', 'ModuleType', 'NoneType', - 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', - 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', - 'UnicodeType', 'XRangeType'] - - -def _register(factory, cls, in_builtin=True, synonym=True): - """ - Register factory as type cls. - - If in_builtin is a true value (which is the default), also - register the type as a built-in. If the value of in_builtin - is a string, use this name as the type name in the __builtin__ - module. - - If synonym is true (which is the default), also register the - type in this very module under its synonym. If synonym is a - string, use this string, else uppercase the class name and - append the string "Type". - """ - pypy.registertype(factory, cls) - if in_builtin: - if isinstance(in_builtin, str): - typename = in_builtin - else: - typename = cls.__name__ - setattr(__builtin__, typename, cls) - if synonym: - if isinstance(synonym, str): - typename = synonym - else: - typename = cls.__name__.title() + 'Type' - setattr(_types, typename, cls) - - -class object: - - def __new__(cls): - if cls is object: - return pypy.ObjectFactory() - else: - return pypy.UserObjectFactory(cls, pypy.ObjectFactory) - - def __repr__(self): - return '<%s object at 0x%x>' % (type(self).__name__, id(self)) - -_register(pypy.ObjectFactory, object) - - -class bool(int): - - def __new__(cls, *args): - if cls is bool: - return pypy.BoolObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.BoolObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.BoolObjectFactory, bool, synonym='BooleanType') - - -class buffer(object): - - def __new__(cls, *args): - if cls is buffer: - return pypy.BufferObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.BufferObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.BufferObjectFactory, buffer) - - -class builtin_function_or_method(object): - - def __new__(cls, *args): - if cls is builtin_function_or_method: - return pypy.Builtin_Function_Or_MethodObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, - pypy.Builtin_Function_Or_MethodObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.Builtin_Function_Or_MethodObjectFactory, - builtin_function_or_method, in_builtin=False, - synonym='BuiltinFunctionType') - -setattr(_types, 'BuiltinMethodType', builtin_function_or_method) - - -class classobj(object): - - def __new__(cls, *args): - if cls is classobj: - return pypy.ClassobjObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.ClassobjObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.ClassobjObjectFactory, classobj, in_builtin=False, - synonym='ClassType') - - -class code(object): - - def __new__(cls, *args): - if cls is code: - return pypy.CodeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.CodeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.CodeObjectFactory, code, in_builtin=False) - - -class complex(object): - - def __new__(cls, *args): - if cls is complex: - return pypy.ComplexObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.ComplexObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.ComplexObjectFactory, complex) - - -class dictproxy(object): - - def __new__(cls, *args): - if cls is dictproxy: - return pypy.DictproxyObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.DictproxyObjectFactory, - args) - - def __repr__(self): - return str(self) - -_register(pypy.DictproxyObjectFactory, dictproxy, in_builtin=False, - synonym='DictProxyType') - - -class dict(object): - - def __new__(cls, *args): - if cls is dict: - return pypy.DictObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.DictObjectFactory, args) - - def __repr__(self): - return str(self) - -# add to dict all and only those methods that used to be defined in -# objspace/std/dicttype.py, but get the implementations from the -# excellent code in UserDict.DictMixin instead (no inheritance for -# two reasons: we could not control what methods we get, and we do -# not want DictMixin among user-visible __bases__). -import UserDict -for attribute in ('update popitem get setdefault pop' - 'iteritems iterkeys itervalues').split(): - setattr(dict, attribute, UserDict.DictMixin.__dict__[attribute]) - -_register(pypy.DictObjectFactory, dict) - -setattr(_types, 'DictionaryType', dict) - - -class ellipsis(object): - - def __new__(cls, *args): - if cls is ellipsis: - return pypy.EllipsisObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.EllipsisObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.EllipsisObjectFactory, ellipsis, in_builtin=False) - - -class file(object): - - def __new__(cls, *args): - if cls is file: - return pypy.FileObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.FileObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.FileObjectFactory, file, in_builtin='open') - - -# XXX: for float as for all other classes, __new__ defers to a suitable -# factory from pypy; in floattype.py, the implementation of __new__ was -# quite differently, but we think that was not needed -- remove this -# comment once this is definitively established. -# NB: other rich implementations of __new__ from old *type.py modules -# not reproduced here: int, slice, str, tuple, type -class float(object): - - def __new__(cls, *args): - if cls is float: - return pypy.FloatObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.FloatObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.FloatObjectFactory, float) - - -class frame(object): - - def __new__(cls, *args): - if cls is frame: - return pypy.FrameObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.FrameObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.FrameObjectFactory, frame, in_builtin=False) - - -class function(object): - - def __new__(cls, *args): - if cls is function: - return pypy.FunctionObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.FunctionObjectFactory, args) - - def __repr__(self): - return str(self) - - # XXX find out details for builtin properties - func_code = pypy.builtin_property('fix') - func_globals = pypy.builtin_property('me') - -_register(pypy.FunctionObjectFactory, function, in_builtin=False) - - -class generator(object): - - def __new__(cls, *args): - if cls is generator: - return pypy.GeneratorObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.GeneratorObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.GeneratorObjectFactory, generator, in_builtin=False) - - -class instance(object): - - def __new__(cls, *args): - if cls is instance: - return pypy.InstanceObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.InstanceObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.InstanceObjectFactory, instance, in_builtin=False) - - -class int(object): - - def __new__(cls, *args): - if cls is int: - return pypy.IntObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.IntObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.IntObjectFactory, int) - -setattr(_types, 'LambdaType', function) - - -class list(object): - - def __new__(cls, *args): - if cls is list: - return pypy.ListObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.ListObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.ListObjectFactory, list) - - -class long(object): - - def __new__(cls, *args): - if cls is long: - return pypy.LongObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.LongObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.LongObjectFactory, long) - - -class instancemethod(object): - - def __new__(cls, *args): - if cls is instancemethod: - return pypy.InstancemethodObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, - pypy.InstancemethodObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.InstancemethodObjectFactory, instancemethod, in_builtin=False, - synonym='MethodType') - - -class module(object): - - def __new__(cls, *args): - if cls is module: - return pypy.ModuleObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.ModuleObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.ModuleObjectFactory, module, in_builtin=False) - - -class NoneType(object): - - def __new__(cls, *args): - if cls is NoneType: - return pypy.NonetypeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.NonetypeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.NonetypeObjectFactory, NoneType, in_builtin=False, - synonym='NoneType') - - -class NotImplementedType(object): - - def __new__(cls, *args): - if cls is NotImplementedType: - return pypy.NotimplementedtypeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, - pypy.NotimplementedtypeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.NotimplementedtypeObjectFactory, NotImplementedType, - in_builtin=False, synonym='NotImplementedType') - - -class slice(object): - - def __new__(cls, *args): - if cls is slice: - return pypy.SliceObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.SliceObjectFactory, args) - - def __repr__(self): - return str(self) - - def indices(self, length): - step = self.step - if step is None: - step = 1 - elif step == 0: - raise ValueError, "slice step cannot be zero" - if step < 0: - defstart = length - 1 - defstop = -1 - else: - defstart = 0 - defstop = length - - start = self.start - if start is None: - start = defstart - else: - if start < 0: - start += length - if start < 0: - if step < 0: - start = -1 - else: - start = 0 - elif start >= length: - if step < 0: - start = length - 1 - else: - start = length - - stop = self.stop - if stop is None: - stop = defstop - else: - if stop < 0: - stop += length - if stop < 0: - stop = -1 - elif stop > length: - stop = length - - return start, stop, step - -_register(pypy.SliceObjectFactory, slice) - - -class str(object): - - def __new__(cls, *args): - if cls is str: - return pypy.StrObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.StrObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.StrObjectFactory, str, synonym='StringType') - - -class traceback(object): - - def __new__(cls, *args): - if cls is traceback: - return pypy.TracebackObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.TracebackObjectFactory, - args) - - def __repr__(self): - return str(self) - -_register(pypy.TracebackObjectFactory, traceback, in_builtin=False) - - -class tuple(object): - - def __new__(cls, *args): - if cls is tuple: - return pypy.TupleObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.TupleObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.TupleObjectFactory, tuple) - - -class type(object): - - def __new__(cls, *args): - if cls is type: - return pypy.TypeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.TypeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.TypeObjectFactory, type) - -setattr(_types, 'UnboundMethodType', instancemethod) - - -class unicode(object): - - def __new__(cls, *args): - if cls is unicode: - return pypy.UnicodeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.UnicodeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.UnicodeObjectFactory, unicode) - - -class xrange(object): - - def __new__(cls, *args): - if cls is xrange: - return pypy.XrangeObjectFactory(args) - else: - return pypy.UserObjectFactory(cls, pypy.XrangeObjectFactory, args) - - def __repr__(self): - return str(self) - -_register(pypy.XrangeObjectFactory, xrange, synonym='XRangeType') - Deleted: /pypy/dist/pypy/appspace/cStringIO.py ============================================================================== --- /pypy/dist/pypy/appspace/cStringIO.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,5 +0,0 @@ -# -# One-liner implementation of cStringIO -# - -from StringIO import * Deleted: /pypy/dist/pypy/appspace/cmathmodule.py ============================================================================== --- /pypy/dist/pypy/appspace/cmathmodule.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,215 +0,0 @@ -"""This module is always available. It provides access to mathematical -functions for complex numbers.""" - -# Complex math module - -# much code borrowed from mathmodule.c - -import math - -M_PI = 3.141592653589793239 - - - -# constants -_one = complex(1., 0.) -_half = complex(0.5, 0.) -_i = complex(0., 1.) -_halfi = complex(0., 0.5) - - -# internal function not available from Python -def _prodi(x): - real = -x.imag - imag = x.real - return complex(real, imag) - - -def acos(x): - """acos(x) - - Return the arc cosine of x.""" - - return -(_prodi(log((x+(_i*sqrt((_one-(x*x)))))))) - - -def acosh(x): - """acosh(x) - - Return the hyperbolic arccosine of x.""" - - z = complex() - z = sqrt(_half) - z = log(z*(sqrt(x+_one)+sqrt(x-_one))) - return z+z - - -def asin(x): - """asin(x) - - Return the arc sine of x.""" - - # -i * log[(sqrt(1-x**2) + i*x] - squared = x*x - sqrt_1_minus_x_sq = sqrt(_one-squared) - return -(_prodi(log((sqrt_1_minus_x_sq+_prodi(x))))) - - -def asinh(x): - """asinh(x) - - Return the hyperbolic arc sine of x.""" - - z = complex() - z = sqrt(_half) - z = log((z * (sqrt(x+_i)+sqrt((x-_i))) )) - return z+z - - -def atan(x): - """atan(x) - - Return the arc tangent of x.""" - - return _halfi*log(((_i+x)/(_i-x))) - - -def atanh(x): - """atanh(x) - - Return the hyperbolic arc tangent of x.""" - - return _half*log((_one+x)/(_one-x)) - - -def cos(x): - """cos(x) - - Return the cosine of x.""" - - real = math.cos(x.real) * math.cosh(x.imag) - imag = -math.sin(x.real) * math.sinh(x.imag) - return complex(real, imag) - - -def cosh(x): - """cosh(x) - - Return the hyperbolic cosine of x.""" - - real = math.cos(x.imag) * math.cosh(x.real) - imag = math.sin(x.imag) * math.sinh(x.real) - return complex(real, imag) - - -def exp(x): - """exp(x) - - Return the exponential value e**x.""" - - l = math.exp(x.real) - real = l * math.cos(x.imag) - imag = l * math.sin(x.imag) - return complex(real, imag) - - -def log(x): - """log(x) - - Return the natural logarithm of x.""" - - l = math.hypot(x.real,x.imag) - imag = math.atan2(x.imag, x.real) - real = math.log(l) - return complex(real, imag) - - -def log10(x): - """log10(x) - - Return the base-10 logarithm of x.""" - - l = math.hypot(x.real, x.imag) - imag = math.atan2(x.imag, x.real)/math.log(10.) - real = math.log10(l) - return complex(real, imag) - - -def sin(x): - """sin(x) - - Return the sine of x.""" - - real = math.sin(x.real) * math.cosh(x.imag) - imag = math.cos(x.real) * math.sinh(x.imag) - return complex(real, imag) - - -def sinh(x): - """sinh(x) - - Return the hyperbolic sine of x.""" - - real = math.cos(x.imag) * math.sinh(x.real) - imag = math.sin(x.imag) * math.cosh(x.real) - return complex(real, imag) - - -def sqrt(x): - """sqrt(x) - - Return the square root of x.""" - - if x.real == 0. and x.imag == 0.: - real, imag = 0, 0 - else: - s = math.sqrt(0.5*(math.fabs(x.real) + math.hypot(x.real,x.imag))) - d = 0.5*x.imag/s - if x.real > 0.: - real = s - imag = d - elif x.imag >= 0.: - real = d - imag = s - else: - real = -d - imag = -s - return complex(real, imag) - - -def tan(x): - """tan(x) - - Return the tangent of x.""" - - sr = math.sin(x.real) - cr = math.cos(x.real) - shi = math.sinh(x.imag) - chi = math.cosh(x.imag) - rs = sr * chi - is_ = cr * shi - rc = cr * chi - ic = -sr * shi - d = rc*rc + ic * ic - real = (rs*rc + is_*ic) / d - imag = (is_*rc - rs*ic) / d - return complex(real, imag) - - -def tanh(x): - """tanh(x) - - Return the hyperbolic tangent of x.""" - - si = math.sin(x.imag) - ci = math.cos(x.imag) - shr = math.sinh(x.real) - chr = math.cosh(x.real) - rs = ci * shr - is_ = si * chr - rc = ci * chr - ic = si * shr - d = rc*rc + ic*ic - real = (rs*rc + is_*ic) / d - imag = (is_*rc - rs*ic) / d - return complex(real, imag) Deleted: /pypy/dist/pypy/appspace/dumbre.py ============================================================================== --- /pypy/dist/pypy/appspace/dumbre.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,5 +0,0 @@ -class Pattern: - def __init__(self, pattern, flags): - print 'regex', pattern - print 'killed' - raise SystemExit Deleted: /pypy/dist/pypy/appspace/imp.py ============================================================================== --- /pypy/dist/pypy/appspace/imp.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,72 +0,0 @@ -""" -This module provides the components needed to build your own -__import__ function. Undocumented functions are obsolete. -""" - -# XXX partial implementation - -# XXX to be reviewed - -import sys, os - -PY_SOURCE = 1 -PKG_DIRECTORY = 5 -C_BUILTIN = 6 - -def get_magic(): - return '\x3b\xf2\x0d\x0a' - -def get_suffixes(): - return [('.py', 'U', PY_SOURCE)] - -new_module = type(sys) - - -def find_module(name, path=None): - if path is None: - if name in sys.builtin_module_names: - return (None, name, ('', '', C_BUILTIN)) - path = sys.path - for base in path: - filename = os.path.join(base, name) - if os.path.isdir(filename): - return (None, filename, ('', '', PKG_DIRECTORY)) - filename += '.py' - if os.path.exists(filename): - return (file(filename, 'U'), filename, ('.py', 'U', PY_SOURCE)) - raise ImportError, 'No module named %s' % (name,) - - -def load_module(name, file, filename, description): - suffix, mode, type = description - module = sys.modules.get(name) - - if type == PY_SOURCE: - source = file.read() - co = compile(source, filename, 'exec') - if module is None: - sys.modules[name] = module = new_module(name) - module.__dict__.clear() - module.__name__ = name - module.__doc__ = None - module.__file__ = filename - exec co in module.__dict__ - return module - - if type == PKG_DIRECTORY: - initfilename = os.path.join(filename, '__init__.py') - if module is None: - sys.modules[name] = module = new_module(name) - module.__dict__.clear() - module.__name__ = name - module.__doc__ = None - module.__file__ = initfilename - module.__path__ = [filename] - execfile(initfilename, module.__dict__) - return module - - if type == C_BUILTIN: - module = __import__(name, {}, {}, None) - return module - - raise ValueError, 'invalid description argument: %r' % (description,) Deleted: /pypy/dist/pypy/appspace/md5.py ============================================================================== --- /pypy/dist/pypy/appspace/md5.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,434 +0,0 @@ -#!/usr/bin/env python -# -*- coding: iso-8859-1 - -"""A sample implementation of MD5 in pure Python. - -This is an implementation of the MD5 hash function, as specified by -RFC 1321, in pure Python. It was implemented using Bruce Schneier's -excellent book "Applied Cryptography", 2nd ed., 1996. - -Surely this is not meant to compete with the existing implementation -of the Python standard library (written in C). Rather, it should be -seen as a Python complement that is more readable than C and can be -used more conveniently for learning and experimenting purposes in -the field of cryptography. - -This module tries very hard to follow the API of the existing Python -standard library's "md5" module, but although it seems to work fine, -it has not been extensively tested! (But note that there is a test -module, test_md5py.py, that compares this Python implementation with -the C one of the Python standard library. - -BEWARE: this comes with no guarantee whatsoever about fitness and/or -other properties! Specifically, do not use this in any production -code! License is Python License! - -Special thanks to Aurelian Coman who fixed some nasty bugs! - -Dinu C. Gherman -""" - - -__date__ = '2004-11-17' -__version__ = 0.91 # Modernised by J. Hall?n and L. Creighton for Pypy - -__metaclass__ = type # or genrpy won't work - -import struct, copy - - -# ====================================================================== -# Bit-Manipulation helpers -# -# _long2bytes() was contributed by Barry Warsaw -# and is reused here with tiny modifications. -# ====================================================================== - -def _long2bytes(n, blocksize=0): - """Convert a long integer to a byte string. - - If optional blocksize is given and greater than zero, pad the front - of the byte string with binary zeros so that the length is a multiple - of blocksize. - """ - - # After much testing, this algorithm was deemed to be the fastest. - s = '' - pack = struct.pack - while n > 0: - ### CHANGED FROM '>I' TO '> 32 - - # Strip off leading zeros. - for i in range(len(s)): - if s[i] <> '\000': - break - else: - # Only happens when n == 0. - s = '\000' - i = 0 - - s = s[i:] - - # Add back some pad bytes. This could be done more efficiently - # w.r.t. the de-padding being done above, but sigh... - if blocksize > 0 and len(s) % blocksize: - s = (blocksize - len(s) % blocksize) * '\000' + s - - return s - - -def _bytelist2long(list): - "Transform a list of characters into a list of longs." - - imax = len(list)/4 - hl = [0L] * imax - - j = 0 - i = 0 - while i < imax: - b0 = long(ord(list[j])) - b1 = (long(ord(list[j+1]))) << 8 - b2 = (long(ord(list[j+2]))) << 16 - b3 = (long(ord(list[j+3]))) << 24 - hl[i] = b0 | b1 |b2 | b3 - i = i+1 - j = j+4 - - return hl - - -def _rotateLeft(x, n): - "Rotate x (32 bit) left n bits circularly." - - return (x << n) | (x >> (32-n)) - - -# ====================================================================== -# The real MD5 meat... -# -# Implemented after "Applied Cryptography", 2nd ed., 1996, -# pp. 436-441 by Bruce Schneier. -# ====================================================================== - -# F, G, H and I are basic MD5 functions. - -def F(x, y, z): - return (x & y) | ((~x) & z) - -def G(x, y, z): - return (x & z) | (y & (~z)) - -def H(x, y, z): - return x ^ y ^ z - -def I(x, y, z): - return y ^ (x | (~z)) - - -def XX(func, a, b, c, d, x, s, ac): - """Wrapper for call distribution to functions F, G, H and I. - - This replaces functions FF, GG, HH and II from "Appl. Crypto." - Rotation is separate from addition to prevent recomputation - (now summed-up in one function). - """ - - res = 0L - res = res + a + func(b, c, d) - res = res + x - res = res + ac - res = res & 0xffffffffL - res = _rotateLeft(res, s) - res = res & 0xffffffffL - res = res + b - - return res & 0xffffffffL - - -class MD5: - "An implementation of the MD5 hash function in pure Python." - - def __init__(self): - "Initialisation." - - # Initial message length in bits(!). - self.length = 0L - self.count = [0, 0] - - # Initial empty message as a sequence of bytes (8 bit characters). - self.input = [] - - # Call a separate init function, that can be used repeatedly - # to start from scratch on the same object. - self.init() - - - def init(self): - "Initialize the message-digest and set all fields to zero." - - self.length = 0L - self.count = [0, 0] - self.input = [] - - # Load magic initialization constants. - self.A = 0x67452301L - self.B = 0xefcdab89L - self.C = 0x98badcfeL - self.D = 0x10325476L - - - def _transform(self, inp): - """Basic MD5 step transforming the digest based on the input. - - Note that if the Mysterious Constants are arranged backwards - in little-endian order and decrypted with the DES they produce - OCCULT MESSAGES! - """ - - a, b, c, d = A, B, C, D = self.A, self.B, self.C, self.D - - # Round 1. - - S11, S12, S13, S14 = 7, 12, 17, 22 - - a = XX(F, a, b, c, d, inp[ 0], S11, 0xD76AA478L) # 1 - d = XX(F, d, a, b, c, inp[ 1], S12, 0xE8C7B756L) # 2 - c = XX(F, c, d, a, b, inp[ 2], S13, 0x242070DBL) # 3 - b = XX(F, b, c, d, a, inp[ 3], S14, 0xC1BDCEEEL) # 4 - a = XX(F, a, b, c, d, inp[ 4], S11, 0xF57C0FAFL) # 5 - d = XX(F, d, a, b, c, inp[ 5], S12, 0x4787C62AL) # 6 - c = XX(F, c, d, a, b, inp[ 6], S13, 0xA8304613L) # 7 - b = XX(F, b, c, d, a, inp[ 7], S14, 0xFD469501L) # 8 - a = XX(F, a, b, c, d, inp[ 8], S11, 0x698098D8L) # 9 - d = XX(F, d, a, b, c, inp[ 9], S12, 0x8B44F7AFL) # 10 - c = XX(F, c, d, a, b, inp[10], S13, 0xFFFF5BB1L) # 11 - b = XX(F, b, c, d, a, inp[11], S14, 0x895CD7BEL) # 12 - a = XX(F, a, b, c, d, inp[12], S11, 0x6B901122L) # 13 - d = XX(F, d, a, b, c, inp[13], S12, 0xFD987193L) # 14 - c = XX(F, c, d, a, b, inp[14], S13, 0xA679438EL) # 15 - b = XX(F, b, c, d, a, inp[15], S14, 0x49B40821L) # 16 - - # Round 2. - - S21, S22, S23, S24 = 5, 9, 14, 20 - - a = XX(G, a, b, c, d, inp[ 1], S21, 0xF61E2562L) # 17 - d = XX(G, d, a, b, c, inp[ 6], S22, 0xC040B340L) # 18 - c = XX(G, c, d, a, b, inp[11], S23, 0x265E5A51L) # 19 - b = XX(G, b, c, d, a, inp[ 0], S24, 0xE9B6C7AAL) # 20 - a = XX(G, a, b, c, d, inp[ 5], S21, 0xD62F105DL) # 21 - d = XX(G, d, a, b, c, inp[10], S22, 0x02441453L) # 22 - c = XX(G, c, d, a, b, inp[15], S23, 0xD8A1E681L) # 23 - b = XX(G, b, c, d, a, inp[ 4], S24, 0xE7D3FBC8L) # 24 - a = XX(G, a, b, c, d, inp[ 9], S21, 0x21E1CDE6L) # 25 - d = XX(G, d, a, b, c, inp[14], S22, 0xC33707D6L) # 26 - c = XX(G, c, d, a, b, inp[ 3], S23, 0xF4D50D87L) # 27 - b = XX(G, b, c, d, a, inp[ 8], S24, 0x455A14EDL) # 28 - a = XX(G, a, b, c, d, inp[13], S21, 0xA9E3E905L) # 29 - d = XX(G, d, a, b, c, inp[ 2], S22, 0xFCEFA3F8L) # 30 - c = XX(G, c, d, a, b, inp[ 7], S23, 0x676F02D9L) # 31 - b = XX(G, b, c, d, a, inp[12], S24, 0x8D2A4C8AL) # 32 - - # Round 3. - - S31, S32, S33, S34 = 4, 11, 16, 23 - - a = XX(H, a, b, c, d, inp[ 5], S31, 0xFFFA3942L) # 33 - d = XX(H, d, a, b, c, inp[ 8], S32, 0x8771F681L) # 34 - c = XX(H, c, d, a, b, inp[11], S33, 0x6D9D6122L) # 35 - b = XX(H, b, c, d, a, inp[14], S34, 0xFDE5380CL) # 36 - a = XX(H, a, b, c, d, inp[ 1], S31, 0xA4BEEA44L) # 37 - d = XX(H, d, a, b, c, inp[ 4], S32, 0x4BDECFA9L) # 38 - c = XX(H, c, d, a, b, inp[ 7], S33, 0xF6BB4B60L) # 39 - b = XX(H, b, c, d, a, inp[10], S34, 0xBEBFBC70L) # 40 - a = XX(H, a, b, c, d, inp[13], S31, 0x289B7EC6L) # 41 - d = XX(H, d, a, b, c, inp[ 0], S32, 0xEAA127FAL) # 42 - c = XX(H, c, d, a, b, inp[ 3], S33, 0xD4EF3085L) # 43 - b = XX(H, b, c, d, a, inp[ 6], S34, 0x04881D05L) # 44 - a = XX(H, a, b, c, d, inp[ 9], S31, 0xD9D4D039L) # 45 - d = XX(H, d, a, b, c, inp[12], S32, 0xE6DB99E5L) # 46 - c = XX(H, c, d, a, b, inp[15], S33, 0x1FA27CF8L) # 47 - b = XX(H, b, c, d, a, inp[ 2], S34, 0xC4AC5665L) # 48 - - # Round 4. - - S41, S42, S43, S44 = 6, 10, 15, 21 - - a = XX(I, a, b, c, d, inp[ 0], S41, 0xF4292244L) # 49 - d = XX(I, d, a, b, c, inp[ 7], S42, 0x432AFF97L) # 50 - c = XX(I, c, d, a, b, inp[14], S43, 0xAB9423A7L) # 51 - b = XX(I, b, c, d, a, inp[ 5], S44, 0xFC93A039L) # 52 - a = XX(I, a, b, c, d, inp[12], S41, 0x655B59C3L) # 53 - d = XX(I, d, a, b, c, inp[ 3], S42, 0x8F0CCC92L) # 54 - c = XX(I, c, d, a, b, inp[10], S43, 0xFFEFF47DL) # 55 - b = XX(I, b, c, d, a, inp[ 1], S44, 0x85845DD1L) # 56 - a = XX(I, a, b, c, d, inp[ 8], S41, 0x6FA87E4FL) # 57 - d = XX(I, d, a, b, c, inp[15], S42, 0xFE2CE6E0L) # 58 - c = XX(I, c, d, a, b, inp[ 6], S43, 0xA3014314L) # 59 - b = XX(I, b, c, d, a, inp[13], S44, 0x4E0811A1L) # 60 - a = XX(I, a, b, c, d, inp[ 4], S41, 0xF7537E82L) # 61 - d = XX(I, d, a, b, c, inp[11], S42, 0xBD3AF235L) # 62 - c = XX(I, c, d, a, b, inp[ 2], S43, 0x2AD7D2BBL) # 63 - b = XX(I, b, c, d, a, inp[ 9], S44, 0xEB86D391L) # 64 - - A = (A + a) & 0xffffffffL - B = (B + b) & 0xffffffffL - C = (C + c) & 0xffffffffL - D = (D + d) & 0xffffffffL - - self.A, self.B, self.C, self.D = A, B, C, D - - - # Down from here all methods follow the Python Standard Library - # API of the md5 module. - - def update(self, inBuf): - """Add to the current message. - - Update the md5 object with the string arg. Repeated calls - are equivalent to a single call with the concatenation of all - the arguments, i.e. m.update(a); m.update(b) is equivalent - to m.update(a+b). - - The hash is immediately calculated for all full blocks. The final - calculation is made in digest(). This allows us to keep an - intermediate value for the hash, so that we only need to make - minimal recalculation if we call update() to add moredata to - the hashed string. - """ - - leninBuf = long(len(inBuf)) - - # Compute number of bytes mod 64. - index = (self.count[0] >> 3) & 0x3FL - - # Update number of bits. - self.count[0] = self.count[0] + (leninBuf << 3) - if self.count[0] < (leninBuf << 3): - self.count[1] = self.count[1] + 1 - self.count[1] = self.count[1] + (leninBuf >> 29) - - partLen = 64 - index - - if leninBuf >= partLen: - self.input[index:] = list(inBuf[:partLen]) - self._transform(_bytelist2long(self.input)) - i = partLen - while i + 63 < leninBuf: - self._transform(_bytelist2long(list(inBuf[i:i+64]))) - i = i + 64 - else: - self.input = list(inBuf[i:leninBuf]) - else: - i = 0 - self.input = self.input + list(inBuf) - - - def digest(self): - """Terminate the message-digest computation and return digest. - - Return the digest of the strings passed to the update() - method so far. This is a 16-byte string which may contain - non-ASCII characters, including null bytes. - """ - - A = self.A - B = self.B - C = self.C - D = self.D - input = [] + self.input - count = [] + self.count - - index = (self.count[0] >> 3) & 0x3fL - - if index < 56: - padLen = 56 - index - else: - padLen = 120 - index - - padding = ['\200'] + ['\000'] * 63 - self.update(padding[:padLen]) - - # Append length (before padding). - bits = _bytelist2long(self.input[:56]) + count - - self._transform(bits) - - # Store state in digest. - digest = _long2bytes(self.A << 96, 16)[:4] + \ - _long2bytes(self.B << 64, 16)[4:8] + \ - _long2bytes(self.C << 32, 16)[8:12] + \ - _long2bytes(self.D, 16)[12:] - - self.A = A - self.B = B - self.C = C - self.D = D - self.input = input - self.count = count - - return digest - - - def hexdigest(self): - """Terminate and return digest in HEX form. - - Like digest() except the digest is returned as a string of - length 32, containing only hexadecimal digits. This may be - used to exchange the value safely in email or other non- - binary environments. - """ - - return ''.join(['%02x' % ord(c) for c in self.digest()]) - - def copy(self): - """Return a clone object. - - Return a copy ('clone') of the md5 object. This can be used - to efficiently compute the digests of strings that share - a common initial substring. - """ - if 0: # set this to 1 to make the flow space crash - return copy.deepcopy(self) - clone = self.__class__() - clone.length = self.length - clone.count = [] + self.count[:] - clone.input = [] + self.input - clone.A = self.A - clone.B = self.B - clone.C = self.C - clone.D = self.D - return clone - - -# ====================================================================== -# Mimic Python top-level functions from standard library API -# for consistency with the md5 module of the standard library. -# ====================================================================== - -digest_size = 16 - -def new(arg=None): - """Return a new md5 object. - - If arg is present, the method call update(arg) is made. - """ - - md5 = MD5() - if arg: - md5.update(arg) - - return md5 - - -def md5(arg=None): - """Same as new(). - - For backward compatibility reasons, this is an alternative - name for the new() function. - """ - - return new(arg) Deleted: /pypy/dist/pypy/appspace/operator.py ============================================================================== --- /pypy/dist/pypy/appspace/operator.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,185 +0,0 @@ -import __builtin__ - -def abs(obj,): - 'abs(a) -- Same as abs(a).' - return __builtin__.abs(obj) -__abs__ = abs -def add(obj1, obj2): - 'add(a, b) -- Same as a + b.' - return obj1 + obj2 -__add__ = add -def and_(obj1,obj2): - 'and_(a, b) -- Same as a & b.' - return obj1 & obj2 -__and__ = and_ -def concat(obj1, obj2): - 'concat(a, b) -- Same as a + b, for a and b sequences.' - return obj1 + obj2 # XXX should we be stricter? -def contains(obj1,obj2): - 'contains(a, b) -- Same as b in a (note reversed operands).' - return obj2 in obj1 -__contains__ = contains -def countOf(a,b): - 'countOf(a, b) -- Return the number of times b occurs in a.' - count = 0 - for x in a: - if x == b: - count += 1 - return count -def delitem(obj, key): - 'delitem(a, b) -- Same as del a[b].' - del obj[key] -__delitem__ = delitem -def delslice(obj, start, end): - 'delslice(a, b, c) -- Same as del a[b:c].' - del obj[start:end] -__delslice__ = delslice -def div(a,b): - 'div(a, b) -- Same as a / b when __future__.division is not in effect.' - return a / b -__div__ = div -def eq(a, b): - 'eq(a, b) -- Same as a==b.' - return a == b -__eq__ = eq -def floordiv(a, b): - 'floordiv(a, b) -- Same as a // b.' - return a // b -__floordiv__ = floordiv -def ge(a, b): - 'ge(a, b) -- Same as a>=b.' - return a >= b -__ge__ = ge -def getitem(a, b): - 'getitem(a, b) -- Same as a[b].' - return a[b] -__getitem__ = getitem -def getslice(a, start, end): - 'getslice(a, b, c) -- Same as a[b:c].' - return a[start:end] -__getslice__ = getslice -def gt(a,b): - 'gt(a, b) -- Same as a>b.' - return a > b -__gt__ = gt -def indexOf(a, b): - 'indexOf(a, b) -- Return the first index of b in a.' - index = 0 - for x in a: - if x == b: - return index - index += 1 - raise ValueError, 'sequence.index(x): x not in sequence' -def inv(obj,): - 'inv(a) -- Same as ~a.' - return ~obj -__inv__ = inv -def invert(obj,): - 'invert(a) -- Same as ~a.' - return ~obj -__invert__ = invert -def isCallable(obj,): - 'isCallable(a) -- Same as callable(a).' - return callable(obj) - -# XXX the following is approximative -def isMappingType(obj,): - 'isMappingType(a) -- Return True if a has a mapping type, False otherwise.' - return hasattr(obj, '__getitem__') and hasattr(obj, 'keys') -def isNumberType(obj,): - 'isNumberType(a) -- Return True if a has a numeric type, False otherwise.' - return hasattr(obj, '__int__') or hasattr(obj, '__float__') -def isSequenceType(obj,): - 'isSequenceType(a) -- Return True if a has a sequence type, False otherwise.' - return hasattr(obj, '__getitem__') - -def is_(a, b): - 'is_(a, b) -- Same as a is b.' - return a is b -def is_not(a, b): - 'is_not(a, b) -- Same as a is not b.' - return a is not b -def le(a, b): - 'le(a, b) -- Same as a<=b.' - return a <= b -__le__ = le -def lshift(a, b): - 'lshift(a, b) -- Same as a << b.' - return a << b -__lshift__ = lshift -def lt(a, b): - 'lt(a, b) -- Same as a> b.' - return a >> b -__rshift__ = rshift -def sequenceIncludes(a, b): - 'sequenceIncludes(a, b) -- Same as b in a (note reversed operands; deprecated).' - for x in a: - if x == b: - return True - return False -def setitem(obj, key, value): - 'setitem(a, b, c) -- Same as a[b] = c.' - obj[key] = value -__setitem__ = setitem -def setslice(a, b, c, d): - 'setslice(a, b, c, d) -- Same as a[b:c] = d.' - a[b:c] = d -__setslice__ = setslice -def sub(a, b): - 'sub(a, b) -- Same as a - b.' - return a - b -__sub__ = sub - -exec """from __future__ import division -def truediv(a, b): - 'truediv(a, b) -- Same as a / b when __future__.division is in effect.' - return a / b -""" -__truediv__ = truediv -def truth(a,): - 'truth(a) -- Return True if a is true, False otherwise.' - return not not a -def xor(a, b): - 'xor(a, b) -- Same as a ^ b.' - return a ^ b -__xor__ = xor Deleted: /pypy/dist/pypy/appspace/plexre.py ============================================================================== --- /pypy/dist/pypy/appspace/plexre.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,15 +0,0 @@ -from StringIO import StringIO -from Pyrex.Plex import Scanner, Lexicon, Traditional, Errors -class Pattern: - def __init__(self, pattern, flags): - compiled = Traditional.re(pattern) - lexicon = Lexicon([(compiled, None)]) - self.lexicon = lexicon - def match(self, string): - stream = StringIO(string) - scanner = Scanner(self.lexicon, stream) - try: - scanner.read() - return 1 - except Errors.UnrecognizedInput: - return 0 Deleted: /pypy/dist/pypy/appspace/pystone.py ============================================================================== --- /pypy/dist/pypy/appspace/pystone.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,267 +0,0 @@ -#! /usr/bin/env python - -""" -"PYSTONE" Benchmark Program - -Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes) - -Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. - - Translated from ADA to C by Rick Richardson. - Every method to preserve ADA-likeness has been used, - at the expense of C-ness. - - Translated from C to Python by Guido van Rossum. - -Version History: - - Version 1.1 corrects two bugs in version 1.0: - - First, it leaked memory: in Proc1(), NextRecord ends - up having a pointer to itself. I have corrected this - by zapping NextRecord.PtrComp at the end of Proc1(). - - Second, Proc3() used the operator != to compare a - record to None. This is rather inefficient and not - true to the intention of the original benchmark (where - a pointer comparison to None is intended; the != - operator attempts to find a method __cmp__ to do value - comparison of the record). Version 1.1 runs 5-10 - percent faster than version 1.0, so benchmark figures - of different versions can't be compared directly. - -""" - -LOOPS = 50000 - -from time import clock - -__version__ = "1.1" - -[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) - -class Record: - - def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, - IntComp = 0, StringComp = 0): - self.PtrComp = PtrComp - self.Discr = Discr - self.EnumComp = EnumComp - self.IntComp = IntComp - self.StringComp = StringComp - - def copy(self): - return Record(self.PtrComp, self.Discr, self.EnumComp, - self.IntComp, self.StringComp) - -TRUE = 1 -FALSE = 0 - -def main(loops=LOOPS): - benchtime, stones = pystones(loops) - print "Pystone(%s) time for %d passes = %g" % \ - (__version__, loops, benchtime) - print "This machine benchmarks at %g pystones/second" % stones - - -def pystones(loops=LOOPS): - return Proc0(loops) - -IntGlob = 0 -BoolGlob = FALSE -Char1Glob = '\0' -Char2Glob = '\0' -Array1Glob = [0]*51 -Array2Glob = map(lambda x: x[:], [Array1Glob]*51) -PtrGlb = None -PtrGlbNext = None - -def Proc0(loops=LOOPS): - global IntGlob - global BoolGlob - global Char1Glob - global Char2Glob - global Array1Glob - global Array2Glob - global PtrGlb - global PtrGlbNext - - starttime = clock() - for i in range(loops): - pass - nulltime = clock() - starttime - - PtrGlbNext = Record() - PtrGlb = Record() - PtrGlb.PtrComp = PtrGlbNext - PtrGlb.Discr = Ident1 - PtrGlb.EnumComp = Ident3 - PtrGlb.IntComp = 40 - PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" - String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" - Array2Glob[8][7] = 10 - - starttime = clock() - - for i in range(loops): - Proc5() - Proc4() - IntLoc1 = 2 - IntLoc2 = 3 - String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" - EnumLoc = Ident2 - BoolGlob = not Func2(String1Loc, String2Loc) - while IntLoc1 < IntLoc2: - IntLoc3 = 5 * IntLoc1 - IntLoc2 - IntLoc3 = Proc7(IntLoc1, IntLoc2) - IntLoc1 = IntLoc1 + 1 - Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) - PtrGlb = Proc1(PtrGlb) - CharIndex = 'A' - while CharIndex <= Char2Glob: - if EnumLoc == Func1(CharIndex, 'C'): - EnumLoc = Proc6(Ident1) - CharIndex = chr(ord(CharIndex)+1) - IntLoc3 = IntLoc2 * IntLoc1 - IntLoc2 = IntLoc3 / IntLoc1 - IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 - IntLoc1 = Proc2(IntLoc1) - - benchtime = clock() - starttime - nulltime - return benchtime, (loops / benchtime) - -def Proc1(PtrParIn): - PtrParIn.PtrComp = NextRecord = PtrGlb.copy() - PtrParIn.IntComp = 5 - NextRecord.IntComp = PtrParIn.IntComp - NextRecord.PtrComp = PtrParIn.PtrComp - NextRecord.PtrComp = Proc3(NextRecord.PtrComp) - if NextRecord.Discr == Ident1: - NextRecord.IntComp = 6 - NextRecord.EnumComp = Proc6(PtrParIn.EnumComp) - NextRecord.PtrComp = PtrGlb.PtrComp - NextRecord.IntComp = Proc7(NextRecord.IntComp, 10) - else: - PtrParIn = NextRecord.copy() - NextRecord.PtrComp = None - return PtrParIn - -def Proc2(IntParIO): - IntLoc = IntParIO + 10 - while 1: - if Char1Glob == 'A': - IntLoc = IntLoc - 1 - IntParIO = IntLoc - IntGlob - EnumLoc = Ident1 - if EnumLoc == Ident1: - break - return IntParIO - -def Proc3(PtrParOut): - global IntGlob - - if PtrGlb is not None: - PtrParOut = PtrGlb.PtrComp - else: - IntGlob = 100 - PtrGlb.IntComp = Proc7(10, IntGlob) - return PtrParOut - -def Proc4(): - global Char2Glob - - BoolLoc = Char1Glob == 'A' - BoolLoc = BoolLoc or BoolGlob - Char2Glob = 'B' - -def Proc5(): - global Char1Glob - global BoolGlob - - Char1Glob = 'A' - BoolGlob = FALSE - -def Proc6(EnumParIn): - EnumParOut = EnumParIn - if not Func3(EnumParIn): - EnumParOut = Ident4 - if EnumParIn == Ident1: - EnumParOut = Ident1 - elif EnumParIn == Ident2: - if IntGlob > 100: - EnumParOut = Ident1 - else: - EnumParOut = Ident4 - elif EnumParIn == Ident3: - EnumParOut = Ident2 - elif EnumParIn == Ident4: - pass - elif EnumParIn == Ident5: - EnumParOut = Ident3 - return EnumParOut - -def Proc7(IntParI1, IntParI2): - IntLoc = IntParI1 + 2 - IntParOut = IntParI2 + IntLoc - return IntParOut - -def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): - global IntGlob - - IntLoc = IntParI1 + 5 - Array1Par[IntLoc] = IntParI2 - Array1Par[IntLoc+1] = Array1Par[IntLoc] - Array1Par[IntLoc+30] = IntLoc - for IntIndex in range(IntLoc, IntLoc+2): - Array2Par[IntLoc][IntIndex] = IntLoc - Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 - Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] - IntGlob = 5 - -def Func1(CharPar1, CharPar2): - CharLoc1 = CharPar1 - CharLoc2 = CharLoc1 - if CharLoc2 != CharPar2: - return Ident1 - else: - return Ident2 - -def Func2(StrParI1, StrParI2): - IntLoc = 1 - while IntLoc <= 1: - if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: - CharLoc = 'A' - IntLoc = IntLoc + 1 - if CharLoc >= 'W' and CharLoc <= 'Z': - IntLoc = 7 - if CharLoc == 'X': - return TRUE - else: - if StrParI1 > StrParI2: - IntLoc = IntLoc + 7 - return TRUE - else: - return FALSE - -def Func3(EnumParIn): - EnumLoc = EnumParIn - if EnumLoc == Ident3: return TRUE - return FALSE - -if __name__ == '__main__': - import sys - def error(msg): - print >>sys.stderr, msg, - print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0] - sys.exit(100) - nargs = len(sys.argv) - 1 - if nargs > 1: - error("%d arguments are too many;" % nargs) - elif nargs == 1: - try: loops = int(sys.argv[1]) - except ValueError: - error("Invalid argument %r;" % sys.argv[1]) - else: - loops = LOOPS - main(loops) - Deleted: /pypy/dist/pypy/appspace/sha.py ============================================================================== --- /pypy/dist/pypy/appspace/sha.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,341 +0,0 @@ -#!/usr/bin/env python -# -*- coding: iso-8859-1 - -"""A sample implementation of SHA-1 in pure Python. - - Framework adapted from Dinu Gherman's MD5 implementation by - J. Hall?n and L. Creighton. SHA-1 implementation based directly on - the text of the NIST standard FIPS PUB 180-1. -""" - - -__date__ = '2004-11-17' -__version__ = 0.91 # Modernised by J. Hall?n and L. Creighton for Pypy - - -import struct, copy - - -# ====================================================================== -# Bit-Manipulation helpers -# -# _long2bytes() was contributed by Barry Warsaw -# and is reused here with tiny modifications. -# ====================================================================== - -def _long2bytesBigEndian(n, blocksize=0): - """Convert a long integer to a byte string. - - If optional blocksize is given and greater than zero, pad the front - of the byte string with binary zeros so that the length is a multiple - of blocksize. - """ - - # After much testing, this algorithm was deemed to be the fastest. - s = '' - pack = struct.pack - while n > 0: - s = pack('>I', n & 0xffffffffL) + s - n = n >> 32 - - # Strip off leading zeros. - for i in range(len(s)): - if s[i] <> '\000': - break - else: - # Only happens when n == 0. - s = '\000' - i = 0 - - s = s[i:] - - # Add back some pad bytes. This could be done more efficiently - # w.r.t. the de-padding being done above, but sigh... - if blocksize > 0 and len(s) % blocksize: - s = (blocksize - len(s) % blocksize) * '\000' + s - - return s - - -def _bytelist2longBigEndian(list): - "Transform a list of characters into a list of longs." - - imax = len(list)/4 - hl = [0L] * imax - - j = 0 - i = 0 - while i < imax: - b0 = long(ord(list[j])) << 24 - b1 = long(ord(list[j+1])) << 16 - b2 = long(ord(list[j+2])) << 8 - b3 = long(ord(list[j+3])) - hl[i] = b0 | b1 | b2 | b3 - i = i+1 - j = j+4 - - return hl - - -def _rotateLeft(x, n): - "Rotate x (32 bit) left n bits circularly." - - return (x << n) | (x >> (32-n)) - - -# ====================================================================== -# The SHA transformation functions -# -# ====================================================================== - -def f0_19(B, C, D): - return (B & C) | ((~ B) & D) - -def f20_39(B, C, D): - return B ^ C ^ D - -def f40_59(B, C, D): - return (B & C) | (B & D) | (C & D) - -def f60_79(B, C, D): - return B ^ C ^ D - - -f = [f0_19, f20_39, f40_59, f60_79] - -# Constants to be used -K = [ - 0x5A827999L, # ( 0 <= t <= 19) - 0x6ED9EBA1L, # (20 <= t <= 39) - 0x8F1BBCDCL, # (40 <= t <= 59) - 0xCA62C1D6L # (60 <= t <= 79) - ] - -class MD5: - "An implementation of the MD5 hash function in pure Python." - - def __init__(self): - "Initialisation." - - # Initial message length in bits(!). - self.length = 0L - self.count = [0, 0] - - # Initial empty message as a sequence of bytes (8 bit characters). - self.input = [] - - # Call a separate init function, that can be used repeatedly - # to start from scratch on the same object. - self.init() - - - def init(self): - "Initialize the message-digest and set all fields to zero." - - self.length = 0L - self.input = [] - - # Initial 160 bit message digest (5 times 32 bit). - self.H0 = 0x67452301L - self.H1 = 0xEFCDAB89L - self.H2 = 0x98BADCFEL - self.H3 = 0x10325476L - self.H4 = 0xC3D2E1F0L - - def _transform(self, W): - - for t in range(16, 80): - W.append(_rotateLeft( - W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffffL) - - A = self.H0 - B = self.H1 - C = self.H2 - D = self.H3 - E = self.H4 - - """ - This loop was unrolled to gain about 10% in speed - for t in range(0, 80): - TEMP = _rotateLeft(A, 5) + f[t/20] + E + W[t] + K[t/20] - E = D - D = C - C = _rotateLeft(B, 30) & 0xffffffffL - B = A - A = TEMP & 0xffffffffL - """ - - for t in range(0, 20): - TEMP = _rotateLeft(A, 5) + ((B & C) | ((~ B) & D)) + E + W[t] + K[0] - E = D - D = C - C = _rotateLeft(B, 30) & 0xffffffffL - B = A - A = TEMP & 0xffffffffL - - for t in range(20, 40): - TEMP = _rotateLeft(A, 5) + (B ^ C ^ D) + E + W[t] + K[1] - E = D - D = C - C = _rotateLeft(B, 30) & 0xffffffffL - B = A - A = TEMP & 0xffffffffL - - for t in range(40, 60): - TEMP = _rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2] - E = D - D = C - C = _rotateLeft(B, 30) & 0xffffffffL - B = A - A = TEMP & 0xffffffffL - - for t in range(60, 80): - TEMP = _rotateLeft(A, 5) + (B ^ C ^ D) + E + W[t] + K[3] - E = D - D = C - C = _rotateLeft(B, 30) & 0xffffffffL - B = A - A = TEMP & 0xffffffffL - - - self.H0 = (self.H0 + A) & 0xffffffffL - self.H1 = (self.H1 + B) & 0xffffffffL - self.H2 = (self.H2 + C) & 0xffffffffL - self.H3 = (self.H3 + D) & 0xffffffffL - self.H4 = (self.H4 + E) & 0xffffffffL - - - # Down from here all methods follow the Python Standard Library - # API of the sha module. - - def update(self, inBuf): - """Add to the current message. - - Update the md5 object with the string arg. Repeated calls - are equivalent to a single call with the concatenation of all - the arguments, i.e. m.update(a); m.update(b) is equivalent - to m.update(a+b). - - The hash is immediately calculated for all full blocks. The final - calculation is made in digest(). It will calculate 1-2 blocks, - depending on how much padding we have to add. This allows us to - keep an intermediate value for the hash, so that we only need to - make minimal recalculation if we call update() to add more data - to the hashed string. - """ - - leninBuf = long(len(inBuf)) - - # Compute number of bytes mod 64. - index = (self.count[1] >> 3) & 0x3FL - - # Update number of bits. - self.count[1] = self.count[1] + (leninBuf << 3) - if self.count[1] < (leninBuf << 3): - self.count[0] = self.count[0] + 1 - self.count[0] = self.count[0] + (leninBuf >> 29) - - partLen = 64 - index - - if leninBuf >= partLen: - self.input[index:] = list(inBuf[:partLen]) - self._transform(_bytelist2longBigEndian(self.input)) - i = partLen - while i + 63 < leninBuf: - self._transform(_bytelist2longBigEndian(list(inBuf[i:i+64]))) - i = i + 64 - else: - self.input = list(inBuf[i:leninBuf]) - else: - i = 0 - self.input = self.input + list(inBuf) - - - def digest(self): - """Terminate the message-digest computation and return digest. - - Return the digest of the strings passed to the update() - method so far. This is a 16-byte string which may contain - non-ASCII characters, including null bytes. - """ - - H0 = self.H0 - H1 = self.H1 - H2 = self.H2 - H3 = self.H3 - H4 = self.H4 - input = [] + self.input - count = [] + self.count - - index = (self.count[1] >> 3) & 0x3fL - - if index < 56: - padLen = 56 - index - else: - padLen = 120 - index - - padding = ['\200'] + ['\000'] * 63 - self.update(padding[:padLen]) - - # Append length (before padding). - bits = _bytelist2longBigEndian(self.input[:56]) + count - - self._transform(bits) - - # Store state in digest. - digest = _long2bytesBigEndian(self.H0, 4) + \ - _long2bytesBigEndian(self.H1, 4) + \ - _long2bytesBigEndian(self.H2, 4) + \ - _long2bytesBigEndian(self.H3, 4) + \ - _long2bytesBigEndian(self.H4, 4) - - self.H0 = H0 - self.H1 = H1 - self.H2 = H2 - self.H3 = H3 - self.H4 = H4 - self.input = input - self.count = count - - return digest - - - def hexdigest(self): - """Terminate and return digest in HEX form. - - Like digest() except the digest is returned as a string of - length 32, containing only hexadecimal digits. This may be - used to exchange the value safely in email or other non- - binary environments. - """ - return ''.join(['%02x' % ord(c) for c in self.digest()]) - - def copy(self): - """Return a clone object. - - Return a copy ('clone') of the md5 object. This can be used - to efficiently compute the digests of strings that share - a common initial substring. - """ - - return copy.deepcopy(self) - - -# ====================================================================== -# Mimic Python top-level functions from standard library API -# for consistency with the md5 module of the standard library. -# ====================================================================== - -digest_size = 16 - -def new(arg=None): - """Return a new md5 object. - - If arg is present, the method call update(arg) is made. - """ - - md5 = MD5() - if arg: - md5.update(arg) - - return md5 Deleted: /pypy/dist/pypy/appspace/sio.py ============================================================================== --- /pypy/dist/pypy/appspace/sio.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,913 +0,0 @@ -"""New standard I/O library. - -This code is still very young and experimental! - -There are fairly complete unit tests in test_sio.py. - -The design is simple: - -- A raw stream supports read(n), write(s), seek(offset, whence=0) and - tell(). This is generally unbuffered. Raw streams may support - Unicode. - -- A basis stream provides the raw stream API and builds on a much more - low-level API, e.g. the os, mmap or socket modules. - -- A filtering stream is raw stream built on top of another raw stream. - There are filtering streams for universal newline translation and - for unicode translation. - -- A buffering stream supports the full classic Python I/O API: - read(n=-1), readline(), readlines(sizehint=0), tell(), seek(offset, - whence=0), write(s), writelines(lst), as well as __iter__() and - next(). (There's also readall() but that's a synonym for read() - without arguments.) This is a superset of the raw stream API. I - haven't thought about fileno() and isatty() yet, nor about - truncate() or the various attributes like name and mode. Also, - close() is not implemented right. We really need only one buffering - stream implementation, which is a filtering stream. - -You typically take a basis stream, place zero or more filtering -streams on top of it, and then top it off with a buffering stream. - -""" - -import os - -class Stream(object): - "All streams except the base ones need to inherit from this class." - base = None - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - return getattr(self.base, name) - -class BufferingInputStream(Stream): - - """Standard buffering input stream. - - This is typically the top of the stack. - """ - - bigsize = 2**19 # Half a Meg - bufsize = 2**13 # 8 K - - def __init__(self, base, bufsize=None): - self.base = base - self.do_read = getattr(base, "read", None) - # function to fill buffer some more - self.do_tell = getattr(base, "tell", None) - # None, or return a byte offset - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.close = base.close - - if bufsize is None: # Get default from the class - bufsize = self.bufsize - self.bufsize = bufsize # buffer size (hint only) - self.lines = [] # ready-made lines (sans "\n") - self.buf = "" # raw data (may contain "\n") - # Invariant: readahead == "\n".join(self.lines + [self.buf]) - # self.lines contains no "\n" - # self.buf may contain "\n" - - def tell(self): - bytes = self.do_tell() # This may fail - offset = len(self.buf) - for line in self.lines: - offset += len(line) + 1 - assert bytes >= offset, (locals(), self.__dict__) - return bytes - offset - - def seek(self, offset, whence=0): - # This may fail on the do_seek() or do_tell() call. - # But it won't call either on a relative forward seek. - # Nor on a seek to the very end. - if whence == 0 or (whence == 2 and self.do_seek is not None): - self.do_seek(offset, whence) - self.lines = [] - self.buf = "" - return - if whence == 2: - # Skip relative to EOF by reading and saving only just as - # much as needed - assert self.do_seek is None - data = "\n".join(self.lines + [self.buf]) - total = len(data) - buffers = [data] - self.lines = [] - self.buf = "" - while 1: - data = self.do_read(self.bufsize) - if not data: - break - buffers.append(data) - total += len(data) - while buffers and total >= len(buffers[0]) - offset: - total -= len(buffers[0]) - del buffers[0] - cutoff = total + offset - if cutoff < 0: - raise TypeError, "cannot seek back" - if buffers: - buffers[0] = buffers[0][cutoff:] - self.buf = "".join(buffers) - self.lines = [] - return - if whence == 1: - if offset < 0: - self.do_seek(self.tell() + offset, 0) - self.lines = [] - self.buf = "" - return - while self.lines: - line = self.lines[0] - if offset <= len(line): - self.lines[0] = line[offset:] - return - offset -= len(self.lines[0]) - 1 - del self.lines[0] - assert not self.lines - if offset <= len(self.buf): - self.buf = self.buf[offset:] - return - offset -= len(self.buf) - self.buf = "" - if self.do_seek is None: - self.read(offset) - else: - self.do_seek(offset, 1) - return - raise ValueError, "whence should be 0, 1 or 2" - - def readall(self): - self.lines.append(self.buf) - more = ["\n".join(self.lines)] - self.lines = [] - self.buf = "" - bufsize = self.bufsize - while 1: - data = self.do_read(bufsize) - if not data: - break - more.append(data) - bufsize = max(bufsize*2, self.bigsize) - return "".join(more) - - def read(self, n=-1): - if n < 0: - return self.readall() - - if self.lines: - # See if this can be satisfied from self.lines[0] - line = self.lines[0] - if len(line) >= n: - self.lines[0] = line[n:] - return line[:n] - - # See if this can be satisfied *without exhausting* self.lines - k = 0 - i = 0 - for line in self.lines: - k += len(line) - if k >= n: - lines = self.lines[:i] - data = self.lines[i] - cutoff = len(data) - (k-n) - lines.append(data[:cutoff]) - self.lines[:i+1] = [data[cutoff:]] - return "\n".join(lines) - k += 1 - i += 1 - - # See if this can be satisfied from self.lines plus self.buf - if k + len(self.buf) >= n: - lines = self.lines - self.lines = [] - cutoff = n - k - lines.append(self.buf[:cutoff]) - self.buf = self.buf[cutoff:] - return "\n".join(lines) - - else: - # See if this can be satisfied from self.buf - data = self.buf - k = len(data) - if k >= n: - cutoff = len(data) - (k-n) - self.buf = data[cutoff:] - return data[:cutoff] - - lines = self.lines - self.lines = [] - lines.append(self.buf) - self.buf = "" - data = "\n".join(lines) - more = [data] - k = len(data) - while k < n: - data = self.do_read(max(self.bufsize, n-k)) - k += len(data) - more.append(data) - if not data: - break - cutoff = len(data) - (k-n) - self.buf = data[cutoff:] - more[-1] = data[:cutoff] - return "".join(more) - - def __iter__(self): - return self - - def next(self): - if self.lines: - return self.lines.pop(0) + "\n" - - # This block is needed because read() can leave self.buf - # containing newlines - self.lines = self.buf.split("\n") - self.buf = self.lines.pop() - if self.lines: - return self.lines.pop(0) + "\n" - - buf = self.buf and [self.buf] or [] - while 1: - self.buf = self.do_read(self.bufsize) - self.lines = self.buf.split("\n") - self.buf = self.lines.pop() - if self.lines: - buf.append(self.lines.pop(0)) - buf.append("\n") - break - if not self.buf: - break - buf.append(self.buf) - - line = "".join(buf) - if not line: - raise StopIteration - return line - - def readline(self): - try: - return self.next() - except StopIteration: - return "" - - def readlines(self, sizehint=0): - return list(self) - -class BufferingOutputStream(Stream): - - """Standard buffering output stream. - - This is typically the top of the stack. - """ - - bigsize = 2**19 # Half a Meg - bufsize = 2**13 # 8 K - - def __init__(self, base, bufsize=None): - self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - - if bufsize is None: # Get default from the class - bufsize = self.bufsize - self.bufsize = bufsize # buffer size (hint only) - self.buf = "" - self.tell() - - def tell(self): - assert self.do_tell is not None - if not hasattr(self, 'pos'): - self.pos = self.do_tell() - - return self.pos - - def seek(self, offset, whence=0): - self.flush() - self.do_seek(offset, whence) - self.pos = self.do_tell() - - def flush(self): - self.do_write(self.buf) - self.buf = '' - self.base.flush() - - def write(self, data): - buflen = len(self.buf) - datalen = len(data) - if datalen + buflen < self.bufsize: - self.buf += data - self.pos += datalen - else: - self.buf += data[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(data[self.bufsize-buflen:]) - - def writelines(self, sequence): - for s in sequence: - self.write(s) - - def close(self): - if (self.buf): - self.do_write(self.buf) - self.buf = '' - self.do_close() - - def truncate(self, size=None): - self.flush() - self.do_truncate(size) - -class LineBufferingOutputStream(BufferingOutputStream): - - """Line buffering output stream. - - This is typically the top of the stack. - """ - - def __init__(self, base, bufsize=None): - self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - - self.linesep = os.linesep - self.buf = "" # raw data (may contain "\n") - self.tell() - - def write(self, data): - all_lines = data.split(self.linesep) - full_lines = all_lines[:-1] - for line in full_lines: - line += self.linesep - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - self.do_write(self.buf) - self.buf = '' - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - # The last part of the split data never has a terminating linesep. - # If the data has a terminating linesep, the last element is an - # empty string. - - line = all_lines[-1] - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - def flush(self): - if self.buf: - self.do_write(self.buf) - self.buf = '' - self.base.flush() - - -class BufferingInputOutputStream(Stream): - """To handle buffered input and output at the same time, we are - switching back and forth between using BuffereingInputStream - and BufferingOutputStream as reads and writes are done. - A more optimal solution would be to read and write on the same - buffer, but it would take a fair bit of time to implement. - """ - - def __init__(self, base, bufsize=None): - self.base = base - self.bufsize = bufsize - self.reader = None - self.writer = None - - def read(self, n=-1): - if not self.reader: - if self.writer: - self.writer.flush() - self.writer = None - self.reader = BufferingInputStream(self.base, self.bufsize) - return self.reader.read(n) - - def write(self, data): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.write(data) - - def truncate(self, size=None): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.truncate(size) - - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - if not self.reader and not self.writer: - self.reader = BufferingInputStream(self.base, self.bufsize) - - if self.reader: - return getattr(self.reader, name) - - return getattr(self.writer, name) - -class CRLFFilter(Stream): - - """Filtering stream for universal newlines. - - TextInputFilter is more general, but this is faster when you don't - need tell/seek. - """ - - def __init__(self, base): - self.base = base - self.do_read = base.read - self.atcr = False - self.close = base.close - - def read(self, n=-1): - data = self.do_read(n) - if self.atcr: - if data.startswith("\n"): - data = data[1:] # Very rare case: in the middle of "\r\n" - self.atcr = False - if "\r" in data: - self.atcr = data.endswith("\r") # Test this before removing \r - data = data.replace("\r\n", "\n") # Catch \r\n this first - data = data.replace("\r", "\n") # Remaining \r are standalone - return data - -class MMapFile(object): - - """Standard I/O basis stream using mmap.""" - - def __init__(self, filename, mode="r"): - import mmap - self.filename = filename - self.mode = mode - if mode == "r": - flag = os.O_RDONLY - self.access = mmap.ACCESS_READ - else: - if mode == "w": - flag = os.O_RDWR | os.O_CREAT - elif mode == "a": - flag = os.O_RDWR - else: - raise ValueError, "mode should be 'r', 'w' or 'a'" - self.access = mmap.ACCESS_WRITE - if hasattr(os, "O_BINARY"): - flag |= os.O_BINARY - self.fd = os.open(filename, flag) - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - self.pos = 0 - - def __del__(self): - self.close() - - mm = fd = None - - def close(self): - if self.mm is not None: - self.mm.close() - self.mm = None - if self.fd is not None: - os.close(self.fd) - self.fd = None - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 0: - self.pos = max(0, offset) - elif whence == 1: - self.pos = max(0, self.pos + offset) - elif whence == 2: - self.pos = max(0, self.mm.size() + offset) - else: - raise ValueError, "seek(): whence must be 0, 1 or 2" - - def readall(self): - return self.read() - - def read(self, n=-1): - import mmap - if n >= 0: - aim = self.pos + n - else: - aim = self.mm.size() # Actual file size, may be more than mapped - n = aim - self.pos - data = self.mm[self.pos:aim] - if len(data) < n: - del data - # File grew since opened; remap to get the new data - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - data = self.mm[self.pos:aim] - self.pos += len(data) - return data - - def __iter__(self): - return self - - def readline(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - self.pos += len(data) - return data - - def next(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - if not data: - raise StopIteration - self.pos += len(data) - return data - - def readlines(self, sizehint=0): - return list(iter(self.readline, "")) - - def write(self, data): - end = self.pos + len(data) - try: - self.mm[self.pos:end] = data - # This can raise IndexError on Windows, ValueError on Unix - except (IndexError, ValueError): - # XXX On Unix, this resize() call doesn't work - self.mm.resize(end) - self.mm[self.pos:end] = data - self.pos = end - - def writelines(self, lines): - filter(self.write, lines) - - def flush(self): - if self.mm is None: - raise ValueError('I/O operation on closed file') - self.mm.flush() - -class DiskFile(object): - - """Standard I/O basis stream using os.open/close/read/write/lseek""" - - # This is not quite correct, since more letters are allowed after - # these. However, the following are the only starting strings allowed - # in the mode parameter. - modes = { - 'r' : os.O_RDONLY, - 'rb' : os.O_RDONLY, - 'rU' : os.O_RDONLY, - 'U' : os.O_RDONLY, - 'w' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'wb' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'a' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'ab' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'r+' : os.O_RDWR, - 'rb+': os.O_RDWR, - 'r+b': os.O_RDWR, - 'w+' : os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'wb+': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'w+b': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'a+' : os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'ab+': os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'a+b': os.O_RDWR | os.O_CREAT | os.O_EXCL, - } - def __init__(self, filename, mode="r"): - self.filename = filename - self.mode = mode - try: - flag = DiskFile.modes[mode] - except KeyError: - raise ValueError, "mode should be 'r', 'r+', 'w', 'w+' or 'a+'" - - O_BINARY = getattr(os, "O_BINARY", 0) - flag |= O_BINARY - try: - self.fd = os.open(filename, flag) - except OSError: - # Opening in mode 'a' or 'a+' and file already exists - flag = flag & (os.O_RDWR | O_BINARY) - self.fd = os.open(filename, flag) - if mode[0] == 'a': - os.lseek(self.fd, 0, 2) # Move to end of file - - def seek(self, offset, whence=0): - if self.fd is None: - raise ValueError('I/O operation on closed file') - os.lseek(self.fd, offset, whence) - - def tell(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return os.lseek(self.fd, 0, 1) - - def read(self, n=-1): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if n >= 0: - return os.read(self.fd, n) - data = [] - while 1: - moreData = os.read(self.fd, 2**20) - if len(moreData) == 0: - return ''.join(data) - data.append(moreData) - - def write(self, data): - if self.fd is None: - raise ValueError('I/O operation on closed file') - while data: - n = os.write(self.fd, data) - data = data[n:] - - def close(self): - fd = self.fd - if fd is not None: - self.fd = None - os.close(fd) - - def truncate(self, size=None): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if size is None: - size = self.tell() - try: - os.ftruncate(self.fd, size) - except AttributeError: - raise NotImplementedError - - def isatty(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - try: - return os.isatty(self.fd) - except AttributeError: - raise NotImplementedError - - def fileno(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return self.fd - - def flush(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - - def __del__(self): - try: - self.close() - except: - pass - -class TextInputFilter(Stream): - - """Filtering input stream for universal newline translation.""" - - def __init__(self, base): - self.base = base # must implement read, may implement tell, seek - self.atcr = False # Set when last char read was \r - self.buf = "" # Optional one-character read-ahead buffer - self.close = base.close - self.CR = False - self.NL = False - self.CRLF = False - - def __getattr__(self, name): - if name == 'newlines': - foundchars = self.CR * 1 + self.NL * 2 + self.CRLF * 4 - if not foundchars: - return None - if foundchars in [1, 2, 4]: - if self.CR: - return '\r' - elif self.NL: - return '\n' - else: - return '\r\n' - else: - result = [] - if self.CR: - result.append('\r') - if self.NL: - result.append('\n') - if self.CRLF: - result.append('\r\n') - return tuple(result) - - def read(self, n): - """Read up to n bytes.""" - if n <= 0: - return "" - if self.buf: - assert not self.atcr - data = self.buf - self.buf = "" - return data - data = self.base.read(n) - - # The following whole ugly mess is because we need to keep track of - # exactly which line separators we have seen for self.newlines, - # grumble, grumble. This has an interesting corner-case. - # - # Consider a file consisting of exactly one line ending with '\r'. - # The first time you read(), you will not know whether it is a - # CR separator or half of a CRLF separator. Neither will be marked - # as seen, since you are waiting for your next read to determine - # what you have seen. But there's no more to read ... - - if self.atcr: - if data.startswith("\n"): - data = data[1:] - self.CRLF = True - if not data: - data = self.base.read(n) - else: - self.CR = True - self.atcr = False - - for i in range(len(data)): - if data[i] == '\n': - if i > 0 and data[i-1] == '\r': - self.CRLF = True - else: - self.NL = True - elif data[i] == '\r': - if i < len(data)-1 and data[i+1] != '\n': - self.CR = True - - if "\r" in data: - self.atcr = data.endswith("\r") - data = data.replace("\r\n", "\n").replace("\r", "\n") - - return data - - def seek(self, offset, whence=0): - """Seeks based on knowledge that does not come from a tell() - may go to the wrong place, since the number of - characters seen may not match the number of characters - that are actually in the file (where \r\n is the - line separator). Arithmetics on the result - of a tell() that moves beyond a newline character may in the - same way give the wrong result. - """ - self.base.seek(offset, whence) - self.atcr = False - self.buf = "" - - def tell(self): - pos = self.base.tell() - if self.atcr: - # Must read the next byte to see if it's \n, - # because then we must report the next position. - assert not self.buf - self.buf = self.base.read(1) - pos += 1 - self.atcr = False - if self.buf == "\n": - self.buf = "" - return pos - len(self.buf) - -class TextOutputFilter(Stream): - - """Filtering output stream for universal newline translation.""" - - def __init__(self, base, linesep=os.linesep): - assert linesep in ["\n", "\r\n", "\r"] - self.base = base # must implement write, may implement seek, tell - self.linesep = linesep - self.close = base.close - - def write(self, data): - if self.linesep is not "\n" and "\n" in data: - data = data.replace("\n", self.linesep) - self.base.write(data) - - def seek(self, offset, whence=0): - self.base.seek(offset, whence) - - def tell(self): - return self.base.tell() - -class DecodingInputFilter(Stream): - - """Filtering input stream that decodes an encoded file.""" - - def __init__(self, base, encoding="utf8", errors="strict"): - self.base = base - self.encoding = encoding - self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close - - def read(self, n): - """Read *approximately* n bytes, then decode them. - - Under extreme circumstances, - the return length could be longer than n! - - Always return a unicode string. - - This does *not* translate newlines; - you can stack TextInputFilter. - """ - data = self.base.read(n) - try: - return data.decode(self.encoding, self.errors) - except ValueError: - # XXX Sigh. decode() doesn't handle incomplete strings well. - # Use the retry strategy from codecs.StreamReader. - for i in range(9): - more = self.base.read(1) - if not more: - raise - data += more - try: - return data.decode(self.encoding, self.errors) - except ValueError: - pass - raise - -class EncodingOutputFilter(Stream): - - """Filtering output stream that writes to an encoded file.""" - - def __init__(self, base, encoding="utf8", errors="strict"): - self.base = base - self.encoding = encoding - self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close - - def write(self, chars): - if isinstance(chars, str): - chars = unicode(chars) # Fail if it's not ASCII - self.base.write(chars.encode(self.encoding, self.errors)) Deleted: /pypy/dist/pypy/appspace/sre_parse.py ============================================================================== --- /pypy/dist/pypy/appspace/sre_parse.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,782 +0,0 @@ -# -# Secret Labs' Regular Expression Engine -# -# convert re-style regular expression to sre pattern -# -# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. -# -# See the sre.py file for information on usage and redistribution. -# - -"""Internal support module for sre""" - -# XXX: show string offset and offending character for all errors - -import sys - -from sre_constants import * - -SPECIAL_CHARS = ".\\[{()*+?^$|" -REPEAT_CHARS = "*+?{" - -DIGITS = tuple("0123456789") - -OCTDIGITS = tuple("01234567") -HEXDIGITS = tuple("0123456789abcdefABCDEF") - -WHITESPACE = tuple(" \t\n\r\v\f") - -ESCAPES = { - r"\a": (LITERAL, ord("\a")), - r"\b": (LITERAL, ord("\b")), - r"\f": (LITERAL, ord("\f")), - r"\n": (LITERAL, ord("\n")), - r"\r": (LITERAL, ord("\r")), - r"\t": (LITERAL, ord("\t")), - r"\v": (LITERAL, ord("\v")), - r"\\": (LITERAL, ord("\\")) -} - -CATEGORIES = { - r"\A": (AT, AT_BEGINNING_STRING), # start of string - r"\b": (AT, AT_BOUNDARY), - r"\B": (AT, AT_NON_BOUNDARY), - r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]), - r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]), - r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]), - r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]), - r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]), - r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]), - r"\Z": (AT, AT_END_STRING), # end of string -} - -FLAGS = { - # standard flags - "i": SRE_FLAG_IGNORECASE, - "L": SRE_FLAG_LOCALE, - "m": SRE_FLAG_MULTILINE, - "s": SRE_FLAG_DOTALL, - "x": SRE_FLAG_VERBOSE, - # extensions - "t": SRE_FLAG_TEMPLATE, - "u": SRE_FLAG_UNICODE, -} - -class Pattern: - # master pattern object. keeps track of global attributes - def __init__(self): - self.flags = 0 - self.open = [] - self.groups = 1 - self.groupdict = {} - def opengroup(self, name=None): - gid = self.groups - self.groups = gid + 1 - if name is not None: - ogid = self.groupdict.get(name, None) - if ogid is not None: - raise error, ("redefinition of group name %s as group %d; " - "was group %d" % (repr(name), gid, ogid)) - self.groupdict[name] = gid - self.open.append(gid) - return gid - def closegroup(self, gid): - self.open.remove(gid) - def checkgroup(self, gid): - return gid < self.groups and gid not in self.open - -class SubPattern: - # a subpattern, in intermediate form - def __init__(self, pattern, data=None): - self.pattern = pattern - if data is None: - data = [] - self.data = data - self.width = None - def dump(self, level=0): - nl = 1 - seqtypes = type(()), type([]) - for op, av in self.data: - print level*" " + op,; nl = 0 - if op == "in": - # member sublanguage - print; nl = 1 - for op, a in av: - print (level+1)*" " + op, a - elif op == "branch": - print; nl = 1 - i = 0 - for a in av[1]: - if i > 0: - print level*" " + "or" - a.dump(level+1); nl = 1 - i = i + 1 - elif type(av) in seqtypes: - for a in av: - if isinstance(a, SubPattern): - if not nl: print - a.dump(level+1); nl = 1 - else: - print a, ; nl = 0 - else: - print av, ; nl = 0 - if not nl: print - def __repr__(self): - return repr(self.data) - def __len__(self): - return len(self.data) - def __delitem__(self, index): - del self.data[index] - def __getitem__(self, index): - return self.data[index] - def __setitem__(self, index, code): - self.data[index] = code - def __getslice__(self, start, stop): - return SubPattern(self.pattern, self.data[start:stop]) - def insert(self, index, code): - self.data.insert(index, code) - def append(self, code): - self.data.append(code) - def getwidth(self): - # determine the width (min, max) for this subpattern - if self.width: - return self.width - lo = hi = 0L - UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY) - REPEATCODES = (MIN_REPEAT, MAX_REPEAT) - for op, av in self.data: - if op is BRANCH: - i = sys.maxint - j = 0 - for av in av[1]: - l, h = av.getwidth() - i = min(i, l) - j = max(j, h) - lo = lo + i - hi = hi + j - elif op is CALL: - i, j = av.getwidth() - lo = lo + i - hi = hi + j - elif op is SUBPATTERN: - i, j = av[1].getwidth() - lo = lo + i - hi = hi + j - elif op in REPEATCODES: - i, j = av[2].getwidth() - lo = lo + long(i) * av[0] - hi = hi + long(j) * av[1] - elif op in UNITCODES: - lo = lo + 1 - hi = hi + 1 - elif op == SUCCESS: - break - self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint)) - return self.width - -class Tokenizer: - def __init__(self, string): - self.string = string - self.index = 0 - self.__next() - def __next(self): - if self.index >= len(self.string): - self.next = None - return - char = self.string[self.index] - if char[0] == "\\": - try: - c = self.string[self.index + 1] - except IndexError: - raise error, "bogus escape (end of line)" - char = char + c - self.index = self.index + len(char) - self.next = char - def match(self, char, skip=1): - if char == self.next: - if skip: - self.__next() - return 1 - return 0 - def get(self): - this = self.next - self.__next() - return this - def tell(self): - return self.index, self.next - def seek(self, index): - self.index, self.next = index - -def isident(char): - return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_" - -def isdigit(char): - return "0" <= char <= "9" - -def isname(name): - # check that group name is a valid string - if not isident(name[0]): - return False - for char in name[1:]: - if not isident(char) and not isdigit(char): - return False - return True - -def _class_escape(source, escape): - # handle escape code inside character class - code = ESCAPES.get(escape) - if code: - return code - code = CATEGORIES.get(escape) - if code: - return code - try: - c = escape[1:2] - if c == "x": - # hexadecimal escape (exactly two digits) - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - escape = escape[2:] - if len(escape) != 2: - raise error, "bogus escape: %s" % repr("\\" + escape) - return LITERAL, int(escape, 16) & 0xff - elif c in OCTDIGITS: - # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 4: - escape = escape + source.get() - escape = escape[1:] - return LITERAL, int(escape, 8) & 0xff - elif c in DIGITS: - raise error, "bogus escape: %s" % repr(escape) - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _escape(source, escape, state): - # handle escape code in expression - code = CATEGORIES.get(escape) - if code: - return code - code = ESCAPES.get(escape) - if code: - return code - try: - c = escape[1:2] - if c == "x": - # hexadecimal escape - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - if len(escape) != 4: - raise ValueError - return LITERAL, int(escape[2:], 16) & 0xff - elif c == "0": - # octal escape - while source.next in OCTDIGITS and len(escape) < 4: - escape = escape + source.get() - return LITERAL, int(escape[1:], 8) & 0xff - elif c in DIGITS: - # octal escape *or* decimal group reference (sigh) - if source.next in DIGITS: - escape = escape + source.get() - if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and - source.next in OCTDIGITS): - # got three octal digits; this is an octal escape - escape = escape + source.get() - return LITERAL, int(escape[1:], 8) & 0xff - # not an octal escape, so this is a group reference - group = int(escape[1:]) - if group < state.groups: - if not state.checkgroup(group): - raise error, "cannot refer to open group" - return GROUPREF, group - raise ValueError - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _parse_sub(source, state, nested=1): - # parse an alternation: a|b|c - - items = [] - itemsappend = items.append - sourcematch = source.match - while 1: - itemsappend(_parse(source, state)) - if sourcematch("|"): - continue - if not nested: - break - if not source.next or sourcematch(")", 0): - break - else: - raise error, "pattern not properly closed" - - if len(items) == 1: - return items[0] - - subpattern = SubPattern(state) - subpatternappend = subpattern.append - - # check if all items share a common prefix - while 1: - prefix = None - for item in items: - if not item: - break - if prefix is None: - prefix = item[0] - elif item[0] != prefix: - break - else: - # all subitems start with a common "prefix". - # move it out of the branch - for item in items: - del item[0] - subpatternappend(prefix) - continue # check next one - break - - # check if the branch can be replaced by a character set - for item in items: - if len(item) != 1 or item[0][0] != LITERAL: - break - else: - # we can store this as a character set instead of a - # branch (the compiler may optimize this even more) - set = [] - setappend = set.append - for item in items: - setappend(item[0]) - subpatternappend((IN, set)) - return subpattern - - subpattern.append((BRANCH, (None, items))) - return subpattern - -def _parse_sub_cond(source, state, condgroup): - item_yes = _parse(source, state) - if source.match("|"): - item_no = _parse(source, state) - if source.match("|"): - raise error, "conditional backref with more than two branches" - else: - item_no = None - if source.next and not source.match(")", 0): - raise error, "pattern not properly closed" - subpattern = SubPattern(state) - subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no))) - return subpattern - -def _parse(source, state): - # parse a simple pattern - subpattern = SubPattern(state) - - # precompute constants into local variables - subpatternappend = subpattern.append - sourceget = source.get - sourcematch = source.match - _len = len - PATTERNENDERS = ("|", ")") - ASSERTCHARS = ("=", "!", "<") - LOOKBEHINDASSERTCHARS = ("=", "!") - REPEATCODES = (MIN_REPEAT, MAX_REPEAT) - - while 1: - - if source.next in PATTERNENDERS: - break # end of subpattern - this = sourceget() - if this is None: - break # end of pattern - - if state.flags & SRE_FLAG_VERBOSE: - # skip whitespace and comments - if this in WHITESPACE: - continue - if this == "#": - while 1: - this = sourceget() - if this in (None, "\n"): - break - continue - - if this and this[0] not in SPECIAL_CHARS: - subpatternappend((LITERAL, ord(this))) - - elif this == "[": - # character set - set = [] - setappend = set.append -## if sourcematch(":"): -## pass # handle character classes - if sourcematch("^"): - setappend((NEGATE, None)) - # check remaining characters - start = set[:] - while 1: - this = sourceget() - if this == "]" and set != start: - break - elif this and this[0] == "\\": - code1 = _class_escape(source, this) - elif this: - code1 = LITERAL, ord(this) - else: - raise error, "unexpected end of regular expression" - if sourcematch("-"): - # potential range - this = sourceget() - if this == "]": - if code1[0] is IN: - code1 = code1[1][0] - setappend(code1) - setappend((LITERAL, ord("-"))) - break - elif this: - if this[0] == "\\": - code2 = _class_escape(source, this) - else: - code2 = LITERAL, ord(this) - if code1[0] != LITERAL or code2[0] != LITERAL: - raise error, "bad character range" - lo = code1[1] - hi = code2[1] - if hi < lo: - raise error, "bad character range" - setappend((RANGE, (lo, hi))) - else: - raise error, "unexpected end of regular expression" - else: - if code1[0] is IN: - code1 = code1[1][0] - setappend(code1) - - # XXX: should move set optimization to compiler! - if _len(set)==1 and set[0][0] is LITERAL: - subpatternappend(set[0]) # optimization - elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: - subpatternappend((NOT_LITERAL, set[1][1])) # optimization - else: - # XXX: should add charmap optimization here - subpatternappend((IN, set)) - - elif this and this[0] in REPEAT_CHARS: - # repeat previous item - if this == "?": - min, max = 0, 1 - elif this == "*": - min, max = 0, MAXREPEAT - - elif this == "+": - min, max = 1, MAXREPEAT - elif this == "{": - here = source.tell() - min, max = 0, MAXREPEAT - lo = hi = "" - while source.next in DIGITS: - lo = lo + source.get() - if sourcematch(","): - while source.next in DIGITS: - hi = hi + sourceget() - else: - hi = lo - if not sourcematch("}"): - subpatternappend((LITERAL, ord(this))) - source.seek(here) - continue - if lo: - min = int(lo) - if hi: - max = int(hi) - if max < min: - raise error, "bad repeat interval" - else: - raise error, "not supported" - # figure out which item to repeat - if subpattern: - item = subpattern[-1:] - else: - item = None - if not item or (_len(item) == 1 and item[0][0] == AT): - raise error, "nothing to repeat" - if item[0][0] in REPEATCODES: - raise error, "multiple repeat" - if sourcematch("?"): - subpattern[-1] = (MIN_REPEAT, (min, max, item)) - else: - subpattern[-1] = (MAX_REPEAT, (min, max, item)) - - elif this == ".": - subpatternappend((ANY, None)) - - elif this == "(": - group = 1 - name = None - condgroup = None - if sourcematch("?"): - group = 0 - # options - if sourcematch("P"): - # python extensions - if sourcematch("<"): - # named group: skip forward to end of name - name = "" - while 1: - char = sourceget() - if char is None: - raise error, "unterminated name" - if char == ">": - break - name = name + char - group = 1 - if not isname(name): - raise error, "bad character in group name" - elif sourcematch("="): - # named backreference - name = "" - while 1: - char = sourceget() - if char is None: - raise error, "unterminated name" - if char == ")": - break - name = name + char - if not isname(name): - raise error, "bad character in group name" - gid = state.groupdict.get(name) - if gid is None: - raise error, "unknown group name" - subpatternappend((GROUPREF, gid)) - continue - else: - char = sourceget() - if char is None: - raise error, "unexpected end of pattern" - raise error, "unknown specifier: ?P%s" % char - elif sourcematch(":"): - # non-capturing group - group = 2 - elif sourcematch("#"): - # comment - while 1: - if source.next is None or source.next == ")": - break - sourceget() - if not sourcematch(")"): - raise error, "unbalanced parenthesis" - continue - elif source.next in ASSERTCHARS: - # lookahead assertions - char = sourceget() - dir = 1 - if char == "<": - if source.next not in LOOKBEHINDASSERTCHARS: - raise error, "syntax error" - dir = -1 # lookbehind - char = sourceget() - p = _parse_sub(source, state) - if not sourcematch(")"): - raise error, "unbalanced parenthesis" - if char == "=": - subpatternappend((ASSERT, (dir, p))) - else: - subpatternappend((ASSERT_NOT, (dir, p))) - continue - elif sourcematch("("): - # conditional backreference group - condname = "" - while 1: - char = sourceget() - if char is None: - raise error, "unterminated name" - if char == ")": - break - condname = condname + char - group = 2 - if isname(condname): - condgroup = state.groupdict.get(condname) - if condgroup is None: - raise error, "unknown group name" - else: - try: - condgroup = int(condname) - except ValueError: - raise error, "bad character in group name" - else: - # flags - if not source.next in FLAGS: - raise error, "unexpected end of pattern" - while source.next in FLAGS: - state.flags = state.flags | FLAGS[sourceget()] - if group: - # parse group contents - if group == 2: - # anonymous group - group = None - else: - group = state.opengroup(name) - if condgroup: - p = _parse_sub_cond(source, state, condgroup) - else: - p = _parse_sub(source, state) - if not sourcematch(")"): - raise error, "unbalanced parenthesis" - if group is not None: - state.closegroup(group) - subpatternappend((SUBPATTERN, (group, p))) - else: - while 1: - char = sourceget() - if char is None: - raise error, "unexpected end of pattern" - if char == ")": - break - raise error, "unknown extension" - - elif this == "^": - subpatternappend((AT, AT_BEGINNING)) - - elif this == "$": - subpattern.append((AT, AT_END)) - - elif this and this[0] == "\\": - code = _escape(source, this, state) - subpatternappend(code) - - else: - raise error, "parser error" - - return subpattern - -def parse(str, flags=0, pattern=None): - # parse 're' pattern into list of (opcode, argument) tuples - - source = Tokenizer(str) - - if pattern is None: - pattern = Pattern() - pattern.flags = flags - pattern.str = str - - p = _parse_sub(source, pattern, 0) - - tail = source.get() - if tail == ")": - raise error, "unbalanced parenthesis" - elif tail: - raise error, "bogus characters at end of regular expression" - - if flags & SRE_FLAG_DEBUG: - p.dump() - - if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: - # the VERBOSE flag was switched on inside the pattern. to be - # on the safe side, we'll parse the whole thing again... - return parse(str, p.pattern.flags) - - return p - -def parse_template(source, pattern): - # parse 're' replacement string into list of literals and - # group references - s = Tokenizer(source) - sget = s.get - p = [] - a = p.append - def literal(literal, p=p, pappend=a): - if p and p[-1][0] is LITERAL: - p[-1] = LITERAL, p[-1][1] + literal - else: - pappend((LITERAL, literal)) - sep = source[:0] - if type(sep) is type(""): - makechar = chr - else: - makechar = unichr - while 1: - this = sget() - if this is None: - break # end of replacement string - if this and this[0] == "\\": - # group - c = this[1:2] - if c == "g": - name = "" - if s.match("<"): - while 1: - char = sget() - if char is None: - raise error, "unterminated group name" - if char == ">": - break - name = name + char - if not name: - raise error, "bad group name" - try: - index = int(name) - if index < 0: - raise error, "negative group number" - except ValueError: - if not isname(name): - raise error, "bad character in group name" - try: - index = pattern.groupindex[name] - except KeyError: - raise IndexError, "unknown group name" - a((MARK, index)) - elif c == "0": - if s.next in OCTDIGITS: - this = this + sget() - if s.next in OCTDIGITS: - this = this + sget() - literal(makechar(int(this[1:], 8) & 0xff)) - elif c in DIGITS: - isoctal = False - if s.next in DIGITS: - this = this + sget() - if (c in OCTDIGITS and this[2] in OCTDIGITS and - s.next in OCTDIGITS): - this = this + sget() - isoctal = True - literal(makechar(int(this[1:], 8) & 0xff)) - if not isoctal: - a((MARK, int(this[1:]))) - else: - try: - this = makechar(ESCAPES[this][1]) - except KeyError: - pass - literal(this) - else: - literal(this) - # convert template to groups and literals lists - i = 0 - groups = [] - groupsappend = groups.append - literals = [None] * len(p) - for c, s in p: - if c is MARK: - groupsappend((i, s)) - # literal[i] is already None - else: - literals[i] = s - i = i + 1 - return groups, literals - -def expand_template(template, match): - g = match.group - sep = match.string[:0] - groups, literals = template - literals = literals[:] - try: - for index, group in groups: - literals[index] = s = g(group) - if s is None: - raise error, "unmatched group" - except IndexError: - raise error, "invalid group reference" - return sep.join(literals) Deleted: /pypy/dist/pypy/appspace/struct.py ============================================================================== --- /pypy/dist/pypy/appspace/struct.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,346 +0,0 @@ -import math,sys - -"""Functions to convert between Python values and C structs. -Python strings are used to hold the data representing the C struct -and also as format strings to describe the layout of data in the C struct. - -The optional first format char indicates byte order, size and alignment: - @: native order, size & alignment (default) - =: native order, std. size & alignment - <: little-endian, std. size & alignment - >: big-endian, std. size & alignment - !: same as > - -The remaining chars indicate types of args and must match exactly; -these can be preceded by a decimal repeat count: - x: pad byte (no data); - c:char; - b:signed byte; - B:unsigned byte; - h:short; - H:unsigned short; - i:int; - I:unsigned int; - l:long; - L:unsigned long; - f:float; - d:double. -Special cases (preceding decimal count indicates length): - s:string (array of char); p: pascal string (with count byte). -Special case (only available in native format): - P:an integer type that is wide enough to hold a pointer. -Special case (not in native mode unless 'long long' in platform C): - q:long long; - Q:unsigned long long -Whitespace between formats is ignored. - -The variable struct.error is an exception raised on errors.""" - -# TODO: XXX Find a way to get information on native sizes and alignments -class StructError(Exception): - pass -error = StructError -def unpack_int(data,index,size,le): - bytes = [ord(b) for b in data[index:index+size]] - if le == 'little': - bytes.reverse() - number = 0L - for b in bytes: - number = number << 8 | b - return int(number) - -def unpack_signed_int(data,index,size,le): - number = unpack_int(data,index,size,le) - max = 2**(size*8) - if number > 2**(size*8 - 1) - 1: - number = int(-1*(max - number)) - return number - -def unpack_float(data,index,size,le): - bytes = [ord(b) for b in data[index:index+size]] - if len(bytes) != size: - raise StructError,"Not enough data to unpack" - if le == 'big': - bytes.reverse() - if size == 4: - bias = 127 - exp = 8 - prec = 23 - else: - bias = 1023 - exp = 11 - prec = 52 -# print bytes,size,index,len(data),data - mantissa = long(bytes[size-2] & (2**(15-exp)-1)) -# print mantissa - for b in bytes[size-3::-1]: - mantissa = mantissa << 8 | b -# print mantissa - mantissa = 1 + (1.0*mantissa)/(2**(prec)) - mantissa /= 2 -# print mantissa - e = (bytes[-1] & 0x7f) << (exp - 7) - e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1) - e -= bias - e += 1 - sign = bytes[-1] & 0x80 - number = math.ldexp(mantissa,e) -# print number,index,mantissa,e,bytes#,data - if sign : number *= -1 - return number - -def unpack_char(data,index,size,le): - return data[index:index+size] - -def pack_int(number,size,le): - x=number - res=[] - for i in range(size): - res.append(chr(x&0xff)) - x >>= 8 - if le == 'big': - res.reverse() - return ''.join(res) - -def pack_signed_int(number,size,le): - if type(number) not in [int,long]: - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" - if number > 2**(8*size-1)-1 or number < -1*2**(8*size-1): - raise OverflowError,"Number:%i to large to convert" % number - return pack_int(number,size,le) - -def pack_unsigned_int(number,size,le): - if type(number) not in [int,long]: - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" - if number < 0: - raise TypeError,"can't convert negative long to unsigned" - if number > 2**(8*size)-1: - raise OverflowError,"Number:%i to large to convert" % number - return pack_int(number,size,le) - -def pack_char(char,size,le): -# print char - return str(char) - -def sane_float(man,e): - # TODO: XXX Implement checks for floats - return True - -def pack_float(number,size,le): - - if number < 0: - sign=1 - number *= -1 - else: - sign =0 - if size == 4: - bias = 127 - exp = 8 - prec = 23 - else: - bias = 1023 - exp = 11 - prec = 52 - - man,e = math.frexp(number) - if 0.5 <= man and man < 1.0: - man *= 2 - e -= 1 - if sane_float(man,e): - man -= 1 - e += bias - mantissa = int(2**prec *(man) +0.5) - res=[] - if mantissa >> prec : - mantissa = 0 - e += 1 - - for i in range(size-2): - res += [ mantissa & 0xff] - mantissa >>= 8 - res += [ (mantissa & (2**(15-exp)-1)) | ((e & (2**(exp-7)-1))<<(15-exp))] - res += [sign << 7 | e >> (exp - 7)] - if le == 'big': - res.reverse() - return ''.join([chr(x) for x in res]) - # TODO: What todo with insane floats/doubles. handle in sanefloat? - -big_endian_format = { - 'x':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'b':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'B':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'c':{ 'size' : 1, 'alignment' : 0, 'pack' : pack_char, 'unpack' : unpack_char}, - 's':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'p':{ 'size' : 1, 'alignment' : 0, 'pack' : None, 'unpack' : None}, - 'h':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'H':{ 'size' : 2, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'i':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'I':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'l':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'L':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_signed_int, 'unpack' : unpack_signed_int}, - 'Q':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_unsigned_int, 'unpack' : unpack_int}, - 'f':{ 'size' : 4, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, - 'd':{ 'size' : 8, 'alignment' : 0, 'pack' : pack_float, 'unpack' : unpack_float}, - } -default = big_endian_format -formatmode={ '<' : (default, 'little'), - '>' : (default, 'big'), - '!' : (default, 'big'), - '=' : (default, sys.byteorder), - '@' : (default, sys.byteorder) - } - -def getmode(fmt): - try: - formatdef,endianness = formatmode[fmt[0]] - index = 1 - except KeyError: - formatdef,endianness = formatmode['@'] - index = 0 - return formatdef,endianness,index -def getNum(fmt,i): - num=None - cur = fmt[i] - while ('0'<= cur ) and ( cur <= '9'): - if num == None: - num = int(cur) - else: - num = 10*num + int(cur) - i += 1 - cur = fmt[i] - return num,i - -def calcsize(fmt): - """calcsize(fmt) -> int - Return size of C struct described by format string fmt. - See struct.__doc__ for more on format strings.""" - - formatdef,endianness,i = getmode(fmt) - num = 0 - result = 0 - while i string - Return string containing values v1, v2, ... packed according to fmt. - See struct.__doc__ for more on format strings.""" - formatdef,endianness,i = getmode(fmt) - args = list(args) - n_args = len(args) - result = [] - while i=0: - result += [args[0][:num] + '\0'*padding] - else: - result += [args[0][:num]] - args.pop() - else: - raise StructError,"arg for string format not a string" - elif cur == 'p': - if type(args[0]) == str: - padding = num - len(args[0]) - 1 - - if padding > 0: - result += [chr(len(args[0])) + args[0][:num-1] + '\0'*padding] - else: - if num<255: - result += [chr(num-1) + args[0][:num-1]] - else: - result += [chr(255) + args[0][:num-1]] - args.pop() - else: - raise StructError,"arg for string format not a string" - - else: - if len(args) == 0: - raise StructError,"insufficient arguments to pack" - for var in args[:num]: - result += [format['pack'](var,format['size'],endianness)] - args=args[num:] - num = None - i += 1 - if len(args) != 0: - raise StructError,"too many arguments for pack format" - return ''.join(result) - -def unpack(fmt,data): - """unpack(fmt, string) -> (v1, v2, ...) - Unpack the string, containing packed C structure data, according - to fmt. Requires len(string)==calcsize(fmt). - See struct.__doc__ for more on format strings.""" - formatdef,endianness,i = getmode(fmt) -# print fmt,data - j = 0 - num = 0 - result = [] - length= calcsize(fmt) - if length != len (data): - raise StructError,"unpack str size does not match format" - while i= num: - n = num-1 - result.append(data[j+1:j+n+1]) - j += num - i += 1 - else: - for n in range(num): - result += [format['unpack'](data,j,format['size'],endianness)] - j += format['size'] - i += 1 - - return tuple(result) - -if __name__ == '__main__': - print pack_float(1.23,4,'little') - import struct - print (struct.pack('f',1.23), pack('f',1.23)) - print unpack('f',pack('f',1.23)) Modified: pypy/dist/pypy/appspace/test/conftest.py ============================================================================== --- pypy/dist/pypy/appspace/test/conftest.py (original) +++ pypy/dist/pypy/appspace/test/conftest.py Thu Jan 27 23:35:29 2005 @@ -6,22 +6,4 @@ class Directory(py.test.collect.Directory): def __iter__(self): - for path in self.fspath.listdir(): - if path.check(fnmatch='cpy_test_*.py', file=1): - continue - #XXX yield RunFileAtAppLevelItem(py.path.extpy(path)) - elif self.fil(path): - if path.basename in ('test_cmathmodule.py', - 'builtin_functions_test.py', - 'test_complexobject.py',): - continue - yield self.Module(path) - elif self.rec(path): - yield self.Directory(path) - -class RunFileAtAppLevelItem(PyPyItem): - def run(self, driver): - space = getobjspace() - source = self.extpy.root.read() - #self.execute_appex(space, run_string, source, str(self.extpy.root), space) - run_string(source, str(self.extpy.root), space) + return iter([]) Modified: pypy/dist/pypy/appspace/test/test_exceptions.py ============================================================================== --- pypy/dist/pypy/appspace/test/test_exceptions.py (original) +++ pypy/dist/pypy/appspace/test/test_exceptions.py Thu Jan 27 23:35:29 2005 @@ -1,5 +1,5 @@ import autopath -def app_test_import(): +def failing_app_test_import(): import exceptions assert exceptions.SyntaxError is SyntaxError Deleted: /pypy/dist/pypy/appspace/test/test_sio.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_sio.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,740 +0,0 @@ -"""Unit tests for sio (new standard I/O).""" - -import os -import time -from pypy.tool.udir import udir - -from pypy.appspace import sio - -class TestSource(object): - - def __init__(self, packets): - for x in packets: - assert x - self.orig_packets = list(packets) - self.packets = list(packets) - self.pos = 0 - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 1: - offset += self.pos - elif whence == 2: - for packet in self.orig_packets: - offset += len(packet) - else: - assert whence == 0 - self.packets = list(self.orig_packets) - self.pos = 0 - while self.pos < offset: - data = self.read(offset - self.pos) - if not data: - break - assert self.pos == offset - - def read(self, n): - try: - data = self.packets.pop(0) - except IndexError: - return "" - if len(data) > n: - data, rest = data[:n], data[n:] - self.packets.insert(0, rest) - self.pos += len(data) - return data - - def close(self): - pass - -class TestReader(object): - - def __init__(self, packets): - for x in packets: - assert x - self.orig_packets = list(packets) - self.packets = list(packets) - self.pos = 0 - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 1: - offset += self.pos - elif whence == 2: - for packet in self.orig_packets: - offset += len(packet) - else: - assert whence == 0 - self.packets = list(self.orig_packets) - self.pos = 0 - while self.pos < offset: - data = self.read(offset - self.pos) - if not data: - break - assert self.pos == offset - - def read(self, n): - try: - data = self.packets.pop(0) - except IndexError: - return "" - if len(data) > n: - data, rest = data[:n], data[n:] - self.packets.insert(0, rest) - self.pos += len(data) - return data - - def close(self): - pass - - def flush(self): - pass -class TestWriter(object): - - def __init__(self, data=''): - self.buf = data - self.pos = 0 - - def write(self, data): - if self.pos >= len(self.buf): - self.buf += "\0" * (self.pos - len(self.buf)) + data - self.pos = len(self.buf) - else: - self.buf = (self.buf[:self.pos] + data + - self.buf[self.pos + len(data):]) - self.pos += len(data) - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 0: - pass - elif whence == 1: - offset += self.pos - elif whence == 2: - offset += len(self.buf) - else: - raise ValueError, "whence should be 0, 1 or 2" - if offset < 0: - offset = 0 - self.pos = offset - - def close(self): - pass - - def truncate(self, size=None): - if size is None: - size = self.pos - if size <= len(self.buf): - self.buf = self.buf[:size] - else: - self.buf += '\0' * (size - len(self.buf)) - - def flush(self): - pass - -class TestReaderWriter(TestWriter): - - def read(self, n=-1): - if n < 1: - result = self.buf[self.pos: ] - self.pos = len(self.buf) - else: - if self.pos + n > len(self.buf): - n = len(self.buf) - self.pos - result = self.buf[self.pos: self.pos+n] - self.pos += n - return result - -class TestBufferingInputStreamTests: - - packets = ["a", "b", "\n", "def", "\nxy\npq\nuv", "wx"] - lines = ["ab\n", "def\n", "xy\n", "pq\n", "uvwx"] - - def makeStream(self, tell=False, seek=False, bufsize=None): - base = TestSource(self.packets) - if not tell: - base.tell = None - if not seek: - base.seek = None - return sio.BufferingInputStream(base, bufsize) - - def test_readline(self): - file = self.makeStream() - assert list(iter(file.readline, "")) == self.lines - - def test_readlines(self): - # This also tests next() and __iter__() - file = self.makeStream() - assert file.readlines() == self.lines - - def test_readlines_small_bufsize(self): - file = self.makeStream(bufsize=1) - assert list(file) == self.lines - - def test_readall(self): - file = self.makeStream() - assert file.readall() == "".join(self.lines) - - def test_readall_small_bufsize(self): - file = self.makeStream(bufsize=1) - assert file.readall() == "".join(self.lines) - - def test_readall_after_readline(self): - file = self.makeStream() - assert file.readline() == self.lines[0] - assert file.readline() == self.lines[1] - assert file.readall() == "".join(self.lines[2:]) - - def test_read_1_after_readline(self): - file = self.makeStream() - assert file.readline() == "ab\n" - assert file.readline() == "def\n" - blocks = [] - while 1: - block = file.read(1) - if not block: - break - blocks.append(block) - assert file.read(0) == "" - assert blocks == list("".join(self.lines)[7:]) - - def test_read_1(self): - file = self.makeStream() - blocks = [] - while 1: - block = file.read(1) - if not block: - break - blocks.append(block) - assert file.read(0) == "" - assert blocks == list("".join(self.lines)) - - def test_read_2(self): - file = self.makeStream() - blocks = [] - while 1: - block = file.read(2) - if not block: - break - blocks.append(block) - assert file.read(0) == "" - assert blocks == ["ab", "\nd", "ef", "\nx", "y\n", "pq", - "\nu", "vw", "x"] - - def test_read_4(self): - file = self.makeStream() - blocks = [] - while 1: - block = file.read(4) - if not block: - break - blocks.append(block) - assert file.read(0) == "" - assert blocks == ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"] - - def test_read_4_after_readline(self): - file = self.makeStream() - assert file.readline() == "ab\n" - assert file.readline() == "def\n" - blocks = [file.read(4)] - while 1: - block = file.read(4) - if not block: - break - blocks.append(block) - assert file.read(0) == "" - assert blocks == ["xy\np", "q\nuv", "wx"] - - def test_read_4_small_bufsize(self): - file = self.makeStream(bufsize=1) - blocks = [] - while 1: - block = file.read(4) - if not block: - break - blocks.append(block) - assert blocks == ["ab\nd", "ef\nx", "y\npq", "\nuvw", "x"] - - def test_tell_1(self): - file = self.makeStream(tell=True) - pos = 0 - while 1: - assert file.tell() == pos - n = len(file.read(1)) - if not n: - break - pos += n - - def test_tell_1_after_readline(self): - file = self.makeStream(tell=True) - pos = 0 - pos += len(file.readline()) - assert file.tell() == pos - pos += len(file.readline()) - assert file.tell() == pos - while 1: - assert file.tell() == pos - n = len(file.read(1)) - if not n: - break - pos += n - - def test_tell_2(self): - file = self.makeStream(tell=True) - pos = 0 - while 1: - assert file.tell() == pos - n = len(file.read(2)) - if not n: - break - pos += n - - def test_tell_4(self): - file = self.makeStream(tell=True) - pos = 0 - while 1: - assert file.tell() == pos - n = len(file.read(4)) - if not n: - break - pos += n - - def test_tell_readline(self): - file = self.makeStream(tell=True) - pos = 0 - while 1: - assert file.tell() == pos - n = len(file.readline()) - if not n: - break - pos += n - - def test_seek(self): - file = self.makeStream(tell=True, seek=True) - all = file.readall() - end = len(all) - for readto in range(0, end+1): - for seekto in range(0, end+1): - for whence in 0, 1, 2: - file.seek(0) - assert file.tell() == 0 - head = file.read(readto) - assert head == all[:readto] - if whence == 1: - offset = seekto - readto - elif whence == 2: - offset = seekto - end - else: - offset = seekto - file.seek(offset, whence) - here = file.tell() - assert here == seekto - rest = file.readall() - assert rest == all[seekto:] - - def test_seek_noseek(self): - file = self.makeStream() - all = file.readall() - end = len(all) - for readto in range(0, end+1): - for seekto in range(readto, end+1): - for whence in 1, 2: - file = self.makeStream() - head = file.read(readto) - assert head == all[:readto] - if whence == 1: - offset = seekto - readto - elif whence == 2: - offset = seekto - end - file.seek(offset, whence) - rest = file.readall() - assert rest == all[seekto:] - -class TestBufferingOutputStream: - - def test_write(self): - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.write("123") - assert base.buf == "" - assert filter.tell() == 3 - filter.write("456") - assert base.buf == "1234" - filter.write("789ABCDEF") - assert base.buf == "123456789ABC" - filter.write("0123") - assert base.buf == "123456789ABCDEF0" - assert filter.tell() == 19 - filter.close() - assert base.buf == "123456789ABCDEF0123" - - def test_write_seek(self): - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.write("x"*6) - filter.seek(3) - filter.write("y"*2) - filter.close() - assert base.buf == "x"*3 + "y"*2 + "x"*1 - - def test_write_seek_beyond_end(self): - "Linux behaviour. May be different on other platforms." - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.seek(3) - filter.write("y"*2) - filter.close() - assert base.buf == "\0"*3 + "y"*2 - - def test_truncate(self): - "Linux behaviour. May be different on other platforms." - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.write('x') - filter.truncate(4) - filter.write('y') - filter.close() - assert base.buf == 'xy' + '\0' * 2 - - def test_truncate2(self): - "Linux behaviour. May be different on other platforms." - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.write('12345678') - filter.truncate(4) - filter.write('y') - filter.close() - assert base.buf == '1234' + '\0' * 4 + 'y' - -class TestLineBufferingOutputStreamTests: - - def test_write(self): - base = TestWriter() - filter = sio.LineBufferingOutputStream(base) - filter.bufsize = 4 # More handy for testing than the default - filter.write("123") - assert base.buf == "" - assert filter.tell() == 3 - filter.write("456") - assert base.buf == "1234" - filter.write("789ABCDEF\n") - assert base.buf == "123456789ABCDEF\n" - filter.write("0123") - assert base.buf == "123456789ABCDEF\n0123" - assert filter.tell() == 20 - filter.close() - assert base.buf == "123456789ABCDEF\n0123" - - def xtest_write_seek(self): - base = TestWriter() - filter = sio.BufferingOutputStream(base, 4) - filter.write("x"*6) - filter.seek(3) - filter.write("y"*2) - filter.close() - assert base.buf == "x"*3 + "y"*2 + "x"*1 - -class TestBufferingInputOutputStreamTests: - - def test_write(self): - base = TestReaderWriter() - filter = sio.BufferingInputOutputStream(base, 4) - filter.write("123456789") - assert base.buf == "12345678" - s = filter.read() - assert base.buf == "123456789" - filter.write("01234") - assert base.buf == "1234567890123" - filter.seek(4,0) - assert base.buf == "12345678901234" - assert filter.read(3) == "567" - filter.write('x') - filter.flush() - assert base.buf == "1234567x901234" - - def test_write_seek_beyond_end(self): - "Linux behaviour. May be different on other platforms." - base = TestReaderWriter() - filter = sio.BufferingInputOutputStream(base, 4) - filter.seek(3) - filter.write("y"*2) - filter.close() - assert base.buf == "\0"*3 + "y"*2 - -class TestCRLFFilter: - - def test_filter(self): - packets = ["abc\ndef\rghi\r\nxyz\r", "123\r", "\n456"] - expected = ["abc\ndef\nghi\nxyz\n", "123\n", "456"] - crlf = sio.CRLFFilter(TestSource(packets)) - blocks = [] - while 1: - block = crlf.read(100) - if not block: - break - blocks.append(block) - assert blocks == expected - -class TestMMapFile(TestBufferingInputStreamTests): - tfn = None - Counter = 0 - - def teardown_method(self, method): - tfn = self.tfn - if tfn: - self.tfn = None - try: - os.remove(tfn) - except os.error, msg: - print "can't remove %s: %s" % (tfn, msg) - - def makeStream(self, tell=None, seek=None, bufsize=None, mode="r"): - self.teardown_method(None) # for tests calling makeStream() several time - self.tfn = str(udir.join('sio%03d' % TestMMapFile.Counter)) - TestMMapFile.Counter += 1 - f = open(self.tfn, "wb") - f.writelines(self.packets) - f.close() - return sio.MMapFile(self.tfn, mode) - - def test_write(self): - if os.name == "posix": - return # write() does't work on Unix :-( - file = self.makeStream(mode="w") - file.write("BooHoo\n") - file.write("Barf\n") - file.writelines(["a\n", "b\n", "c\n"]) - assert file.tell() == len("BooHoo\nBarf\na\nb\nc\n") - file.seek(0) - assert file.read() == "BooHoo\nBarf\na\nb\nc\n" - file.seek(0) - assert file.readlines() == ( - ["BooHoo\n", "Barf\n", "a\n", "b\n", "c\n"]) - assert file.tell() == len("BooHoo\nBarf\na\nb\nc\n") - -class TestTextInputFilter: - - packets = [ - "foo\r", - "bar\r", - "\nfoo\r\n", - "abc\ndef\rghi\r\nxyz", - "\nuvw\npqr\r", - "\n", - "abc\n", - ] - expected = [ - ("foo\n", 4), - ("bar\n", 9), - ("foo\n", 14), - ("abc\ndef\nghi\nxyz", 30), - ("\nuvw\npqr\n", 40), - ("abc\n", 44), - ("", 44), - ("", 44), - ] - - expected_with_tell = [ - ("foo\n", 4), - ("b", 5), - ("ar\n", 9), - ("foo\n", 14), - ("abc\ndef\nghi\nxyz", 30), - ("\nuvw\npqr\n", 40), - ("abc\n", 44), - ("", 44), - ("", 44), - ] - - expected_newlines = [ - (["abcd"], [None]), - (["abcd\n"], ["\n"]), - (["abcd\r\n"],["\r\n"]), - (["abcd\r"],[None]), # wrong, but requires precognition to fix - (["abcd\r", "\nefgh"], [None, "\r\n"]), - (["abcd", "\nefg\r", "hij", "k\r\n"], [None, "\n", ("\r", "\n"), - ("\r", "\n", "\r\n")]), - (["abcd", "\refg\r", "\nhij", "k\n"], [None, "\r", ("\r", "\r\n"), - ("\r", "\n", "\r\n")]) - ] - - def test_read(self): - base = TestReader(self.packets) - filter = sio.TextInputFilter(base) - for data, pos in self.expected: - assert filter.read(100) == data - - def test_read_tell(self): - base = TestReader(self.packets) - filter = sio.TextInputFilter(base) - for data, pos in self.expected_with_tell: - assert filter.read(100) == data - assert filter.tell() == pos - assert filter.tell() == pos # Repeat the tell() ! - - def test_seek(self): - base = TestReader(self.packets) - filter = sio.TextInputFilter(base) - sofar = "" - pairs = [] - while True: - pairs.append((sofar, filter.tell())) - c = filter.read(1) - if not c: - break - assert len(c) == 1 - sofar += c - all = sofar - for i in range(len(pairs)): - sofar, pos = pairs[i] - filter.seek(pos) - assert filter.tell() == pos - assert filter.tell() == pos - bufs = [sofar] - while True: - data = filter.read(100) - if not data: - assert filter.read(100) == "" - break - bufs.append(data) - assert "".join(bufs) == all - - def test_newlines_attribute(self): - - for packets, expected in self.expected_newlines: - base = TestReader(packets) - filter = sio.TextInputFilter(base) - for e in expected: - filter.read(100) - assert filter.newlines == e - -class TestTextOutputFilter: - - def test_write_nl(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\n") - filter.write("abc") - filter.write("def\npqr\nuvw") - filter.write("\n123\n") - assert base.buf == "abcdef\npqr\nuvw\n123\n" - - def test_write_cr(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\r") - filter.write("abc") - filter.write("def\npqr\nuvw") - filter.write("\n123\n") - assert base.buf == "abcdef\rpqr\ruvw\r123\r" - - def test_write_crnl(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\r\n") - filter.write("abc") - filter.write("def\npqr\nuvw") - filter.write("\n123\n") - assert base.buf == "abcdef\r\npqr\r\nuvw\r\n123\r\n" - - def test_write_tell_nl(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\n") - filter.write("xxx") - assert filter.tell() == 3 - filter.write("\nabc\n") - assert filter.tell() == 8 - - def test_write_tell_cr(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\r") - filter.write("xxx") - assert filter.tell() == 3 - filter.write("\nabc\n") - assert filter.tell() == 8 - - def test_write_tell_crnl(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\r\n") - filter.write("xxx") - assert filter.tell() == 3 - filter.write("\nabc\n") - assert filter.tell() == 10 - - def test_write_seek(self): - base = TestWriter() - filter = sio.TextOutputFilter(base, linesep="\n") - filter.write("x"*100) - filter.seek(50) - filter.write("y"*10) - assert base.buf == "x"*50 + "y"*10 + "x"*40 - -class TestDecodingInputFilter: - - def test_read(self): - chars = u"abc\xff\u1234\u4321\x80xyz" - data = chars.encode("utf8") - base = TestReader([data]) - filter = sio.DecodingInputFilter(base) - bufs = [] - for n in range(1, 11): - while 1: - c = filter.read(n) - assert type(c) == unicode - if not c: - break - bufs.append(c) - assert u"".join(bufs) == chars - -class TestEncodingOutputFilterTests: - - def test_write(self): - chars = u"abc\xff\u1234\u4321\x80xyz" - data = chars.encode("utf8") - for n in range(1, 11): - base = TestWriter() - filter = sio.EncodingOutputFilter(base) - pos = 0 - while 1: - c = chars[pos:pos+n] - if not c: - break - pos += len(c) - filter.write(c) - assert base.buf == data - -# Speed test - -FN = "BIG" - -def timeit(fn=FN, opener=sio.MMapFile): - f = opener(fn, "r") - lines = bytes = 0 - t0 = time.clock() - for line in f: - lines += 1 - bytes += len(line) - t1 = time.clock() - print "%d lines (%d bytes) in %.3f seconds for %s" % ( - lines, bytes, t1-t0, opener.__name__) - -def speed_main(): - def diskopen(fn, mode): - base = sio.DiskFile(fn, mode) - return sio.BufferingInputStream(base) - timeit(opener=diskopen) - timeit(opener=sio.MMapFile) - timeit(opener=open) - -# Functional test - -def functional_main(): - f = sio.DiskFile("sio.py") - f = sio.DecodingInputFilter(f) - f = sio.TextInputFilter(f) - f = sio.BufferingInputStream(f) - for i in range(10): - print repr(f.readline()) - Deleted: /pypy/dist/pypy/appspace/traceback.py ============================================================================== --- /pypy/dist/pypy/appspace/traceback.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,286 +0,0 @@ -"""Extract, format and print information about Python stack traces.""" - -import linecache -import sys -import types - -__all__ = ['extract_stack', 'extract_tb', 'format_exception', - 'format_exception_only', 'format_list', 'format_stack', - 'format_tb', 'print_exc', 'print_exception', 'print_last', - 'print_stack', 'print_tb', 'tb_lineno'] - -def _print(file, str='', terminator='\n'): - file.write(str+terminator) - - -def print_list(extracted_list, file=None): - """Print the list of tuples as returned by extract_tb() or - extract_stack() as a formatted stack trace to the given file.""" - if file is None: - file = sys.stderr - for filename, lineno, name, line in extracted_list: - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - if line: - _print(file, ' %s' % line.strip()) - -def format_list(extracted_list): - """Format a list of traceback entry tuples for printing. - - Given a list of tuples as returned by extract_tb() or - extract_stack(), return a list of strings ready for printing. - Each string in the resulting list corresponds to the item with the - same index in the argument list. Each string ends in a newline; - the strings may contain internal newlines as well, for those items - whose source text line is not None. - """ - list = [] - for filename, lineno, name, line in extracted_list: - item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) - if line: - item = item + ' %s\n' % line.strip() - list.append(item) - return list - - -def print_tb(tb, limit=None, file=None): - """Print up to 'limit' stack trace entries from the traceback 'tb'. - - If 'limit' is omitted or None, all entries are printed. If 'file' - is omitted or None, the output goes to sys.stderr; otherwise - 'file' should be an open file or file-like object with a write() - method. - """ - if file is None: - file = sys.stderr - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - line = linecache.getline(filename, lineno) - if line: _print(file, ' ' + line.strip()) - tb = tb.tb_next - n = n+1 - -def format_tb(tb, limit = None): - """A shorthand for 'format_list(extract_stack(f, limit)).""" - return format_list(extract_tb(tb, limit)) - -def extract_tb(tb, limit = None): - """Return list of up to limit pre-processed entries from traceback. - - This is useful for alternate formatting of stack traces. If - 'limit' is omitted or None, all entries are extracted. A - pre-processed stack trace entry is a quadruple (filename, line - number, function name, text) representing the information that is - usually printed for a stack trace. The text is a string with - leading and trailing whitespace stripped; if the source is not - available it is None. - """ - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = line.strip() - else: line = None - list.append((filename, lineno, name, line)) - tb = tb.tb_next - n = n+1 - return list - - -def print_exception(etype, value, tb, limit=None, file=None): - """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. - - This differs from print_tb() in the following ways: (1) if - traceback is not None, it prints a header "Traceback (most recent - call last):"; (2) it prints the exception type and value after the - stack trace; (3) if type is SyntaxError and value has the - appropriate format, it prints the line where the syntax error - occurred with a caret on the next line indicating the approximate - position of the error. - """ - if file is None: - file = sys.stderr - if tb: - _print(file, 'Traceback (most recent call last):') - print_tb(tb, limit, file) - lines = format_exception_only(etype, value) - for line in lines[:-1]: - _print(file, line, ' ') - _print(file, lines[-1], '') - -def format_exception(etype, value, tb, limit = None): - """Format a stack trace and the exception information. - - The arguments have the same meaning as the corresponding arguments - to print_exception(). The return value is a list of strings, each - ending in a newline and some containing internal newlines. When - these lines are concatenated and printed, exactly the same text is - printed as does print_exception(). - """ - if tb: - list = ['Traceback (most recent call last):\n'] - list = list + format_tb(tb, limit) - else: - list = [] - list = list + format_exception_only(etype, value) - return list - -def format_exception_only(etype, value): - """Format the exception part of a traceback. - - The arguments are the exception type and value such as given by - sys.last_type and sys.last_value. The return value is a list of - strings, each ending in a newline. Normally, the list contains a - single string; however, for SyntaxError exceptions, it contains - several lines that (when printed) display detailed information - about where the syntax error occurred. The message indicating - which exception occurred is the always last string in the list. - """ - list = [] - # the following line is the only change against Py 2.3.3 - # Python will change here, anyway. Drop this file, then. - if isinstance(etype, (types.ClassType, type)): - stype = etype.__name__ - else: - stype = etype - if value is None: - list.append(str(stype) + '\n') - else: - if etype is SyntaxError: - try: - msg, (filename, lineno, offset, line) = value - except: - pass - else: - if not filename: filename = "" - list.append(' File "%s", line %d\n' % - (filename, lineno)) - if line is not None: - i = 0 - while i < len(line) and line[i].isspace(): - i = i+1 - list.append(' %s\n' % line.strip()) - if offset is not None: - s = ' ' - for c in line[i:offset-1]: - if c.isspace(): - s = s + c - else: - s = s + ' ' - list.append('%s^\n' % s) - value = msg - s = _some_str(value) - if s: - list.append('%s: %s\n' % (str(stype), s)) - else: - list.append('%s\n' % str(stype)) - return list - -def _some_str(value): - try: - return str(value) - except: - return '' % type(value).__name__ - - -def print_exc(limit=None, file=None): - """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. - (In fact, it uses sys.exc_info() to retrieve the same information - in a thread-safe way.)""" - if file is None: - file = sys.stderr - try: - etype, value, tb = sys.exc_info() - print_exception(etype, value, tb, limit, file) - finally: - etype = value = tb = None - -def print_last(limit=None, file=None): - """This is a shorthand for 'print_exception(sys.last_type, - sys.last_value, sys.last_traceback, limit, file)'.""" - if file is None: - file = sys.stderr - print_exception(sys.last_type, sys.last_value, sys.last_traceback, - limit, file) - - -def print_stack(f=None, limit=None, file=None): - """Print a stack trace from its invocation point. - - The optional 'f' argument can be used to specify an alternate - stack frame at which to start. The optional 'limit' and 'file' - arguments have the same meaning as for print_exception(). - """ - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - print_list(extract_stack(f, limit), file) - -def format_stack(f=None, limit=None): - """Shorthand for 'format_list(extract_stack(f, limit))'.""" - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - return format_list(extract_stack(f, limit)) - -def extract_stack(f=None, limit = None): - """Extract the raw traceback from the current stack frame. - - The return value has the same format as for extract_tb(). The - optional 'f' and 'limit' arguments have the same meaning as for - print_stack(). Each item in the list is a quadruple (filename, - line number, function name, text), and the entries are in order - from oldest to newest stack frame. - """ - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while f is not None and (limit is None or n < limit): - lineno = f.f_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = line.strip() - else: line = None - list.append((filename, lineno, name, line)) - f = f.f_back - n = n+1 - list.reverse() - return list - -def tb_lineno(tb): - """Calculate correct line number of traceback given in tb. - - Obsolete in 2.3. - """ - return tb.tb_lineno Deleted: /pypy/dist/pypy/appspace/types.py ============================================================================== --- /pypy/dist/pypy/appspace/types.py Thu Jan 27 23:35:29 2005 +++ (empty file) @@ -1,123 +0,0 @@ -"""Appspace types module. - -!! This file has been copied practicaly verbatim from the CPython source. -!! See http://www.python.org/2.3.2/license.html for licensing info. - -Define names for all type symbols known in the standard interpreter. - -Types that are part of optional modules (e.g. array) are not listed. -""" -from __future__ import generators - -import sys - -# Iterators in Python aren't a matter of type but of protocol. A large -# and changing number of builtin types implement *some* flavor of -# iterator. Don't check the type! Use hasattr to check for both -# "__iter__" and "next" attributes instead. - -NoneType = type(None) -TypeType = type -ObjectType = object - -IntType = int -try: - LongType = long -except NameError: - pass -FloatType = float -try: - BooleanType = bool -except NameError: - pass -try: - ComplexType = complex -except NameError: - pass - -StringType = str -try: - UnicodeType = unicode - StringTypes = (StringType, UnicodeType) -except NameError: - StringTypes = (StringType,) - -try: - BufferType = buffer -except NameError: - pass - -TupleType = tuple -ListType = list -DictType = DictionaryType = dict - -def _f(): pass -FunctionType = type(_f) -LambdaType = type(lambda: None) # Same as FunctionType -try: - CodeType = type(_f.func_code) -except RuntimeError: - # Execution in restricted environment - pass - -def g(): - yield 1 -try: - GeneratorType = type(g()) -except: - # Refusing generators - pass -del g - -# checking whether we can make copy_reg happy -##class _C: -## def _m(self): pass -##ClassType = type(_C) -class ClassType: pass -class _C: - def _m(self):pass -## end of testing hack -try: - UnboundMethodType = type(_C._m) # Same as MethodType -except AttributeError: - pass -_x = _C() -InstanceType = type(_x) -MethodType = type(_x._m) - -BuiltinFunctionType = type(len) -BuiltinMethodType = type([].append) # Same as BuiltinFunctionType - -ModuleType = type(sys) -try: - FileType = file -except NameError: - pass -try: - XRangeType = type(xrange(0)) -except NameError: - pass - -try: - raise TypeError -except TypeError: - try: - tb = sys.exc_info()[2] - TracebackType = type(tb) - FrameType = type(tb.tb_frame) - except AttributeError: - # In the restricted environment, exc_info returns (None, None, - # None) Then, tb.tb_frame gives an attribute error - pass - tb = None; del tb - -SliceType = type(slice(0)) -EllipsisType = type(Ellipsis) - -#DictProxyType = type(TypeType.__dict__) -try: - NotImplementedType = type(NotImplemented) -except NameError: - pass - -del sys, _f, _C, _x#, generators # Not for export Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Thu Jan 27 23:35:29 2005 @@ -62,9 +62,14 @@ from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) appdir = os.path.join(autopath.pypydir, 'appspace') +python_std_lib = os.path.join(autopath.pypydir, '..','lib-python-2.3.4') +assert os.path.exists(python_std_lib) del os, autopath # XXX for the translator. Something is very wrong around here. -w_initialpath = space.newlist([space.wrap(''), space.wrap(appdir)] + +w_initialpath = space.newlist([space.wrap(''), + space.wrap(python_std_lib), + #space.wrap(appdir), + ] + [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) # XXX - Replace with appropriate PyPy version numbering Modified: pypy/dist/pypy/module/test/test_zip.py ============================================================================== --- pypy/dist/pypy/module/test/test_zip.py (original) +++ pypy/dist/pypy/module/test/test_zip.py Thu Jan 27 23:35:29 2005 @@ -32,7 +32,7 @@ [('h', 1, 7), ('e', 2, 8), ('l', 3, 9), ('l', 4, 10)]) def test_from_cpython(self): - from test.support_tests import TESTFN, unlink + from test.test_support import TESTFN, unlink class BasicIterClass: def __init__(self, n): self.n = n From hpk at codespeak.net Fri Jan 28 08:24:10 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 28 Jan 2005 08:24:10 +0100 (MET) Subject: [pypy-svn] r8647 - pypy/dist/pypy Message-ID: <20050128072410.2E94627B90@code1.codespeak.net> Author: hpk Date: Fri Jan 28 08:24:09 2005 New Revision: 8647 Modified: pypy/dist/pypy/conftest.py Log: allow KeyboardInterrupt to interrupt testing of applevel tests. Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Fri Jan 28 08:24:09 2005 @@ -103,6 +103,8 @@ try: target(*args) except OperationError, e: + if e.match(space, space.w_KeyboardInterrupt): + raise KeyboardInterrupt raise self.Failed(excinfo=pytestsupport.AppExceptionInfo(space, e)) class IntTestFunction(PyPyItem): From arigo at codespeak.net Fri Jan 28 10:00:30 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 28 Jan 2005 10:00:30 +0100 (MET) Subject: [pypy-svn] r8648 - pypy/dist/pypy/objspace/std Message-ID: <20050128090030.4966927B90@code1.codespeak.net> Author: arigo Date: Fri Jan 28 10:00:30 2005 New Revision: 8648 Modified: pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/tupleobject.py Log: Added list.__contains__ and tuple.__contains__ instead of relying on the default behavior based on __iter__. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Fri Jan 28 10:00:30 2005 @@ -89,6 +89,13 @@ w_res.ob_size = slicelength return w_res +def contains__List_ANY(space, w_list, w_obj): + items = w_list.ob_item + for i in range(w_list.ob_size): + if space.eq_w(items[i], w_obj): + return space.w_True + return space.w_False + def iter__List(space, w_list): from pypy.objspace.std import iterobject return iterobject.W_SeqIterObject(space, w_list) Modified: pypy/dist/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupleobject.py (original) +++ pypy/dist/pypy/objspace/std/tupleobject.py Fri Jan 28 10:00:30 2005 @@ -48,6 +48,12 @@ start += step return W_TupleObject(space, subitems) +def contains__Tuple_ANY(space, w_tuple, w_obj): + for w_item in w_tuple.wrappeditems: + if space.eq_w(w_item, w_obj): + return space.w_True + return space.w_False + def iter__Tuple(space, w_tuple): from pypy.objspace.std import iterobject return iterobject.W_SeqIterObject(space, w_tuple) From pedronis at codespeak.net Fri Jan 28 10:16:04 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 28 Jan 2005 10:16:04 +0100 (MET) Subject: [pypy-svn] r8649 - pypy/dist/pypy/translator/test Message-ID: <20050128091604.4414027B90@code1.codespeak.net> Author: pedronis Date: Fri Jan 28 10:16:04 2005 New Revision: 8649 Modified: pypy/dist/pypy/translator/test/test_annrpython.py Log: make the test tests what we are really interested in Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Fri Jan 28 10:16:04 2005 @@ -491,14 +491,15 @@ def test_bltin_code_frame_confusion(self): a = RPythonAnnotator() - s = a.build_types(snippet.bltin_code_frame_confusion,[]) - assert isinstance(s, annmodel.SomeTuple) - is_int = isinstance(s.items[0], annmodel.SomeInteger) + a.build_types(snippet.bltin_code_frame_confusion,[]) + f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f) + g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g) + is_int = isinstance(a.binding(f_flowgraph.getreturnvar()), + annmodel.SomeInteger) if not is_int: py.test.skip("annotator confused with bltin code/frame setup") - assert isinstance(s.items[1], annmodel.SomeInteger) - assert isinstance(s.items[2], annmodel.SomeString) - assert isinstance(s.items[3], annmodel.SomeString) + assert isinstance(a.binding(g_flowgraph.getreturnvar()), + annmodel.SomeString) def g(n): From arigo at codespeak.net Fri Jan 28 11:11:16 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 28 Jan 2005 11:11:16 +0100 (MET) Subject: [pypy-svn] r8651 - in pypy/dist/pypy: appspace interpreter/test module tool Message-ID: <20050128101116.3363027B90@code1.codespeak.net> Author: arigo Date: Fri Jan 28 11:11:16 2005 New Revision: 8651 Modified: pypy/dist/pypy/appspace/re.py (props changed) pypy/dist/pypy/interpreter/test/test_py.py (props changed) pypy/dist/pypy/module/exceptionsinterp.py (props changed) pypy/dist/pypy/tool/_enum_exceptions.py (contents, props changed) Log: fixeol Modified: pypy/dist/pypy/tool/_enum_exceptions.py ============================================================================== --- pypy/dist/pypy/tool/_enum_exceptions.py (original) +++ pypy/dist/pypy/tool/_enum_exceptions.py Fri Jan 28 11:11:16 2005 @@ -1,147 +1,147 @@ -# this script is used for extracting -# the information available for exceptions -# via introspection. -# The idea is to use it once to create -# a template for a re-birth of exceptions.py - -import types - -def classOfAttribute(klass, attname): - if attname in klass.__dict__: - return klass - for base in klass.__bases__: - ret = classOfAttribute(base, attname) - if ret: - return ret - -def getAttributes(klass, ignorelist = []): - return [name for name in dir(klass) if name not in ignorelist] - -def makeExceptionsTemplate(f=None): - - def enumExceptionsInOrder(): - import exceptions - seen = {} - ordered = [] - - def enumerateOne(exc): - seen[exc] = 1 - for each in exc.__bases__: - if each not in seen: - enumerateOne(each) - ordered.append(exc) - - for each in exceptions.__dict__.values(): - if isinstance(each, (types.ClassType, type)) and \ - each not in seen: - enumerateOne(each) - - return ordered - - if not f: - f = sys.stdout - - for exc in enumExceptionsInOrder(): - name = exc.__name__ - bases = exc.__bases__ - doc = exc.__doc__ - bases = [this.__name__ for this in bases] - bases = ", ".join(bases) - if bases: bases = "(%s)" % bases - - ignorelist = "__doc__ __module__".split() - # find out class variables and methods - simple = [] - difficult = [] - for attname in getAttributes(exc, ignorelist): - if classOfAttribute(exc, attname) is exc: - obj = getattr(exc, attname) - (simple, difficult)[callable(obj)].append( (attname, obj) ) - print >> f, "class %s%s:" % (name, bases) - if doc: - print >> f, ' """%s"""' % doc - if not (simple or difficult or doc): - print >> f, " pass" - for tup in simple: - print >> f, " %s = %r" % tup - - for attname, meth in difficult: - print >> f - func = globals().get("tryGenerate" + attname, None) - if not func: - print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) - else: - try: - print >> f, " # auto-generated code, please check carefully!" - for line in func(exc): - print >> f, " " + line - except ValueError, e: - print >> f, " # %s" % e - print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) - print >> f - -def tryGenerate__getitem__(exc): - for args in (), (1, 2, 3): - try: - sample = exc(*args) - except: - raise ValueError, "cannot create instance" - if "args" not in sample.__dict__: - raise ValueError, "args attribute not found in __dict__" - if args != sample.args: - raise ValueError, "instance has modified args" - for i in range(5): - try: x = sample[i] - except IndexError: x = 42 - try: y = args[i] - except IndexError: y = 42 - if x != y: - raise ValueError, "args does not behave like a sequence" - del sample.args - try: x = sample[0] - except: x = 42 - use_default = x is None - # looks fine so far. - yield "def __getitem__(self, idx):" - if use_default: - yield " if not hasattr(self, 'args'):" - yield " return None" - yield " return self.args[idx]" - - -class ProbeObject(object): - """ this class creates general "any" objects, and - for the special case of SyntaxError, it can behave - like a subscriptable object - """ - def __init__(self, argpos, maxprobe=None): - self.argpos = argpos - self.maxprobe = maxprobe - self.probed = [] - def __getitem__(self, idx): - if idx not in self.probed: - self.probed.append(idx) - if self.maxprobe is not None and idx > self.maxprobe: - raise IndexError, "cheat cheat %d" % idx - return "arg%d_%s" % (self.argpos, idx) - def __repr__(self): - if self.probed: - return "" % (self.argpos, self.probed) - else: - return "" % self.argpos - def __str__(self): - # make this different from repr! - return repr(self)[1:-1] - def __cmp__(self, other): - return cmp( (self.argpos, self.probed), other) - -def genArgsToTry(argpos): - args = [ProbeObject(argpos), - "arg%d" % argpos, u"arg%d" %argpos, 1000+argpos*10] - return args - -def cartesian(*args): - if len(args)== 0: +# this script is used for extracting +# the information available for exceptions +# via introspection. +# The idea is to use it once to create +# a template for a re-birth of exceptions.py + +import types + +def classOfAttribute(klass, attname): + if attname in klass.__dict__: + return klass + for base in klass.__bases__: + ret = classOfAttribute(base, attname) + if ret: + return ret + +def getAttributes(klass, ignorelist = []): + return [name for name in dir(klass) if name not in ignorelist] + +def makeExceptionsTemplate(f=None): + + def enumExceptionsInOrder(): + import exceptions + seen = {} + ordered = [] + + def enumerateOne(exc): + seen[exc] = 1 + for each in exc.__bases__: + if each not in seen: + enumerateOne(each) + ordered.append(exc) + + for each in exceptions.__dict__.values(): + if isinstance(each, (types.ClassType, type)) and \ + each not in seen: + enumerateOne(each) + + return ordered + + if not f: + f = sys.stdout + + for exc in enumExceptionsInOrder(): + name = exc.__name__ + bases = exc.__bases__ + doc = exc.__doc__ + bases = [this.__name__ for this in bases] + bases = ", ".join(bases) + if bases: bases = "(%s)" % bases + + ignorelist = "__doc__ __module__".split() + # find out class variables and methods + simple = [] + difficult = [] + for attname in getAttributes(exc, ignorelist): + if classOfAttribute(exc, attname) is exc: + obj = getattr(exc, attname) + (simple, difficult)[callable(obj)].append( (attname, obj) ) + print >> f, "class %s%s:" % (name, bases) + if doc: + print >> f, ' """%s"""' % doc + if not (simple or difficult or doc): + print >> f, " pass" + for tup in simple: + print >> f, " %s = %r" % tup + + for attname, meth in difficult: + print >> f + func = globals().get("tryGenerate" + attname, None) + if not func: + print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) + else: + try: + print >> f, " # auto-generated code, please check carefully!" + for line in func(exc): + print >> f, " " + line + except ValueError, e: + print >> f, " # %s" % e + print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) + print >> f + +def tryGenerate__getitem__(exc): + for args in (), (1, 2, 3): + try: + sample = exc(*args) + except: + raise ValueError, "cannot create instance" + if "args" not in sample.__dict__: + raise ValueError, "args attribute not found in __dict__" + if args != sample.args: + raise ValueError, "instance has modified args" + for i in range(5): + try: x = sample[i] + except IndexError: x = 42 + try: y = args[i] + except IndexError: y = 42 + if x != y: + raise ValueError, "args does not behave like a sequence" + del sample.args + try: x = sample[0] + except: x = 42 + use_default = x is None + # looks fine so far. + yield "def __getitem__(self, idx):" + if use_default: + yield " if not hasattr(self, 'args'):" + yield " return None" + yield " return self.args[idx]" + + +class ProbeObject(object): + """ this class creates general "any" objects, and + for the special case of SyntaxError, it can behave + like a subscriptable object + """ + def __init__(self, argpos, maxprobe=None): + self.argpos = argpos + self.maxprobe = maxprobe + self.probed = [] + def __getitem__(self, idx): + if idx not in self.probed: + self.probed.append(idx) + if self.maxprobe is not None and idx > self.maxprobe: + raise IndexError, "cheat cheat %d" % idx + return "arg%d_%s" % (self.argpos, idx) + def __repr__(self): + if self.probed: + return "" % (self.argpos, self.probed) + else: + return "" % self.argpos + def __str__(self): + # make this different from repr! + return repr(self)[1:-1] + def __cmp__(self, other): + return cmp( (self.argpos, self.probed), other) + +def genArgsToTry(argpos): + args = [ProbeObject(argpos), + "arg%d" % argpos, u"arg%d" %argpos, 1000+argpos*10] + return args + +def cartesian(*args): + if len(args)== 0: yield args elif len(args) == 1: for item in args[0]: @@ -150,182 +150,182 @@ for item in args[0]: for other in cartesian(*args[1:]): yield (item,) + other - -def probeArgCount(exc, maxprobe=20): - worksmaybe = [] - for i in range(maxprobe): - try: - probe = exc(*(i,)*i) # test i-tuple - worksmaybe.append(i) - except TypeError, e: - if not str(e).startswith("function takes "): - worksmaybe.append(i) - except: - pass - return min(worksmaybe), max(worksmaybe) - -def refreshArgs(tup): - res = [] - for arg in tup: - if type(arg) is ProbeObject: - arg = ProbeObject(arg.argpos) # cleanup probing - res.append(arg) - return tuple(res) - -def findAllArgs(exc, maxprobe): - minargs, maxargs = probeArgCount(exc, maxprobe=20) - res = [] - # for minargs args, we need to try combinations - arglist = tuple([genArgsToTry(i) for i in range(minargs)]) - for args in cartesian(*arglist): - try: - probe = exc(*args) - res.append(args) - works = refreshArgs(args) - break - except Exception, e: - continue - else: - raise TypeError, "cannot analyse arguments of %s" % exc.__name__ - # for the variable part, don't try combinations - for i in range(minargs, maxargs): - for arg in genArgsToTry(i): - args = works + (arg,) - try: - probe = exc(*args) - res.append(args) - works = refreshArgs(args) - break - except: - continue - else: - raise TypeError, "cannot analyse arguments of %s" % exc.__name__ - return minargs, maxargs, res - -def captureAssignments(exc, args): - """ we wrap a class around the exc class and record attribute access """ - assigned = [] - class WrapExc(exc): - def __setattr__(self, name, obj): - assigned.append( (name, obj) ) - self.__dict__[name] = obj - probe = WrapExc(*args) - names = {} - names[args] = "args" - for i, arg in enumerate(args): - names[arg] = "args[%d]" % i - if not isinstance(arg, ProbeObject): - continue - for subidx in arg.probed: - names[arg[subidx]] = "args[%d][%d]" % (i, subidx) - def nameof(obj): - if obj in names: - return names[obj] - elif isinstance(obj, (tuple, list)): - stuff = [nameof(x) for x in obj] - br = str(type(obj)()) - txt = br[0] + ", ".join(stuff) + br[-1] - names[obj] = txt - else: - names[obj] = "%r # default, hopefully" % obj - return names[obj] - res = [] - for name, obj in assigned: - res.append("self.%s = %s" % (name, nameof(obj))) - return tuple(res) - -def tryGenerate__init__(exc, maxprobe=20): - minargs, maxargs, working = findAllArgs(exc, maxprobe) - # merge assignments in order, record set of arg counts - foldcases = {} - for args in working: - singleprog = captureAssignments(exc, args) - for tup in enumerate(singleprog): - foldcases.setdefault(tup, []) - foldcases[tup].append(len(args)) - # group assignments by set of arg counts and order - groupassign = {} - for (order, assignment), argcounts in foldcases.items(): - key = tuple(argcounts) - # special case: we don't raise errors - # and always assign to self.args - if assignment == "self.args = args" and len(key) != maxprobe: - assignment += " # modified: always assign args, no error check" - key = tuple(range(maxprobe)) - groupassign.setdefault(key, []) - groupassign[key].append( (order, assignment) ) - cases = groupassign.items() - cases.sort() - yield "def __init__(self, *args):" - if len(cases) > 1 or len(cases[0][0]) != maxprobe: - yield " argc = len(args)" - for argcounts, ordered_statements in cases: - ordered_statements.sort() - if len(argcounts) == maxprobe: - # all counts, no condition - indent = 1 - else: - indent = 2 - dense = tuple(range(argcounts[0], argcounts[-1]+1)) == argcounts - if len(argcounts) == 1: - yield " if argc == %d:" % argcounts - elif dense and argcounts[0] == 0: - yield " if argc <= %d:" % argcounts[-1] - elif dense and argcounts[-1] == maxprobe-1: - yield " if argc >= %d:" % argcounts[0] - elif dense: - yield " if %d <= argc <= %d:" % (argcounts[0], argcounts[-1]) - else: - yield " if argc in %r:" % (argcounts, ) - for order, line in ordered_statements: - yield indent * " " + line - -def tryGenerate__str__(exc, maxprobe=20): - minargs, maxargs, working = findAllArgs(exc, maxprobe) - # checking the default case (well, there are two) - simple = False - arg1_methods = [] - for args in working: - test = str(exc(*args)) - if len(args) == 0 and test != "": - break - if len(args) == 1: - if test == repr(args[0]): - arg1_methods.append("repr") - elif test == str(args[0]): - arg1_methods.append("str") - else: - break - if len(args) >= 2 and test != repr(args): - break - else: - simple = arg1_methods and min(arg1_methods) == max(arg1_methods) - if simple: - yield "def __str__(self):" - yield " argc = len(self.args)" - yield " if argc == 0:" - yield " return ''" - yield " elif argc == 1:" - yield " return %s(self.args[0])" % arg1_methods.pop() - yield " else:" - yield " return str(self.args)" - return - # no idea how I should do this - probe = exc(*working[0]) - dic = probe.__dict__ - for key in dic.keys(): - if key.startswith("__") and key.endswith("__"): - del dic[key] - yield "def __str__(self):" - yield " # this is a bad hack, please supply an implementation" - yield " res = ' '.join([" - for key in dic.keys(): - yield " '%s=' + str(self.%s)," % (key, key) - yield " ])" - yield " return res" - -if __name__ == "__main__": - import pypy.appspace, os - targetdir = os.path.dirname(pypy.appspace.__file__) - fname = os.path.join(targetdir, "_exceptions.py") - makeExceptionsTemplate(file(fname, "w")) + +def probeArgCount(exc, maxprobe=20): + worksmaybe = [] + for i in range(maxprobe): + try: + probe = exc(*(i,)*i) # test i-tuple + worksmaybe.append(i) + except TypeError, e: + if not str(e).startswith("function takes "): + worksmaybe.append(i) + except: + pass + return min(worksmaybe), max(worksmaybe) + +def refreshArgs(tup): + res = [] + for arg in tup: + if type(arg) is ProbeObject: + arg = ProbeObject(arg.argpos) # cleanup probing + res.append(arg) + return tuple(res) + +def findAllArgs(exc, maxprobe): + minargs, maxargs = probeArgCount(exc, maxprobe=20) + res = [] + # for minargs args, we need to try combinations + arglist = tuple([genArgsToTry(i) for i in range(minargs)]) + for args in cartesian(*arglist): + try: + probe = exc(*args) + res.append(args) + works = refreshArgs(args) + break + except Exception, e: + continue + else: + raise TypeError, "cannot analyse arguments of %s" % exc.__name__ + # for the variable part, don't try combinations + for i in range(minargs, maxargs): + for arg in genArgsToTry(i): + args = works + (arg,) + try: + probe = exc(*args) + res.append(args) + works = refreshArgs(args) + break + except: + continue + else: + raise TypeError, "cannot analyse arguments of %s" % exc.__name__ + return minargs, maxargs, res + +def captureAssignments(exc, args): + """ we wrap a class around the exc class and record attribute access """ + assigned = [] + class WrapExc(exc): + def __setattr__(self, name, obj): + assigned.append( (name, obj) ) + self.__dict__[name] = obj + probe = WrapExc(*args) + names = {} + names[args] = "args" + for i, arg in enumerate(args): + names[arg] = "args[%d]" % i + if not isinstance(arg, ProbeObject): + continue + for subidx in arg.probed: + names[arg[subidx]] = "args[%d][%d]" % (i, subidx) + def nameof(obj): + if obj in names: + return names[obj] + elif isinstance(obj, (tuple, list)): + stuff = [nameof(x) for x in obj] + br = str(type(obj)()) + txt = br[0] + ", ".join(stuff) + br[-1] + names[obj] = txt + else: + names[obj] = "%r # default, hopefully" % obj + return names[obj] + res = [] + for name, obj in assigned: + res.append("self.%s = %s" % (name, nameof(obj))) + return tuple(res) + +def tryGenerate__init__(exc, maxprobe=20): + minargs, maxargs, working = findAllArgs(exc, maxprobe) + # merge assignments in order, record set of arg counts + foldcases = {} + for args in working: + singleprog = captureAssignments(exc, args) + for tup in enumerate(singleprog): + foldcases.setdefault(tup, []) + foldcases[tup].append(len(args)) + # group assignments by set of arg counts and order + groupassign = {} + for (order, assignment), argcounts in foldcases.items(): + key = tuple(argcounts) + # special case: we don't raise errors + # and always assign to self.args + if assignment == "self.args = args" and len(key) != maxprobe: + assignment += " # modified: always assign args, no error check" + key = tuple(range(maxprobe)) + groupassign.setdefault(key, []) + groupassign[key].append( (order, assignment) ) + cases = groupassign.items() + cases.sort() + yield "def __init__(self, *args):" + if len(cases) > 1 or len(cases[0][0]) != maxprobe: + yield " argc = len(args)" + for argcounts, ordered_statements in cases: + ordered_statements.sort() + if len(argcounts) == maxprobe: + # all counts, no condition + indent = 1 + else: + indent = 2 + dense = tuple(range(argcounts[0], argcounts[-1]+1)) == argcounts + if len(argcounts) == 1: + yield " if argc == %d:" % argcounts + elif dense and argcounts[0] == 0: + yield " if argc <= %d:" % argcounts[-1] + elif dense and argcounts[-1] == maxprobe-1: + yield " if argc >= %d:" % argcounts[0] + elif dense: + yield " if %d <= argc <= %d:" % (argcounts[0], argcounts[-1]) + else: + yield " if argc in %r:" % (argcounts, ) + for order, line in ordered_statements: + yield indent * " " + line + +def tryGenerate__str__(exc, maxprobe=20): + minargs, maxargs, working = findAllArgs(exc, maxprobe) + # checking the default case (well, there are two) + simple = False + arg1_methods = [] + for args in working: + test = str(exc(*args)) + if len(args) == 0 and test != "": + break + if len(args) == 1: + if test == repr(args[0]): + arg1_methods.append("repr") + elif test == str(args[0]): + arg1_methods.append("str") + else: + break + if len(args) >= 2 and test != repr(args): + break + else: + simple = arg1_methods and min(arg1_methods) == max(arg1_methods) + if simple: + yield "def __str__(self):" + yield " argc = len(self.args)" + yield " if argc == 0:" + yield " return ''" + yield " elif argc == 1:" + yield " return %s(self.args[0])" % arg1_methods.pop() + yield " else:" + yield " return str(self.args)" + return + # no idea how I should do this + probe = exc(*working[0]) + dic = probe.__dict__ + for key in dic.keys(): + if key.startswith("__") and key.endswith("__"): + del dic[key] + yield "def __str__(self):" + yield " # this is a bad hack, please supply an implementation" + yield " res = ' '.join([" + for key in dic.keys(): + yield " '%s=' + str(self.%s)," % (key, key) + yield " ])" + yield " return res" + +if __name__ == "__main__": + import pypy.appspace, os + targetdir = os.path.dirname(pypy.appspace.__file__) + fname = os.path.join(targetdir, "_exceptions.py") + makeExceptionsTemplate(file(fname, "w")) From arigo at codespeak.net Fri Jan 28 11:13:56 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 28 Jan 2005 11:13:56 +0100 (MET) Subject: [pypy-svn] r8652 - pypy/dist/lib-python-2.3.4 Message-ID: <20050128101356.3F0D027B90@code1.codespeak.net> Author: arigo Date: Fri Jan 28 11:13:56 2005 New Revision: 8652 Modified: pypy/dist/lib-python-2.3.4/conftest.py (props changed) pypy/dist/lib-python-2.3.4/dumbre.py (props changed) pypy/dist/lib-python-2.3.4/plexre.py (props changed) pypy/dist/lib-python-2.3.4/pypy_unittest.py (props changed) Log: fixeol From arigo at codespeak.net Fri Jan 28 11:10:39 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 28 Jan 2005 11:10:39 +0100 (MET) Subject: [pypy-svn] r8650 - in pypy/dist/pypy: interpreter module translator Message-ID: <20050128101039.B8F5E27B90@code1.codespeak.net> Author: arigo Date: Fri Jan 28 11:10:39 2005 New Revision: 8650 Modified: pypy/dist/pypy/interpreter/py.py pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: Don't import pypy.tool.udir or pypy.translator.geninterplevel at start-up! Modified: pypy/dist/pypy/interpreter/py.py ============================================================================== --- pypy/dist/pypy/interpreter/py.py (original) +++ pypy/dist/pypy/interpreter/py.py Fri Jan 28 11:10:39 2005 @@ -47,6 +47,9 @@ space = None try: space = option.objspace() + assert 'pypy.tool.udir' not in sys.modules, ( + "running py.py should not import pypy.tool.udir, which is\n" + "only for testing or translating purposes.") go_interactive = Options.interactive banner = '' space.setitem(space.sys.w_dict,space.wrap('executable'),space.wrap(argv[0])) Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Fri Jan 28 11:10:39 2005 @@ -1,1603 +1,1609 @@ -#!/bin/env python -# -*- coding: LATIN-1 -*- -##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' -## function 'test_exceptions' -## firstlineno 1253 -##SECTION## -# global declarations -# global object gfunc_test_exceptions -# global object gbltinmethod_keys -# global object g48dict -# global object gs_keys - -def test_exceptions(space, *args_w): - """ enumerate all exceptions """ - kwlist = [] - _args_w = args_w - defaults_w = () - funcname = "test_exceptions" - PyArg_ParseMini(space, funcname, 0, 0, _args_w, defaults_w) - return fastf_test_exceptions(space, ) -f_test_exceptions = globals().pop("test_exceptions") - -def test_exceptions(space, ): - """ enumerate all exceptions """ - - w_0=w_0=w_1=None - - goto = 1 # startblock - while True: - - if goto == 1: - _tup = space.newtuple([]) - w_0 = space.call(gbltinmethod_keys, _tup) - w_1 = w_0 - goto = 2 - - if goto == 2: - return w_1 -fastf_test_exceptions = globals().pop("test_exceptions") - -# global declarations -# global object gs_MemoryError -# global object gcls_MemoryError -# global object gcls_StandardError -# global object gcls_Exception -# global object gs___module__ -# global object gs_pypy_appspace__exceptions -# global object gs___doc__ -# global object gs_Exception -# global object gs_StandardError -# global object gs_ImportError -# global object gcls_ImportError -# global object gs_RuntimeError -# global object gcls_RuntimeError -# global object gs_UnicodeTranslateError -# global object gcls_UnicodeTranslateError -# global object gcls_UnicodeError -# global object gcls_ValueError -# global object gs_ValueError -# global object gs_UnicodeError -# global object gs_KeyError -# global object gcls_KeyError -# global object gcls_LookupError -# global object gs_LookupError -# global object gs_SyntaxWarning -# global object gcls_SyntaxWarning -# global object gcls_Warning -# global object gs_Warning -# global object gs_StopIteration -# global object gcls_StopIteration -# global object gs_PendingDeprecationWarning -# global object gcls_PendingDeprecationWarning -# global object gs_EnvironmentError -# global object gcls_EnvironmentError -# global object gs_SyntaxError -# global object gcls_SyntaxError -# global object gs_OSError -# global object gcls_OSError -# global object gs_DeprecationWarning -# global object gcls_DeprecationWarning -# global object gs_FloatingPointError -# global object gcls_FloatingPointError -# global object gcls_ArithmeticError -# global object gs_ArithmeticError -# global object gs_ReferenceError -# global object gcls_ReferenceError -# global object gs_NameError -# global object gcls_NameError -# global object gs_OverflowWarning -# global object gcls_OverflowWarning -# global object gs_IOError -# global object gcls_IOError -# global object gs_FutureWarning -# global object gcls_FutureWarning -# global object gs_SystemExit -# global object gcls_SystemExit -# global object gs_EOFError -# global object gcls_EOFError -# global object gs___file__ -# global object gs_D___pypy__dist__pypy__appspace__ -# global object gs_TabError -# global object gcls_TabError -# global object gcls_IndentationError -# global object gs_IndentationError -# global object gs_ZeroDivisionError -# global object gcls_ZeroDivisionError -# global object gs_UnicodeEncodeError -# global object gcls_UnicodeEncodeError -# global object gs_SystemError -# global object gcls_SystemError -# global object gs___name__ -# global object gs_AssertionError -# global object gcls_AssertionError -# global object gs_UnicodeDecodeError -# global object gcls_UnicodeDecodeError -# global object gs_TypeError -# global object gcls_TypeError -# global object gs_IndexError -# global object gcls_IndexError -# global object gs_RuntimeWarning -# global object gcls_RuntimeWarning -# global object gs_KeyboardInterrupt -# global object gcls_KeyboardInterrupt -# global object gs_UserWarning -# global object gcls_UserWarning -# global object gs_TaskletExit -# global object gcls_TaskletExit -# global object gs_UnboundLocalError -# global object gcls_UnboundLocalError -# global object gs_NotImplementedError -# global object gcls_NotImplementedError -# global object gs_AttributeError -# global object gcls_AttributeError -# global object gs_OverflowError -# global object gcls_OverflowError -# global object gs_WindowsError -# global object gcls_WindowsError -# global object gs___init__ -# global object gfunc_UnicodeDecodeError___init__ -# global object gs___str__ -# global object gfunc_UnicodeDecodeError___str__ -# global object gfunc_UnicodeEncodeError___init__ -# global object gfunc_UnicodeEncodeError___str__ -# global object gfunc_SystemExit___init__ -# global object gfunc_SyntaxError___init__ -# global object gfunc_SyntaxError___str__ -# global object gs_filename -# global object gs_lineno -# global object gs_msg -# global object gs__emptystr_ -# global object gs_offset -# global object gs_print_file_and_line -# global object gs_text -# global object gfunc_EnvironmentError___init__ -# global object gfunc_EnvironmentError___str__ -# global object gfunc_KeyError___str__ -# global object gfunc_UnicodeTranslateError___init__ -# global object gfunc_UnicodeTranslateError___str__ -# global object gs___getitem__ -# global object gfunc_Exception___getitem__ -# global object gfunc_Exception___init__ -# global object gfunc_Exception___str__ - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__getitem__' -## firstlineno 5 -##SECTION## -def __getitem__(space, *args_w): - kwlist = ["self", "idx"] - _args_w = args_w - defaults_w = () - funcname = "__getitem__" - w_self_1, w_idx_3 = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) - return fastf_Exception___getitem__(space, w_self_1, w_idx_3) -f_Exception___getitem__ = globals().pop("__getitem__") - -def __getitem__(space, w_self_1, w_idx_3): - - w_0=w_0=w_2=w_4=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_2 = space.getitem(w_0, w_idx_3) - w_4 = w_2 - goto = 2 - - if goto == 2: - return w_4 -fastf_Exception___getitem__ = globals().pop("__getitem__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 9 -##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args_2 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_Exception___init__(space, w_self_1, w_args_2) -f_Exception___init__ = globals().pop("__init__") - -def __init__(space, w_self_1, w_args_2): - - w_0=w_0=w_3=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.setattr(w_self_1, gs_args, w_args_2) - w_3 = space.w_None - goto = 2 - - if goto == 2: - return w_3 -fastf_Exception___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 13 -##SECTION## -# global declarations -# global object gs_args -# global object gi_0 -# global object gi_1 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_Exception___str__(space, w_self_1) -f_Exception___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None - w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None - w_14=w_14=w_15=w_19=w_20=w_21=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_argc_2 = space.len(w_0) - w_3 = space.eq(w_argc_2, gi_0) - v4 = space.is_true(w_3) - if v4 == True: - w_5 = gs__emptystr_ - goto = 5 - else: - assert v4 == False - w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 - goto = 2 - - if goto == 2: - w_9 = space.eq(w_argc_7, gi_1) - v10 = space.is_true(w_9) - if v10 == True: - (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, - w_8, w_9, v10) - goto = 3 - else: - assert v10 == False - w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 - goto = 4 - - if goto == 3: - w_19 = space.getattr(w_self_11, gs_args) - w_20 = space.getitem(w_19, gi_0) - _tup = space.newtuple([w_20]) - w_21 = space.call(space.w_str, _tup) - w_5 = w_21 - goto = 5 - - if goto == 4: - w_22 = space.getattr(w_self_16, gs_args) - _tup = space.newtuple([w_22]) - w_23 = space.call(space.w_str, _tup) - w_5 = w_23 - goto = 5 - - if goto == 5: - return w_5 -fastf_Exception___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 41 -##SECTION## -# global declarations -# global object gi_4 -# global object gi_2 -# global object gi_3 - -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeTranslateError___init__(space, w_self_3, w_args_1) -f_UnicodeTranslateError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_4) - v5 = space.is_true(w_4) - if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) - goto = 2 - else: - assert v5 == False - w_12 = space.w_None - goto = 3 - - if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_object, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_start, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_end, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_reason, w_19) - w_12 = space.w_None - goto = 3 - - if goto == 3: - return w_12 -fastf_UnicodeTranslateError___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 51 -##SECTION## -# global declarations -# global object gs_start -# global object gs_start_ -# global object gs_reason -# global object gs_reason_ -# global object gs_args_ -# global object gs_end -# global object gs_end_ -# global object gs_object -# global object gs_object_ -# global object gbltinmethod_join -# global object gs__ -# global object gs_join - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeTranslateError___str__(space, w_self_1) -f_UnicodeTranslateError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_res_17=w_18=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_start) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_start_, w_2) - w_4 = space.getattr(w_self_1, gs_reason) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) - w_6 = space.add(gs_reason_, w_5) - w_7 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) - w_9 = space.add(gs_args_, w_8) - w_10 = space.getattr(w_self_1, gs_end) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) - w_12 = space.add(gs_end_, w_11) - w_13 = space.getattr(w_self_1, gs_object) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) - w_15 = space.add(gs_object_, w_14) - w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) - _tup = space.newtuple([w_16]) - w_res_17 = space.call(gbltinmethod_join, _tup) - w_18 = w_res_17 - goto = 2 - - if goto == 2: - return w_18 -fastf_UnicodeTranslateError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 69 -##SECTION## -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_KeyError___str__(space, w_self_1) -f_KeyError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None - w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None - w_14=w_14=w_15=w_19=w_20=w_21=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_argc_2 = space.len(w_0) - w_3 = space.eq(w_argc_2, gi_0) - v4 = space.is_true(w_3) - if v4 == True: - w_5 = gs__emptystr_ - goto = 5 - else: - assert v4 == False - w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 - goto = 2 - - if goto == 2: - w_9 = space.eq(w_argc_7, gi_1) - v10 = space.is_true(w_9) - if v10 == True: - (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, - w_8, w_9, v10) - goto = 3 - else: - assert v10 == False - w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 - goto = 4 - - if goto == 3: - w_19 = space.getattr(w_self_11, gs_args) - w_20 = space.getitem(w_19, gi_0) - w_21 = space.repr(w_20) - w_5 = w_21 - goto = 5 - - if goto == 4: - w_22 = space.getattr(w_self_16, gs_args) - _tup = space.newtuple([w_22]) - w_23 = space.call(space.w_str, _tup) - w_5 = w_23 - goto = 5 - - if goto == 5: - return w_5 -fastf_KeyError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 94 -##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_EnvironmentError___init__(space, w_self_3, w_args_1) -f_EnvironmentError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=None - w_argc_20=w_argc_20=w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=None - v37=v37=w_43=w_self_38=w_args_39=w_argc_40=w_41=w_42=w_44=w_45=None - w_46=w_46=w_47=w_48=w_49=w_self_24=w_args_25=w_argc_26=w_27=w_28=None - w_32=w_32=w_33=w_34=w_35=w_self_9=w_args_10=w_argc_11=w_12=w_13=None - w_14=w_14=w_15=w_16=w_17=w_22=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.setattr(w_self_3, gs_errno, space.w_None) - w_5 = space.setattr(w_self_3, gs_strerror, space.w_None) - w_6 = space.setattr(w_self_3, gs_filename, space.w_None) - w_7 = space.le(gi_2, w_argc_0) - v8 = space.is_true(w_7) - if v8 == True: - (w_self_9, w_args_10, w_argc_11, w_12, w_13, w_14, w_15, w_16, - w_17) = (w_self_3, w_args_1, w_argc_0, w_2, w_4, w_5, w_6, w_7, - v8) - goto = 2 - else: - assert v8 == False - (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_3, w_args_1, - w_argc_0, w_7) - goto = 3 - - if goto == 2: - w_22 = space.le(w_argc_11, gi_3) - (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_9, w_args_10, - w_argc_11, w_22) - goto = 3 - - if goto == 3: - v23 = space.is_true(w_21) - if v23 == True: - (w_self_24, w_args_25, w_argc_26, w_27, w_28) = (w_self_18, - w_args_19, w_argc_20, w_21, v23) - goto = 4 - else: - assert v23 == False - w_self_29, w_args_30, w_argc_31 = w_self_18, w_args_19, w_argc_20 - goto = 5 - - if goto == 4: - w_32 = space.getitem(w_args_25, gi_0) - w_33 = space.setattr(w_self_24, gs_errno, w_32) - w_34 = space.getitem(w_args_25, gi_1) - w_35 = space.setattr(w_self_24, gs_strerror, w_34) - w_self_29, w_args_30, w_argc_31 = w_self_24, w_args_25, w_argc_26 - goto = 5 - - if goto == 5: - w_36 = space.eq(w_argc_31, gi_3) - v37 = space.is_true(w_36) - if v37 == True: - (w_self_38, w_args_39, w_argc_40, w_41, w_42) = (w_self_29, - w_args_30, w_argc_31, w_36, v37) - goto = 6 - else: - assert v37 == False - w_43 = space.w_None - goto = 7 - - if goto == 6: - w_44 = space.getitem(w_args_39, gi_2) - w_45 = space.setattr(w_self_38, gs_filename, w_44) - w_46 = space.getitem(w_args_39, gi_0) - w_47 = space.getitem(w_args_39, gi_1) - w_48 = space.newtuple([w_46, w_47]) - w_49 = space.setattr(w_self_38, gs_args, w_48) - w_43 = space.w_None - goto = 7 - - if goto == 7: - return w_43 -fastf_EnvironmentError___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 108 -##SECTION## -# global declarations -# global object gs_errno -# global object gs_errno_ -# global object gs_strerror -# global object gs_strerror_ -# global object gs_filename_ -# global object gbltinmethod_join_1 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_EnvironmentError___str__(space, w_self_1) -f_EnvironmentError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None - w_15=w_15=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_errno) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_errno_, w_2) - w_4 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) - w_6 = space.add(gs_args_, w_5) - w_7 = space.getattr(w_self_1, gs_strerror) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) - w_9 = space.add(gs_strerror_, w_8) - w_10 = space.getattr(w_self_1, gs_filename) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) - w_12 = space.add(gs_filename_, w_11) - w_13 = space.newlist([w_3, w_6, w_9, w_12]) - _tup = space.newtuple([w_13]) - w_res_14 = space.call(gbltinmethod_join_1, _tup) - w_15 = w_res_14 - goto = 2 - - if goto == 2: - return w_15 -fastf_EnvironmentError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 128 -##SECTION## -# global declaration -# global object gi_5 - -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) -f_UnicodeEncodeError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None - w_22=w_22=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_5) - v5 = space.is_true(w_4) - if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) - goto = 2 - else: - assert v5 == False - w_12 = space.w_None - goto = 3 - - if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_encoding, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_object, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_start, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_end, w_19) - w_21 = space.getitem(w_args_7, gi_4) - w_22 = space.setattr(w_self_6, gs_reason, w_21) - w_12 = space.w_None - goto = 3 - - if goto == 3: - return w_12 -fastf_UnicodeEncodeError___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 139 -##SECTION## -# global declarations -# global object gs_encoding -# global object gs_encoding_ -# global object gbltinmethod_join_3 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___str__(space, w_self_1) -f_UnicodeEncodeError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_object) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self_1, gs_end) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) - w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self_1, gs_encoding) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) - w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) - w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self_1, gs_start) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) - w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self_1, gs_reason) - _tup = space.newtuple([w_16]) - w_17 = space.call(space.w_str, _tup) - w_18 = space.add(gs_reason_, w_17) - w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) - _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join_3, _tup) - w_21 = w_res_20 - goto = 2 - - if goto == 2: - return w_21 -fastf_UnicodeEncodeError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 179 -##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SyntaxError___init__(space, w_self_3, w_args_1) -f_SyntaxError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=None - v18=v18=w_24=w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=None - w_27=w_27=w_28=w_29=w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=None - w_args_7=w_args_7=w_argc_8=w_9=w_10=w_11=w_15=w_16=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.ge(w_argc_0, gi_1) - v5 = space.is_true(w_4) - if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) - goto = 2 - else: - assert v5 == False - w_self_12, w_args_13, w_argc_14 = w_self_3, w_args_1, w_argc_0 - goto = 3 - - if goto == 2: - w_15 = space.getitem(w_args_7, gi_0) - w_16 = space.setattr(w_self_6, gs_msg, w_15) - w_self_12, w_args_13, w_argc_14 = w_self_6, w_args_7, w_argc_8 - goto = 3 - - if goto == 3: - w_17 = space.eq(w_argc_14, gi_2) - v18 = space.is_true(w_17) - if v18 == True: - (w_self_19, w_args_20, w_argc_21, w_22, w_23) = (w_self_12, - w_args_13, w_argc_14, w_17, v18) - goto = 4 - else: - assert v18 == False - w_24 = space.w_None - goto = 5 - - if goto == 4: - w_25 = space.getitem(w_args_20, gi_1) - w_26 = space.getitem(w_25, gi_0) - w_27 = space.setattr(w_self_19, gs_filename, w_26) - w_28 = space.getitem(w_args_20, gi_1) - w_29 = space.getitem(w_28, gi_1) - w_30 = space.setattr(w_self_19, gs_lineno, w_29) - w_31 = space.getitem(w_args_20, gi_1) - w_32 = space.getitem(w_31, gi_2) - w_33 = space.setattr(w_self_19, gs_offset, w_32) - w_34 = space.getitem(w_args_20, gi_1) - w_35 = space.getitem(w_34, gi_3) - w_36 = space.setattr(w_self_19, gs_text, w_35) - w_24 = space.w_None - goto = 5 - - if goto == 5: - return w_24 -fastf_SyntaxError___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 191 -##SECTION## -# global declaration -# global object gbltinmethod_join_2 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SyntaxError___str__(space, w_self_1) -f_SyntaxError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_res_5=w_6=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_args_, w_2) - w_4 = space.newlist([w_3]) - _tup = space.newtuple([w_4]) - w_res_5 = space.call(gbltinmethod_join_2, _tup) - w_6 = w_res_5 - goto = 2 - - if goto == 2: - return w_6 -fastf_SyntaxError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 205 -##SECTION## -# global declaration -# global object gs_code - -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_4, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SystemExit___init__(space, w_self_4, w_args_1) -f_SystemExit___init__ = globals().pop("__init__") - -def __init__(space, w_self_4, w_args_1): - - w_argc_0=w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=None - v16=v16=w_self_23=w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=None - w_args_31=w_args_31=w_argc_32=w_33=w_34=w_36=w_self_17=w_args_18=None - w_argc_19=w_argc_19=w_20=w_21=w_22=w_26=w_27=w_self_5=w_args_6=None - w_argc_7=w_argc_7=w_8=w_9=w_13=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.eq(w_argc_0, gi_0) - v3 = space.is_true(w_2) - if v3 == True: - (w_self_5, w_args_6, w_argc_7, w_8, w_9) = (w_self_4, w_args_1, - w_argc_0, w_2, v3) - goto = 2 - else: - assert v3 == False - w_self_10, w_args_11, w_argc_12 = w_self_4, w_args_1, w_argc_0 - goto = 3 - - if goto == 2: - w_13 = space.setattr(w_self_5, gs_code, space.w_None) - w_self_10, w_args_11, w_argc_12 = w_self_5, w_args_6, w_argc_7 - goto = 3 - - if goto == 3: - w_14 = space.setattr(w_self_10, gs_args, w_args_11) - w_15 = space.eq(w_argc_12, gi_1) - v16 = space.is_true(w_15) - if v16 == True: - (w_self_17, w_args_18, w_argc_19, w_20, w_21, w_22) = (w_self_10, - w_args_11, w_argc_12, w_14, w_15, v16) - goto = 4 - else: - assert v16 == False - w_self_23, w_args_24, w_argc_25 = w_self_10, w_args_11, w_argc_12 - goto = 5 - - if goto == 4: - w_26 = space.getitem(w_args_18, gi_0) - w_27 = space.setattr(w_self_17, gs_code, w_26) - w_self_23, w_args_24, w_argc_25 = w_self_17, w_args_18, w_argc_19 - goto = 5 - - if goto == 5: - w_28 = space.ge(w_argc_25, gi_2) - v29 = space.is_true(w_28) - if v29 == True: - (w_self_30, w_args_31, w_argc_32, w_33, w_34) = (w_self_23, - w_args_24, w_argc_25, w_28, v29) - goto = 6 - else: - assert v29 == False - w_35 = space.w_None - goto = 7 - - if goto == 6: - w_36 = space.setattr(w_self_30, gs_code, w_args_31) - w_35 = space.w_None - goto = 7 - - if goto == 7: - return w_35 -fastf_SystemExit___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__init__' -## firstlineno 240 -##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeDecodeError___init__(space, w_self_3, w_args_1) -f_UnicodeDecodeError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None - w_22=w_22=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_5) - v5 = space.is_true(w_4) - if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) - goto = 2 - else: - assert v5 == False - w_12 = space.w_None - goto = 3 - - if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_encoding, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_object, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_start, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_end, w_19) - w_21 = space.getitem(w_args_7, gi_4) - w_22 = space.setattr(w_self_6, gs_reason, w_21) - w_12 = space.w_None - goto = 3 - - if goto == 3: - return w_12 -fastf_UnicodeDecodeError___init__ = globals().pop("__init__") - -##SECTION## -## filename 'd:\\pypy\\dist\\pypy\\appspace\\_exceptions.py' -## function '__str__' -## firstlineno 251 -##SECTION## -# global declaration -# global object gbltinmethod_join_4 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeDecodeError___str__(space, w_self_1) -f_UnicodeDecodeError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_object) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self_1, gs_end) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) - w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self_1, gs_encoding) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) - w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) - w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self_1, gs_start) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) - w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self_1, gs_reason) - _tup = space.newtuple([w_16]) - w_17 = space.call(space.w_str, _tup) - w_18 = space.add(gs_reason_, w_17) - w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) - _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join_4, _tup) - w_21 = w_res_20 - goto = 2 - - if goto == 2: - return w_21 -fastf_UnicodeDecodeError___str__ = globals().pop("__str__") - -##SECTION## -#************************************************************* - -def inittest_exceptions_1(space): - """NOT_RPYTHON""" - class m: pass # fake module - m.__dict__ = globals() - - from pypy.interpreter.gateway import interp2app - m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) - m.g48dict = space.newdict([]) - m.gs_keys = space.wrap('keys') - m.gbltinmethod_keys = space.getattr(g48dict, gs_keys) - from pypy.translator.geninterplevel import PyArg_ParseMini - m.PyArg_ParseMini = PyArg_ParseMini - from pypy.interpreter.error import OperationError - m.OperationError = OperationError - m.gs_MemoryError = space.wrap('MemoryError') - _dic = space.newdict([]) - m.gs___module__ = space.wrap('__module__') - m.gs_pypy_appspace__exceptions = space.wrap('pypy.appspace._exceptions') - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - m.gs___doc__ = space.wrap('__doc__') - _doc = space.wrap("""Common base class for all exceptions.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_Exception = space.wrap('Exception') - _bases = space.newtuple([]) - _args = space.newtuple([gs_Exception, _bases, _dic]) - m.gcls_Exception = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for all standard Python exceptions.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_StandardError = space.wrap('StandardError') - _bases = space.newtuple([gcls_Exception]) - _args = space.newtuple([gs_StandardError, _bases, _dic]) - m.gcls_StandardError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Out of memory.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_MemoryError, _bases, _dic]) - m.gcls_MemoryError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_MemoryError, gcls_MemoryError) - m.gs_ImportError = space.wrap('ImportError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Import can't find module, or can't find name in module.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_ImportError, _bases, _dic]) - m.gcls_ImportError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_ImportError, gcls_ImportError) - m.gs_RuntimeError = space.wrap('RuntimeError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Unspecified run-time error.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_RuntimeError, _bases, _dic]) - m.gcls_RuntimeError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_RuntimeError, gcls_RuntimeError) - m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Inappropriate argument value (of correct type).""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_ValueError = space.wrap('ValueError') - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_ValueError, _bases, _dic]) - m.gcls_ValueError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Unicode related error.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_UnicodeError = space.wrap('UnicodeError') - _bases = space.newtuple([gcls_ValueError]) - _args = space.newtuple([gs_UnicodeError, _bases, _dic]) - m.gcls_UnicodeError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Unicode translation error.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_UnicodeError]) - _args = space.newtuple([gs_UnicodeTranslateError, _bases, _dic]) - m.gcls_UnicodeTranslateError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) - m.gs_KeyError = space.wrap('KeyError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for lookup errors.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_LookupError = space.wrap('LookupError') - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_LookupError, _bases, _dic]) - m.gcls_LookupError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Mapping key not found.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_LookupError]) - _args = space.newtuple([gs_KeyError, _bases, _dic]) - m.gcls_KeyError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_KeyError, gcls_KeyError) - m.gs_SyntaxWarning = space.wrap('SyntaxWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warning categories.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_Warning = space.wrap('Warning') - _bases = space.newtuple([gcls_Exception]) - _args = space.newtuple([gs_Warning, _bases, _dic]) - m.gcls_Warning = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about dubious syntax.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) - m.gcls_SyntaxWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_SyntaxWarning, gcls_SyntaxWarning) - m.gs_StopIteration = space.wrap('StopIteration') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Signal the end from iterator.next().""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Exception]) - _args = space.newtuple([gs_StopIteration, _bases, _dic]) - m.gcls_StopIteration = space.call(space.w_type, _args) - space.setitem(g48dict, gs_StopIteration, gcls_StopIteration) - m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) - m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) - m.gs_EnvironmentError = space.wrap('EnvironmentError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for I/O related errors.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_EnvironmentError, _bases, _dic]) - m.gcls_EnvironmentError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_EnvironmentError, gcls_EnvironmentError) - m.gs_SyntaxError = space.wrap('SyntaxError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Invalid syntax.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_SyntaxError, _bases, _dic]) - m.gcls_SyntaxError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_SyntaxError, gcls_SyntaxError) - space.setitem(g48dict, gs_LookupError, gcls_LookupError) - m.gs_OSError = space.wrap('OSError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""OS system call failed.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_EnvironmentError]) - _args = space.newtuple([gs_OSError, _bases, _dic]) - m.gcls_OSError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_OSError, gcls_OSError) - m.gs_DeprecationWarning = space.wrap('DeprecationWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about deprecated features.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_DeprecationWarning, _bases, _dic]) - m.gcls_DeprecationWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_DeprecationWarning, gcls_DeprecationWarning) - space.setitem(g48dict, gs_UnicodeError, gcls_UnicodeError) - m.gs_FloatingPointError = space.wrap('FloatingPointError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for arithmetic errors.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_ArithmeticError = space.wrap('ArithmeticError') - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_ArithmeticError, _bases, _dic]) - m.gcls_ArithmeticError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Floating point operation failed.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_ArithmeticError]) - _args = space.newtuple([gs_FloatingPointError, _bases, _dic]) - m.gcls_FloatingPointError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_FloatingPointError, gcls_FloatingPointError) - m.gs_ReferenceError = space.wrap('ReferenceError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Weak ref proxy used after referent went away.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_ReferenceError, _bases, _dic]) - m.gcls_ReferenceError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_ReferenceError, gcls_ReferenceError) - m.gs_NameError = space.wrap('NameError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Name not found globally.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_NameError, _bases, _dic]) - m.gcls_NameError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_NameError, gcls_NameError) - m.gs_OverflowWarning = space.wrap('OverflowWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about numeric overflow.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_OverflowWarning, _bases, _dic]) - m.gcls_OverflowWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_OverflowWarning, gcls_OverflowWarning) - m.gs_IOError = space.wrap('IOError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""I/O operation failed.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_EnvironmentError]) - _args = space.newtuple([gs_IOError, _bases, _dic]) - m.gcls_IOError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_IOError, gcls_IOError) - space.setitem(g48dict, gs_ValueError, gcls_ValueError) - m.gs_FutureWarning = space.wrap('FutureWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about constructs that will change semantically in the future.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_FutureWarning, _bases, _dic]) - m.gcls_FutureWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_FutureWarning, gcls_FutureWarning) - m.gs_SystemExit = space.wrap('SystemExit') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Request to exit from the interpreter.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Exception]) - _args = space.newtuple([gs_SystemExit, _bases, _dic]) - m.gcls_SystemExit = space.call(space.w_type, _args) - space.setitem(g48dict, gs_SystemExit, gcls_SystemExit) - space.setitem(g48dict, gs_Exception, gcls_Exception) - m.gs_EOFError = space.wrap('EOFError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Read beyond end of file.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_EOFError, _bases, _dic]) - m.gcls_EOFError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_EOFError, gcls_EOFError) - space.setitem(g48dict, gs_StandardError, gcls_StandardError) - m.gs___file__ = space.wrap('__file__') - m.gs_D___pypy__dist__pypy__appspace__ = space.wrap('D:\\pypy\\dist\\pypy\\appspace\\_exceptions.pyc') - space.setitem(g48dict, gs___file__, gs_D___pypy__dist__pypy__appspace__) - m.gs_TabError = space.wrap('TabError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Improper indentation.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_IndentationError = space.wrap('IndentationError') - _bases = space.newtuple([gcls_SyntaxError]) - _args = space.newtuple([gs_IndentationError, _bases, _dic]) - m.gcls_IndentationError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Improper mixture of spaces and tabs.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_IndentationError]) - _args = space.newtuple([gs_TabError, _bases, _dic]) - m.gcls_TabError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_TabError, gcls_TabError) - m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Second argument to a division or modulo operation was zero.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_ArithmeticError]) - _args = space.newtuple([gs_ZeroDivisionError, _bases, _dic]) - m.gcls_ZeroDivisionError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) - m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Unicode encoding error.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_UnicodeError]) - _args = space.newtuple([gs_UnicodeEncodeError, _bases, _dic]) - m.gcls_UnicodeEncodeError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) - m.gs_SystemError = space.wrap('SystemError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Internal error in the Python interpreter. - - Please report this to the Python maintainer, along with the traceback, - the Python version, and the hardware/OS platform and version.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_SystemError, _bases, _dic]) - m.gcls_SystemError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_SystemError, gcls_SystemError) - m.gs___name__ = space.wrap('__name__') - space.setitem(g48dict, gs___name__, gs_pypy_appspace__exceptions) - space.setitem(g48dict, gs_IndentationError, gcls_IndentationError) - m.gs_AssertionError = space.wrap('AssertionError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Assertion failed.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_AssertionError, _bases, _dic]) - m.gcls_AssertionError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_AssertionError, gcls_AssertionError) - m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Unicode decoding error.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_UnicodeError]) - _args = space.newtuple([gs_UnicodeDecodeError, _bases, _dic]) - m.gcls_UnicodeDecodeError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) - m.gs_TypeError = space.wrap('TypeError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Inappropriate argument type.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_TypeError, _bases, _dic]) - m.gcls_TypeError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_TypeError, gcls_TypeError) - m.gs_IndexError = space.wrap('IndexError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Sequence index out of range.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_LookupError]) - _args = space.newtuple([gs_IndexError, _bases, _dic]) - m.gcls_IndexError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_IndexError, gcls_IndexError) - m.gs_RuntimeWarning = space.wrap('RuntimeWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about dubious runtime behavior.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_RuntimeWarning, _bases, _dic]) - m.gcls_RuntimeWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_RuntimeWarning, gcls_RuntimeWarning) - m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Program interrupted by user.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_KeyboardInterrupt, _bases, _dic]) - m.gcls_KeyboardInterrupt = space.call(space.w_type, _args) - space.setitem(g48dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) - space.setitem(g48dict, gs___doc__, space.w_None) - m.gs_UserWarning = space.wrap('UserWarning') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings generated by user code.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_UserWarning, _bases, _dic]) - m.gcls_UserWarning = space.call(space.w_type, _args) - space.setitem(g48dict, gs_UserWarning, gcls_UserWarning) - m.gs_TaskletExit = space.wrap('TaskletExit') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Request to exit from a tasklet.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_SystemExit]) - _args = space.newtuple([gs_TaskletExit, _bases, _dic]) - m.gcls_TaskletExit = space.call(space.w_type, _args) - space.setitem(g48dict, gs_TaskletExit, gcls_TaskletExit) - m.gs_UnboundLocalError = space.wrap('UnboundLocalError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Local name referenced but not bound to a value.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_NameError]) - _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) - m.gcls_UnboundLocalError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_UnboundLocalError, gcls_UnboundLocalError) - space.setitem(g48dict, gs_ArithmeticError, gcls_ArithmeticError) - space.setitem(g48dict, gs_Warning, gcls_Warning) - m.gs_NotImplementedError = space.wrap('NotImplementedError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Method or function hasn't been implemented yet.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_RuntimeError]) - _args = space.newtuple([gs_NotImplementedError, _bases, _dic]) - m.gcls_NotImplementedError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_NotImplementedError, gcls_NotImplementedError) - m.gs_AttributeError = space.wrap('AttributeError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Attribute not found.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_AttributeError, _bases, _dic]) - m.gcls_AttributeError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_AttributeError, gcls_AttributeError) - m.gs_OverflowError = space.wrap('OverflowError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Result too large to be represented.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_ArithmeticError]) - _args = space.newtuple([gs_OverflowError, _bases, _dic]) - m.gcls_OverflowError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_OverflowError, gcls_OverflowError) - m.gs_WindowsError = space.wrap('WindowsError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""MS-Windows OS system call failed.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_OSError]) - _args = space.newtuple([gs_WindowsError, _bases, _dic]) - m.gcls_WindowsError = space.call(space.w_type, _args) - space.setitem(g48dict, gs_WindowsError, gcls_WindowsError) - m.gs___init__ = space.wrap('__init__') - m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) - space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) - m.gs___str__ = space.wrap('__str__') - m.gfunc_UnicodeDecodeError___str__ = space.wrap(interp2app(f_UnicodeDecodeError___str__)) - space.setattr(gcls_UnicodeDecodeError, gs___str__, gfunc_UnicodeDecodeError___str__) - m.gfunc_UnicodeEncodeError___init__ = space.wrap(interp2app(f_UnicodeEncodeError___init__)) - space.setattr(gcls_UnicodeEncodeError, gs___init__, gfunc_UnicodeEncodeError___init__) - m.gfunc_UnicodeEncodeError___str__ = space.wrap(interp2app(f_UnicodeEncodeError___str__)) - space.setattr(gcls_UnicodeEncodeError, gs___str__, gfunc_UnicodeEncodeError___str__) - m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) - space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) - m.gfunc_SyntaxError___init__ = space.wrap(interp2app(f_SyntaxError___init__)) - space.setattr(gcls_SyntaxError, gs___init__, gfunc_SyntaxError___init__) - m.gfunc_SyntaxError___str__ = space.wrap(interp2app(f_SyntaxError___str__)) - space.setattr(gcls_SyntaxError, gs___str__, gfunc_SyntaxError___str__) - m.gs_filename = space.wrap('filename') - space.setattr(gcls_SyntaxError, gs_filename, space.w_None) - m.gs_lineno = space.wrap('lineno') - space.setattr(gcls_SyntaxError, gs_lineno, space.w_None) - m.gs_msg = space.wrap('msg') - m.gs__emptystr_ = space.wrap('') - space.setattr(gcls_SyntaxError, gs_msg, gs__emptystr_) - m.gs_offset = space.wrap('offset') - space.setattr(gcls_SyntaxError, gs_offset, space.w_None) - m.gs_print_file_and_line = space.wrap('print_file_and_line') - space.setattr(gcls_SyntaxError, gs_print_file_and_line, space.w_None) - m.gs_text = space.wrap('text') - space.setattr(gcls_SyntaxError, gs_text, space.w_None) - m.gfunc_EnvironmentError___init__ = space.wrap(interp2app(f_EnvironmentError___init__)) - space.setattr(gcls_EnvironmentError, gs___init__, gfunc_EnvironmentError___init__) - m.gfunc_EnvironmentError___str__ = space.wrap(interp2app(f_EnvironmentError___str__)) - space.setattr(gcls_EnvironmentError, gs___str__, gfunc_EnvironmentError___str__) - m.gfunc_KeyError___str__ = space.wrap(interp2app(f_KeyError___str__)) - space.setattr(gcls_KeyError, gs___str__, gfunc_KeyError___str__) - m.gfunc_UnicodeTranslateError___init__ = space.wrap(interp2app(f_UnicodeTranslateError___init__)) - space.setattr(gcls_UnicodeTranslateError, gs___init__, gfunc_UnicodeTranslateError___init__) - m.gfunc_UnicodeTranslateError___str__ = space.wrap(interp2app(f_UnicodeTranslateError___str__)) - space.setattr(gcls_UnicodeTranslateError, gs___str__, gfunc_UnicodeTranslateError___str__) - m.gs___getitem__ = space.wrap('__getitem__') - m.gfunc_Exception___getitem__ = space.wrap(interp2app(f_Exception___getitem__)) - space.setattr(gcls_Exception, gs___getitem__, gfunc_Exception___getitem__) - m.gfunc_Exception___init__ = space.wrap(interp2app(f_Exception___init__)) - space.setattr(gcls_Exception, gs___init__, gfunc_Exception___init__) - m.gfunc_Exception___str__ = space.wrap(interp2app(f_Exception___str__)) - space.setattr(gcls_Exception, gs___str__, gfunc_Exception___str__) - m.gs_args = space.wrap('args') - m.gi_0 = space.newint(0) - m.gi_1 = space.newint(1) - m.gs_start = space.wrap('start') - m.gs_start_ = space.wrap('start=') - m.gs_reason = space.wrap('reason') - m.gs_reason_ = space.wrap('reason=') - m.gs_args_ = space.wrap('args=') - m.gs_end = space.wrap('end') - m.gs_end_ = space.wrap('end=') - m.gs_object = space.wrap('object') - m.gs_object_ = space.wrap('object=') - m.gs__ = space.wrap(' ') - m.gs_join = space.wrap('join') - m.gbltinmethod_join = space.getattr(gs__, gs_join) - m.gi_4 = space.newint(4) - m.gi_2 = space.newint(2) - m.gi_3 = space.newint(3) - m.gs_errno = space.wrap('errno') - m.gs_errno_ = space.wrap('errno=') - m.gs_strerror = space.wrap('strerror') - m.gs_strerror_ = space.wrap('strerror=') - m.gs_filename_ = space.wrap('filename=') - m.gbltinmethod_join_1 = space.getattr(gs__, gs_join) - m.gbltinmethod_join_2 = space.getattr(gs__, gs_join) - m.gs_code = space.wrap('code') - m.gs_encoding = space.wrap('encoding') - m.gs_encoding_ = space.wrap('encoding=') - m.gbltinmethod_join_3 = space.getattr(gs__, gs_join) - m.gi_5 = space.newint(5) - m.gbltinmethod_join_4 = space.getattr(gs__, gs_join) - -# entry point: test_exceptions, gfunc_test_exceptions) -if __name__ == "__main__": - from pypy.objspace.std import StdObjSpace - space = StdObjSpace() - inittest_exceptions_1(space) - print space.unwrap(space.call( - gfunc_test_exceptions, space.newtuple([]))) - +#!/bin/env python +# -*- coding: LATIN-1 -*- +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__getitem__' +## firstlineno 5 +##SECTION## +def __getitem__(space, *args_w): + kwlist = ["self", "idx"] + _args_w = args_w + defaults_w = () + funcname = "__getitem__" + w_self_1, w_idx_3 = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) + return fastf_Exception___getitem__(space, w_self_1, w_idx_3) +f_Exception___getitem__ = globals().pop("__getitem__") + +def __getitem__(space, w_self_1, w_idx_3): + + w_0=w_0=w_2=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_2 = space.getitem(w_0, w_idx_3) + w_4 = w_2 + goto = 2 + + if goto == 2: + return w_4 +fastf_Exception___getitem__ = globals().pop("__getitem__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 9 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_2 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___init__(space, w_self_1, w_args_2) +f_Exception___init__ = globals().pop("__init__") + +def __init__(space, w_self_1, w_args_2): + + w_0=w_0=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.setattr(w_self_1, gs_args, w_args_2) + w_3 = space.w_None + goto = 2 + + if goto == 2: + return w_3 +fastf_Exception___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 13 +##SECTION## +# global declarations +# global object gs_args +# global object gi_0 +# global object gi_1 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___str__(space, w_self_1) +f_Exception___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None + w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None + w_14=w_14=w_15=w_19=w_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_argc_2 = space.len(w_0) + w_3 = space.eq(w_argc_2, gi_0) + v4 = space.is_true(w_3) + if v4 == True: + w_5 = gs__emptystr_ + goto = 5 + else: + assert v4 == False + w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + goto = 2 + + if goto == 2: + w_9 = space.eq(w_argc_7, gi_1) + v10 = space.is_true(w_9) + if v10 == True: + (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, + w_8, w_9, v10) + goto = 3 + else: + assert v10 == False + w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + goto = 4 + + if goto == 3: + w_19 = space.getattr(w_self_11, gs_args) + w_20 = space.getitem(w_19, gi_0) + _tup = space.newtuple([w_20]) + w_21 = space.call(space.w_str, _tup) + w_5 = w_21 + goto = 5 + + if goto == 4: + w_22 = space.getattr(w_self_16, gs_args) + _tup = space.newtuple([w_22]) + w_23 = space.call(space.w_str, _tup) + w_5 = w_23 + goto = 5 + + if goto == 5: + return w_5 +fastf_Exception___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 41 +##SECTION## +# global declarations +# global object gi_4 +# global object gi_2 +# global object gi_3 + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___init__(space, w_self_3, w_args_1) +f_UnicodeTranslateError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_4) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_object, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_start, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_end, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_reason, w_19) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeTranslateError___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 51 +##SECTION## +# global declarations +# global object gs_start +# global object gs_start_ +# global object gs_reason +# global object gs_reason_ +# global object gs_args_ +# global object gs_end +# global object gs_end_ +# global object gs_object +# global object gs_object_ +# global object gbltinmethod_join +# global object gs__ +# global object gs_join + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___str__(space, w_self_1) +f_UnicodeTranslateError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_res_17=w_18=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_start_, w_2) + w_4 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_reason_, w_5) + w_7 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_args_, w_8) + w_10 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_end_, w_11) + w_13 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_object_, w_14) + w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) + _tup = space.newtuple([w_16]) + w_res_17 = space.call(gbltinmethod_join, _tup) + w_18 = w_res_17 + goto = 2 + + if goto == 2: + return w_18 +fastf_UnicodeTranslateError___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 69 +##SECTION## +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_KeyError___str__(space, w_self_1) +f_KeyError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None + w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None + w_14=w_14=w_15=w_19=w_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + w_argc_2 = space.len(w_0) + w_3 = space.eq(w_argc_2, gi_0) + v4 = space.is_true(w_3) + if v4 == True: + w_5 = gs__emptystr_ + goto = 5 + else: + assert v4 == False + w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + goto = 2 + + if goto == 2: + w_9 = space.eq(w_argc_7, gi_1) + v10 = space.is_true(w_9) + if v10 == True: + (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, + w_8, w_9, v10) + goto = 3 + else: + assert v10 == False + w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + goto = 4 + + if goto == 3: + w_19 = space.getattr(w_self_11, gs_args) + w_20 = space.getitem(w_19, gi_0) + w_21 = space.repr(w_20) + w_5 = w_21 + goto = 5 + + if goto == 4: + w_22 = space.getattr(w_self_16, gs_args) + _tup = space.newtuple([w_22]) + w_23 = space.call(space.w_str, _tup) + w_5 = w_23 + goto = 5 + + if goto == 5: + return w_5 +fastf_KeyError___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 91 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___init__(space, w_self_3, w_args_1) +f_EnvironmentError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=None + w_argc_20=w_argc_20=w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=None + v37=v37=w_43=w_self_38=w_args_39=w_argc_40=w_41=w_42=w_44=w_45=None + w_46=w_46=w_47=w_48=w_49=w_self_24=w_args_25=w_argc_26=w_27=w_28=None + w_32=w_32=w_33=w_34=w_35=w_self_9=w_args_10=w_argc_11=w_12=w_13=None + w_14=w_14=w_15=w_16=w_17=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.setattr(w_self_3, gs_errno, space.w_None) + w_5 = space.setattr(w_self_3, gs_strerror, space.w_None) + w_6 = space.setattr(w_self_3, gs_filename, space.w_None) + w_7 = space.le(gi_2, w_argc_0) + v8 = space.is_true(w_7) + if v8 == True: + (w_self_9, w_args_10, w_argc_11, w_12, w_13, w_14, w_15, w_16, + w_17) = (w_self_3, w_args_1, w_argc_0, w_2, w_4, w_5, w_6, w_7, + v8) + goto = 2 + else: + assert v8 == False + (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_3, w_args_1, + w_argc_0, w_7) + goto = 3 + + if goto == 2: + w_22 = space.le(w_argc_11, gi_3) + (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_9, w_args_10, + w_argc_11, w_22) + goto = 3 + + if goto == 3: + v23 = space.is_true(w_21) + if v23 == True: + (w_self_24, w_args_25, w_argc_26, w_27, w_28) = (w_self_18, + w_args_19, w_argc_20, w_21, v23) + goto = 4 + else: + assert v23 == False + w_self_29, w_args_30, w_argc_31 = w_self_18, w_args_19, w_argc_20 + goto = 5 + + if goto == 4: + w_32 = space.getitem(w_args_25, gi_0) + w_33 = space.setattr(w_self_24, gs_errno, w_32) + w_34 = space.getitem(w_args_25, gi_1) + w_35 = space.setattr(w_self_24, gs_strerror, w_34) + w_self_29, w_args_30, w_argc_31 = w_self_24, w_args_25, w_argc_26 + goto = 5 + + if goto == 5: + w_36 = space.eq(w_argc_31, gi_3) + v37 = space.is_true(w_36) + if v37 == True: + (w_self_38, w_args_39, w_argc_40, w_41, w_42) = (w_self_29, + w_args_30, w_argc_31, w_36, v37) + goto = 6 + else: + assert v37 == False + w_43 = space.w_None + goto = 7 + + if goto == 6: + w_44 = space.getitem(w_args_39, gi_2) + w_45 = space.setattr(w_self_38, gs_filename, w_44) + w_46 = space.getitem(w_args_39, gi_0) + w_47 = space.getitem(w_args_39, gi_1) + w_48 = space.newtuple([w_46, w_47]) + w_49 = space.setattr(w_self_38, gs_args, w_48) + w_43 = space.w_None + goto = 7 + + if goto == 7: + return w_43 +fastf_EnvironmentError___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 105 +##SECTION## +# global declarations +# global object gs_errno +# global object gs_errno_ +# global object gs_strerror +# global object gs_strerror_ +# global object gs_filename_ +# global object gbltinmethod_join_1 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___str__(space, w_self_1) +f_EnvironmentError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None + w_15=w_15=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_errno) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_errno_, w_2) + w_4 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_args_, w_5) + w_7 = space.getattr(w_self_1, gs_strerror) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_strerror_, w_8) + w_10 = space.getattr(w_self_1, gs_filename) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_filename_, w_11) + w_13 = space.newlist([w_3, w_6, w_9, w_12]) + _tup = space.newtuple([w_13]) + w_res_14 = space.call(gbltinmethod_join_1, _tup) + w_15 = w_res_14 + goto = 2 + + if goto == 2: + return w_15 +fastf_EnvironmentError___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 149 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___init__(space, w_self_3, w_args_1) +f_SyntaxError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=None + v18=v18=w_24=w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=None + w_27=w_27=w_28=w_29=w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=None + w_args_7=w_args_7=w_argc_8=w_9=w_10=w_11=w_15=w_16=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.ge(w_argc_0, gi_1) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_self_12, w_args_13, w_argc_14 = w_self_3, w_args_1, w_argc_0 + goto = 3 + + if goto == 2: + w_15 = space.getitem(w_args_7, gi_0) + w_16 = space.setattr(w_self_6, gs_msg, w_15) + w_self_12, w_args_13, w_argc_14 = w_self_6, w_args_7, w_argc_8 + goto = 3 + + if goto == 3: + w_17 = space.eq(w_argc_14, gi_2) + v18 = space.is_true(w_17) + if v18 == True: + (w_self_19, w_args_20, w_argc_21, w_22, w_23) = (w_self_12, + w_args_13, w_argc_14, w_17, v18) + goto = 4 + else: + assert v18 == False + w_24 = space.w_None + goto = 5 + + if goto == 4: + w_25 = space.getitem(w_args_20, gi_1) + w_26 = space.getitem(w_25, gi_0) + w_27 = space.setattr(w_self_19, gs_filename, w_26) + w_28 = space.getitem(w_args_20, gi_1) + w_29 = space.getitem(w_28, gi_1) + w_30 = space.setattr(w_self_19, gs_lineno, w_29) + w_31 = space.getitem(w_args_20, gi_1) + w_32 = space.getitem(w_31, gi_2) + w_33 = space.setattr(w_self_19, gs_offset, w_32) + w_34 = space.getitem(w_args_20, gi_1) + w_35 = space.getitem(w_34, gi_3) + w_36 = space.setattr(w_self_19, gs_text, w_35) + w_24 = space.w_None + goto = 5 + + if goto == 5: + return w_24 +fastf_SyntaxError___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 161 +##SECTION## +# global declaration +# global object gbltinmethod_join_2 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___str__(space, w_self_1) +f_SyntaxError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_res_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_args_, w_2) + w_4 = space.newlist([w_3]) + _tup = space.newtuple([w_4]) + w_res_5 = space.call(gbltinmethod_join_2, _tup) + w_6 = w_res_5 + goto = 2 + + if goto == 2: + return w_6 +fastf_SyntaxError___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 175 +##SECTION## +# global declaration +# global object gs_code + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_4, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SystemExit___init__(space, w_self_4, w_args_1) +f_SystemExit___init__ = globals().pop("__init__") + +def __init__(space, w_self_4, w_args_1): + + w_argc_0=w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=None + v16=v16=w_self_23=w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=None + w_args_31=w_args_31=w_argc_32=w_33=w_34=w_36=w_self_17=w_args_18=None + w_argc_19=w_argc_19=w_20=w_21=w_22=w_26=w_27=w_self_5=w_args_6=None + w_argc_7=w_argc_7=w_8=w_9=w_13=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.eq(w_argc_0, gi_0) + v3 = space.is_true(w_2) + if v3 == True: + (w_self_5, w_args_6, w_argc_7, w_8, w_9) = (w_self_4, w_args_1, + w_argc_0, w_2, v3) + goto = 2 + else: + assert v3 == False + w_self_10, w_args_11, w_argc_12 = w_self_4, w_args_1, w_argc_0 + goto = 3 + + if goto == 2: + w_13 = space.setattr(w_self_5, gs_code, space.w_None) + w_self_10, w_args_11, w_argc_12 = w_self_5, w_args_6, w_argc_7 + goto = 3 + + if goto == 3: + w_14 = space.setattr(w_self_10, gs_args, w_args_11) + w_15 = space.eq(w_argc_12, gi_1) + v16 = space.is_true(w_15) + if v16 == True: + (w_self_17, w_args_18, w_argc_19, w_20, w_21, w_22) = (w_self_10, + w_args_11, w_argc_12, w_14, w_15, v16) + goto = 4 + else: + assert v16 == False + w_self_23, w_args_24, w_argc_25 = w_self_10, w_args_11, w_argc_12 + goto = 5 + + if goto == 4: + w_26 = space.getitem(w_args_18, gi_0) + w_27 = space.setattr(w_self_17, gs_code, w_26) + w_self_23, w_args_24, w_argc_25 = w_self_17, w_args_18, w_argc_19 + goto = 5 + + if goto == 5: + w_28 = space.ge(w_argc_25, gi_2) + v29 = space.is_true(w_28) + if v29 == True: + (w_self_30, w_args_31, w_argc_32, w_33, w_34) = (w_self_23, + w_args_24, w_argc_25, w_28, v29) + goto = 6 + else: + assert v29 == False + w_35 = space.w_None + goto = 7 + + if goto == 6: + w_36 = space.setattr(w_self_30, gs_code, w_args_31) + w_35 = space.w_None + goto = 7 + + if goto == 7: + return w_35 +fastf_SystemExit___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 210 +##SECTION## +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___init__(space, w_self_3, w_args_1) +f_UnicodeDecodeError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None + w_22=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_5) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_encoding, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_object, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_start, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_end, w_19) + w_21 = space.getitem(w_args_7, gi_4) + w_22 = space.setattr(w_self_6, gs_reason, w_21) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeDecodeError___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 221 +##SECTION## +# global declaration +# global object gbltinmethod_join_4 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___str__(space, w_self_1) +f_UnicodeDecodeError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_object_, w_2) + w_4 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_end_, w_5) + w_7 = space.getattr(w_self_1, gs_encoding) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_encoding_, w_8) + w_10 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_args_, w_11) + w_13 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_start_, w_14) + w_16 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_16]) + w_17 = space.call(space.w_str, _tup) + w_18 = space.add(gs_reason_, w_17) + w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) + _tup = space.newtuple([w_19]) + w_res_20 = space.call(gbltinmethod_join_4, _tup) + w_21 = w_res_20 + goto = 2 + + if goto == 2: + return w_21 +fastf_UnicodeDecodeError___str__ = globals().pop("__str__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__init__' +## firstlineno 270 +##SECTION## +# global declaration +# global object gi_5 + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) +f_UnicodeEncodeError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None + w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None + w_22=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_5) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_encoding, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_object, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_start, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_end, w_19) + w_21 = space.getitem(w_args_7, gi_4) + w_22 = space.setattr(w_self_6, gs_reason, w_21) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeEncodeError___init__ = globals().pop("__init__") + +##SECTION## +## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## function '__str__' +## firstlineno 281 +##SECTION## +# global declarations +# global object gs_encoding +# global object gs_encoding_ +# global object gbltinmethod_join_3 + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___str__(space, w_self_1) +f_UnicodeEncodeError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_object_, w_2) + w_4 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_end_, w_5) + w_7 = space.getattr(w_self_1, gs_encoding) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_encoding_, w_8) + w_10 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_args_, w_11) + w_13 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_start_, w_14) + w_16 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_16]) + w_17 = space.call(space.w_str, _tup) + w_18 = space.add(gs_reason_, w_17) + w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) + _tup = space.newtuple([w_19]) + w_res_20 = space.call(gbltinmethod_join_3, _tup) + w_21 = w_res_20 + goto = 2 + + if goto == 2: + return w_21 +fastf_UnicodeEncodeError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'geninterplevel.py' +## function 'test_exceptions' +## firstlineno 1253 +##SECTION## +# global declarations +# global object gfunc_test_exceptions +# global object gbltinmethod_keys +# global object g46dict +# global object gs_keys + +def test_exceptions(space, *args_w): + """ enumerate all exceptions """ + kwlist = [] + _args_w = args_w + defaults_w = () + funcname = "test_exceptions" + PyArg_ParseMini(space, funcname, 0, 0, _args_w, defaults_w) + return fastf_test_exceptions(space, ) +f_test_exceptions = globals().pop("test_exceptions") + +def test_exceptions(space, ): + """ enumerate all exceptions """ + + w_0=w_0=w_1=None + + goto = 1 # startblock + while True: + + if goto == 1: + _tup = space.newtuple([]) + w_0 = space.call(gbltinmethod_keys, _tup) + w_1 = w_0 + goto = 2 + + if goto == 2: + return w_1 +fastf_test_exceptions = globals().pop("test_exceptions") + +# global declarations +# global object gs_MemoryError +# global object gcls_MemoryError +# global object gcls_StandardError +# global object gcls_Exception +# global object gs___module__ +# global object gs_pypy_appspace__exceptions +# global object gs___doc__ +# global object gs_Exception +# global object gs_StandardError +# global object gs_ImportError +# global object gcls_ImportError +# global object gs_RuntimeError +# global object gcls_RuntimeError +# global object gs_UnicodeTranslateError +# global object gcls_UnicodeTranslateError +# global object gcls_UnicodeError +# global object gcls_ValueError +# global object gs_ValueError +# global object gs_UnicodeError +# global object gs_KeyError +# global object gcls_KeyError +# global object gcls_LookupError +# global object gs_LookupError +# global object gs_StopIteration +# global object gcls_StopIteration +# global object gs_SyntaxWarning +# global object gcls_SyntaxWarning +# global object gcls_Warning +# global object gs_Warning +# global object gs_EnvironmentError +# global object gcls_EnvironmentError +# global object gs_OSError +# global object gcls_OSError +# global object gs_DeprecationWarning +# global object gcls_DeprecationWarning +# global object gs_FloatingPointError +# global object gcls_FloatingPointError +# global object gcls_ArithmeticError +# global object gs_ArithmeticError +# global object gs_ReferenceError +# global object gcls_ReferenceError +# global object gs_NameError +# global object gcls_NameError +# global object gs_OverflowWarning +# global object gcls_OverflowWarning +# global object gs_IOError +# global object gcls_IOError +# global object gs_FutureWarning +# global object gcls_FutureWarning +# global object gs_ZeroDivisionError +# global object gcls_ZeroDivisionError +# global object gs_SystemExit +# global object gcls_SystemExit +# global object gs_EOFError +# global object gcls_EOFError +# global object gs___file__ +# global object gs__home_arigo_svn_pypy_dist_pypy_a +# global object gs_TabError +# global object gcls_TabError +# global object gcls_IndentationError +# global object gcls_SyntaxError +# global object gs_SyntaxError +# global object gs_IndentationError +# global object gs_UnicodeEncodeError +# global object gcls_UnicodeEncodeError +# global object gs_SystemError +# global object gcls_SystemError +# global object gs___name__ +# global object gs_AssertionError +# global object gcls_AssertionError +# global object gs_UnicodeDecodeError +# global object gcls_UnicodeDecodeError +# global object gs_TypeError +# global object gcls_TypeError +# global object gs_IndexError +# global object gcls_IndexError +# global object gs_RuntimeWarning +# global object gcls_RuntimeWarning +# global object gs_KeyboardInterrupt +# global object gcls_KeyboardInterrupt +# global object gs_UserWarning +# global object gcls_UserWarning +# global object gs_PendingDeprecationWarning +# global object gcls_PendingDeprecationWarning +# global object gs_UnboundLocalError +# global object gcls_UnboundLocalError +# global object gs_NotImplementedError +# global object gcls_NotImplementedError +# global object gs_AttributeError +# global object gcls_AttributeError +# global object gs_OverflowError +# global object gcls_OverflowError +# global object gs___init__ +# global object gfunc_UnicodeDecodeError___init__ +# global object gs___str__ +# global object gfunc_UnicodeDecodeError___str__ +# global object gfunc_UnicodeEncodeError___init__ +# global object gfunc_UnicodeEncodeError___str__ +# global object gfunc_SyntaxError___init__ +# global object gfunc_SyntaxError___str__ +# global object gs_filename +# global object gs_lineno +# global object gs_msg +# global object gs__emptystr_ +# global object gs_offset +# global object gs_print_file_and_line +# global object gs_text +# global object gfunc_SystemExit___init__ +# global object gfunc_EnvironmentError___init__ +# global object gfunc_EnvironmentError___str__ +# global object gfunc_KeyError___str__ +# global object gfunc_UnicodeTranslateError___init__ +# global object gfunc_UnicodeTranslateError___str__ +# global object gs___getitem__ +# global object gfunc_Exception___getitem__ +# global object gfunc_Exception___init__ +# global object gfunc_Exception___str__ + +##SECTION## +#************************************************************* + +def inittest_exceptions_1(space): + """NOT_RPYTHON""" + class m: pass # fake module + m.__dict__ = globals() + + from pypy.interpreter.gateway import interp2app + m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) + m.g46dict = space.newdict([]) + m.gs_keys = space.wrap('keys') + m.gbltinmethod_keys = space.getattr(g46dict, gs_keys) + def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): + err = None + if len(args_w) < minargs: + txt = "%s() takes at least %d argument%s (%d given)" + plural = ['s', ''][minargs == 1] + err = (name, minargs, plural, len(args_w)) + if len(args_w) > maxargs: + plural = ['s', ''][maxargs == 1] + if minargs == maxargs: + if minargs == 0: + txt = '%s() takes no arguments (%d given)' + err = (name, len(args_w)) + elif minargs == 1: + txt = '%s() takes exactly %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + else: + txt = '%s() takes at most %d argument%s (%d given)' + err = (name, maxargs, plural, len(args_w)) + if err: + w_txt = space.wrap(txt) + w_tup = space.wrap(err) + w_txt = space.mod(w_txt, w_tup) + raise OperationError(space.w_TypeError, w_txt) + + # finally, we create the result ;-) + res_w = args_w + defaults_w[len(args_w) - minargs:] + assert len(res_w) == maxargs + return res_w + + m.PyArg_ParseMini = PyArg_ParseMini + from pypy.interpreter.error import OperationError + m.OperationError = OperationError + m.gs_MemoryError = space.wrap('MemoryError') + _dic = space.newdict([]) + m.gs___module__ = space.wrap('__module__') + m.gs_pypy_appspace__exceptions = space.wrap('pypy.appspace._exceptions') + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + m.gs___doc__ = space.wrap('__doc__') + _doc = space.wrap("""Common base class for all exceptions.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_Exception = space.wrap('Exception') + _bases = space.newtuple([]) + _args = space.newtuple([gs_Exception, _bases, _dic]) + m.gcls_Exception = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for all standard Python exceptions.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_StandardError = space.wrap('StandardError') + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_StandardError, _bases, _dic]) + m.gcls_StandardError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Out of memory.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_MemoryError, _bases, _dic]) + m.gcls_MemoryError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_MemoryError, gcls_MemoryError) + m.gs_ImportError = space.wrap('ImportError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Import can't find module, or can't find name in module.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ImportError, _bases, _dic]) + m.gcls_ImportError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_ImportError, gcls_ImportError) + m.gs_RuntimeError = space.wrap('RuntimeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unspecified run-time error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_RuntimeError, _bases, _dic]) + m.gcls_RuntimeError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_RuntimeError, gcls_RuntimeError) + m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Inappropriate argument value (of correct type).""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_ValueError = space.wrap('ValueError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ValueError, _bases, _dic]) + m.gcls_ValueError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode related error.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_UnicodeError = space.wrap('UnicodeError') + _bases = space.newtuple([gcls_ValueError]) + _args = space.newtuple([gs_UnicodeError, _bases, _dic]) + m.gcls_UnicodeError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode translation error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeTranslateError, _bases, _dic]) + m.gcls_UnicodeTranslateError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) + m.gs_KeyError = space.wrap('KeyError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for lookup errors.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_LookupError = space.wrap('LookupError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_LookupError, _bases, _dic]) + m.gcls_LookupError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Mapping key not found.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_LookupError]) + _args = space.newtuple([gs_KeyError, _bases, _dic]) + m.gcls_KeyError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_KeyError, gcls_KeyError) + m.gs_StopIteration = space.wrap('StopIteration') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Signal the end from iterator.next().""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_StopIteration, _bases, _dic]) + m.gcls_StopIteration = space.call(space.w_type, _args) + space.setitem(g46dict, gs_StopIteration, gcls_StopIteration) + m.gs_SyntaxWarning = space.wrap('SyntaxWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warning categories.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_Warning = space.wrap('Warning') + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_Warning, _bases, _dic]) + m.gcls_Warning = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about dubious syntax.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) + m.gcls_SyntaxWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_SyntaxWarning, gcls_SyntaxWarning) + m.gs_EnvironmentError = space.wrap('EnvironmentError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for I/O related errors.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_EnvironmentError, _bases, _dic]) + m.gcls_EnvironmentError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_EnvironmentError, gcls_EnvironmentError) + space.setitem(g46dict, gs_LookupError, gcls_LookupError) + m.gs_OSError = space.wrap('OSError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""OS system call failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_EnvironmentError]) + _args = space.newtuple([gs_OSError, _bases, _dic]) + m.gcls_OSError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_OSError, gcls_OSError) + m.gs_DeprecationWarning = space.wrap('DeprecationWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about deprecated features.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_DeprecationWarning, _bases, _dic]) + m.gcls_DeprecationWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_DeprecationWarning, gcls_DeprecationWarning) + space.setitem(g46dict, gs_UnicodeError, gcls_UnicodeError) + m.gs_FloatingPointError = space.wrap('FloatingPointError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for arithmetic errors.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_ArithmeticError = space.wrap('ArithmeticError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ArithmeticError, _bases, _dic]) + m.gcls_ArithmeticError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Floating point operation failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_FloatingPointError, _bases, _dic]) + m.gcls_FloatingPointError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_FloatingPointError, gcls_FloatingPointError) + m.gs_ReferenceError = space.wrap('ReferenceError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Weak ref proxy used after referent went away.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ReferenceError, _bases, _dic]) + m.gcls_ReferenceError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_ReferenceError, gcls_ReferenceError) + m.gs_NameError = space.wrap('NameError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Name not found globally.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_NameError, _bases, _dic]) + m.gcls_NameError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_NameError, gcls_NameError) + m.gs_OverflowWarning = space.wrap('OverflowWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about numeric overflow.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_OverflowWarning, _bases, _dic]) + m.gcls_OverflowWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_OverflowWarning, gcls_OverflowWarning) + m.gs_IOError = space.wrap('IOError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""I/O operation failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_EnvironmentError]) + _args = space.newtuple([gs_IOError, _bases, _dic]) + m.gcls_IOError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_IOError, gcls_IOError) + space.setitem(g46dict, gs_ValueError, gcls_ValueError) + m.gs_FutureWarning = space.wrap('FutureWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about constructs that will change semantically in the future.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_FutureWarning, _bases, _dic]) + m.gcls_FutureWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_FutureWarning, gcls_FutureWarning) + m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Second argument to a division or modulo operation was zero.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_ZeroDivisionError, _bases, _dic]) + m.gcls_ZeroDivisionError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) + m.gs_SystemExit = space.wrap('SystemExit') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Request to exit from the interpreter.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_SystemExit, _bases, _dic]) + m.gcls_SystemExit = space.call(space.w_type, _args) + space.setitem(g46dict, gs_SystemExit, gcls_SystemExit) + space.setitem(g46dict, gs_Exception, gcls_Exception) + m.gs_EOFError = space.wrap('EOFError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Read beyond end of file.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_EOFError, _bases, _dic]) + m.gcls_EOFError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_EOFError, gcls_EOFError) + space.setitem(g46dict, gs_StandardError, gcls_StandardError) + m.gs___file__ = space.wrap('__file__') + m.gs__home_arigo_svn_pypy_dist_pypy_a = space.wrap('/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.pyc') + space.setitem(g46dict, gs___file__, gs__home_arigo_svn_pypy_dist_pypy_a) + m.gs_TabError = space.wrap('TabError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Invalid syntax.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_SyntaxError = space.wrap('SyntaxError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_SyntaxError, _bases, _dic]) + m.gcls_SyntaxError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Improper indentation.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_IndentationError = space.wrap('IndentationError') + _bases = space.newtuple([gcls_SyntaxError]) + _args = space.newtuple([gs_IndentationError, _bases, _dic]) + m.gcls_IndentationError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Improper mixture of spaces and tabs.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_IndentationError]) + _args = space.newtuple([gs_TabError, _bases, _dic]) + m.gcls_TabError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_TabError, gcls_TabError) + space.setitem(g46dict, gs_SyntaxError, gcls_SyntaxError) + m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode encoding error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeEncodeError, _bases, _dic]) + m.gcls_UnicodeEncodeError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) + m.gs_SystemError = space.wrap('SystemError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Internal error in the Python interpreter. + + Please report this to the Python maintainer, along with the traceback, + the Python version, and the hardware/OS platform and version.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_SystemError, _bases, _dic]) + m.gcls_SystemError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_SystemError, gcls_SystemError) + m.gs___name__ = space.wrap('__name__') + space.setitem(g46dict, gs___name__, gs_pypy_appspace__exceptions) + space.setitem(g46dict, gs_IndentationError, gcls_IndentationError) + m.gs_AssertionError = space.wrap('AssertionError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Assertion failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_AssertionError, _bases, _dic]) + m.gcls_AssertionError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_AssertionError, gcls_AssertionError) + m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Unicode decoding error.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_UnicodeError]) + _args = space.newtuple([gs_UnicodeDecodeError, _bases, _dic]) + m.gcls_UnicodeDecodeError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) + m.gs_TypeError = space.wrap('TypeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Inappropriate argument type.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_TypeError, _bases, _dic]) + m.gcls_TypeError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_TypeError, gcls_TypeError) + m.gs_IndexError = space.wrap('IndexError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Sequence index out of range.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_LookupError]) + _args = space.newtuple([gs_IndexError, _bases, _dic]) + m.gcls_IndexError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_IndexError, gcls_IndexError) + m.gs_RuntimeWarning = space.wrap('RuntimeWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about dubious runtime behavior.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_RuntimeWarning, _bases, _dic]) + m.gcls_RuntimeWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_RuntimeWarning, gcls_RuntimeWarning) + m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Program interrupted by user.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_KeyboardInterrupt, _bases, _dic]) + m.gcls_KeyboardInterrupt = space.call(space.w_type, _args) + space.setitem(g46dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) + space.setitem(g46dict, gs___doc__, space.w_None) + m.gs_UserWarning = space.wrap('UserWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings generated by user code.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_UserWarning, _bases, _dic]) + m.gcls_UserWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_UserWarning, gcls_UserWarning) + m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_Warning]) + _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) + m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) + space.setitem(g46dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) + m.gs_UnboundLocalError = space.wrap('UnboundLocalError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Local name referenced but not bound to a value.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_NameError]) + _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) + m.gcls_UnboundLocalError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_UnboundLocalError, gcls_UnboundLocalError) + space.setitem(g46dict, gs_ArithmeticError, gcls_ArithmeticError) + space.setitem(g46dict, gs_Warning, gcls_Warning) + m.gs_NotImplementedError = space.wrap('NotImplementedError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Method or function hasn't been implemented yet.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_RuntimeError]) + _args = space.newtuple([gs_NotImplementedError, _bases, _dic]) + m.gcls_NotImplementedError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_NotImplementedError, gcls_NotImplementedError) + m.gs_AttributeError = space.wrap('AttributeError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Attribute not found.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_AttributeError, _bases, _dic]) + m.gcls_AttributeError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_AttributeError, gcls_AttributeError) + m.gs_OverflowError = space.wrap('OverflowError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + _doc = space.wrap("""Result too large to be represented.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_ArithmeticError]) + _args = space.newtuple([gs_OverflowError, _bases, _dic]) + m.gcls_OverflowError = space.call(space.w_type, _args) + space.setitem(g46dict, gs_OverflowError, gcls_OverflowError) + m.gs___init__ = space.wrap('__init__') + m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) + space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) + m.gs___str__ = space.wrap('__str__') + m.gfunc_UnicodeDecodeError___str__ = space.wrap(interp2app(f_UnicodeDecodeError___str__)) + space.setattr(gcls_UnicodeDecodeError, gs___str__, gfunc_UnicodeDecodeError___str__) + m.gfunc_UnicodeEncodeError___init__ = space.wrap(interp2app(f_UnicodeEncodeError___init__)) + space.setattr(gcls_UnicodeEncodeError, gs___init__, gfunc_UnicodeEncodeError___init__) + m.gfunc_UnicodeEncodeError___str__ = space.wrap(interp2app(f_UnicodeEncodeError___str__)) + space.setattr(gcls_UnicodeEncodeError, gs___str__, gfunc_UnicodeEncodeError___str__) + m.gfunc_SyntaxError___init__ = space.wrap(interp2app(f_SyntaxError___init__)) + space.setattr(gcls_SyntaxError, gs___init__, gfunc_SyntaxError___init__) + m.gfunc_SyntaxError___str__ = space.wrap(interp2app(f_SyntaxError___str__)) + space.setattr(gcls_SyntaxError, gs___str__, gfunc_SyntaxError___str__) + m.gs_filename = space.wrap('filename') + space.setattr(gcls_SyntaxError, gs_filename, space.w_None) + m.gs_lineno = space.wrap('lineno') + space.setattr(gcls_SyntaxError, gs_lineno, space.w_None) + m.gs_msg = space.wrap('msg') + m.gs__emptystr_ = space.wrap('') + space.setattr(gcls_SyntaxError, gs_msg, gs__emptystr_) + m.gs_offset = space.wrap('offset') + space.setattr(gcls_SyntaxError, gs_offset, space.w_None) + m.gs_print_file_and_line = space.wrap('print_file_and_line') + space.setattr(gcls_SyntaxError, gs_print_file_and_line, space.w_None) + m.gs_text = space.wrap('text') + space.setattr(gcls_SyntaxError, gs_text, space.w_None) + m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) + space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) + m.gfunc_EnvironmentError___init__ = space.wrap(interp2app(f_EnvironmentError___init__)) + space.setattr(gcls_EnvironmentError, gs___init__, gfunc_EnvironmentError___init__) + m.gfunc_EnvironmentError___str__ = space.wrap(interp2app(f_EnvironmentError___str__)) + space.setattr(gcls_EnvironmentError, gs___str__, gfunc_EnvironmentError___str__) + m.gfunc_KeyError___str__ = space.wrap(interp2app(f_KeyError___str__)) + space.setattr(gcls_KeyError, gs___str__, gfunc_KeyError___str__) + m.gfunc_UnicodeTranslateError___init__ = space.wrap(interp2app(f_UnicodeTranslateError___init__)) + space.setattr(gcls_UnicodeTranslateError, gs___init__, gfunc_UnicodeTranslateError___init__) + m.gfunc_UnicodeTranslateError___str__ = space.wrap(interp2app(f_UnicodeTranslateError___str__)) + space.setattr(gcls_UnicodeTranslateError, gs___str__, gfunc_UnicodeTranslateError___str__) + m.gs___getitem__ = space.wrap('__getitem__') + m.gfunc_Exception___getitem__ = space.wrap(interp2app(f_Exception___getitem__)) + space.setattr(gcls_Exception, gs___getitem__, gfunc_Exception___getitem__) + m.gfunc_Exception___init__ = space.wrap(interp2app(f_Exception___init__)) + space.setattr(gcls_Exception, gs___init__, gfunc_Exception___init__) + m.gfunc_Exception___str__ = space.wrap(interp2app(f_Exception___str__)) + space.setattr(gcls_Exception, gs___str__, gfunc_Exception___str__) + m.gs_args = space.wrap('args') + m.gi_0 = space.newint(0) + m.gi_1 = space.newint(1) + m.gs_start = space.wrap('start') + m.gs_start_ = space.wrap('start=') + m.gs_reason = space.wrap('reason') + m.gs_reason_ = space.wrap('reason=') + m.gs_args_ = space.wrap('args=') + m.gs_end = space.wrap('end') + m.gs_end_ = space.wrap('end=') + m.gs_object = space.wrap('object') + m.gs_object_ = space.wrap('object=') + m.gs__ = space.wrap(' ') + m.gs_join = space.wrap('join') + m.gbltinmethod_join = space.getattr(gs__, gs_join) + m.gi_4 = space.newint(4) + m.gi_2 = space.newint(2) + m.gi_3 = space.newint(3) + m.gs_errno = space.wrap('errno') + m.gs_errno_ = space.wrap('errno=') + m.gs_strerror = space.wrap('strerror') + m.gs_strerror_ = space.wrap('strerror=') + m.gs_filename_ = space.wrap('filename=') + m.gbltinmethod_join_1 = space.getattr(gs__, gs_join) + m.gs_code = space.wrap('code') + m.gbltinmethod_join_2 = space.getattr(gs__, gs_join) + m.gs_encoding = space.wrap('encoding') + m.gs_encoding_ = space.wrap('encoding=') + m.gbltinmethod_join_3 = space.getattr(gs__, gs_join) + m.gi_5 = space.newint(5) + m.gbltinmethod_join_4 = space.getattr(gs__, gs_join) + +# entry point: test_exceptions, gfunc_test_exceptions) +if __name__ == "__main__": + from pypy.objspace.std import StdObjSpace + space = StdObjSpace() + inittest_exceptions_1(space) + print space.unwrap(space.call( + gfunc_test_exceptions, space.newtuple([]))) + Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Fri Jan 28 11:10:39 2005 @@ -24,7 +24,7 @@ """ from __future__ import generators -import autopath, os, sys, exceptions +import autopath, os, sys, exceptions, inspect from pypy.objspace.flow.model import Variable, Constant, SpaceOperation from pypy.objspace.flow.model import FunctionGraph, Block, Link from pypy.objspace.flow.model import last_exception, last_exc_value @@ -889,7 +889,7 @@ print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) theargs = [arg for arg in fast_args if arg != varname] - txt = ('from pypy.translator.geninterplevel import PyArg_ParseMini\n' + txt = inspect.getsource(PyArg_ParseMini) + ('\n' 'm.PyArg_ParseMini = PyArg_ParseMini\n' 'from pypy.interpreter.error import OperationError\n' 'm.OperationError = OperationError') @@ -1291,7 +1291,7 @@ gen.use_fast_call = True import pypy.appspace.generated as tmp pth = os.path.dirname(tmp.__file__) - ftmpname = "d:/tmp/look.py" + ftmpname = "/tmp/look.py" fname = os.path.join(pth, gen.modname+".py") gen.gen_source(fname, ftmpname) From ac at codespeak.net Fri Jan 28 11:26:39 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 28 Jan 2005 11:26:39 +0100 (MET) Subject: [pypy-svn] r8653 - pypy/dist/lib-python-2.3.4 Message-ID: <20050128102639.9A0BF27B90@code1.codespeak.net> Author: ac Date: Fri Jan 28 11:26:39 2005 New Revision: 8653 Modified: pypy/dist/lib-python-2.3.4/_file.py Log: Implement file.readinto() so that our file passes the cpython tests. Modified: pypy/dist/lib-python-2.3.4/_file.py ============================================================================== --- pypy/dist/lib-python-2.3.4/_file.py (original) +++ pypy/dist/lib-python-2.3.4/_file.py Fri Jan 28 11:26:39 2005 @@ -1,4 +1,5 @@ import sio +from array import array class file_(object): """An implementation of file objects in Python. it relies on Guido's @@ -116,3 +117,14 @@ for line in seq: self.write(line) + def readinto(self, a=None): + 'Obsolete method, do not use it.' + if self._closed: + raise ValueError('I/O operation on closed file') + if type(a) != array: + raise TypeError('Can only read into array objects') + i = 0 + for char in self.read(len(a)): + a[i] = char + i += 1 + return i From ac at codespeak.net Fri Jan 28 12:12:59 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 28 Jan 2005 12:12:59 +0100 (MET) Subject: [pypy-svn] r8657 - in pypy/dist/pypy/module: . test Message-ID: <20050128111259.062EC27B92@code1.codespeak.net> Author: ac Date: Fri Jan 28 12:12:58 2005 New Revision: 8657 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_zip.py Log: Have zip match python 2.3 and 2.4 behaviour as appropriate. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Fri Jan 28 12:12:58 2005 @@ -144,6 +144,9 @@ ignoring the trailing items in the other collections.""" if len(collections) == 0: + import sys + if sys.version_info < (2,4): + raise TypeError("zip() requires at least one sequence") return [] res = [] iterators = [ iter(collection) for collection in collections ] Modified: pypy/dist/pypy/module/test/test_zip.py ============================================================================== --- pypy/dist/pypy/module/test/test_zip.py (original) +++ pypy/dist/pypy/module/test/test_zip.py Fri Jan 28 12:12:58 2005 @@ -3,6 +3,12 @@ class AppTestZip: def test_zip_no_arguments(self): + import sys + if sys.version_info < (2,4): + # Test 2.3 behaviour + raises(TypeError, zip) + return + # Test 2.4 behaviour assert zip() == [] assert zip(*[]) == [] From arigo at codespeak.net Fri Jan 28 13:23:58 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 28 Jan 2005 13:23:58 +0100 (MET) Subject: [pypy-svn] r8661 - pypy/dist/pypy/interpreter Message-ID: <20050128122358.0ED3F27B95@code1.codespeak.net> Author: arigo Date: Fri Jan 28 13:23:57 2005 New Revision: 8661 Modified: pypy/dist/pypy/interpreter/error.py Log: Disable ANSI color codes by default on Windows. Better solution welcome. Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Fri Jan 28 13:23:57 2005 @@ -137,7 +137,7 @@ def debug_print(text, file=None): if file is None: file = sys.stderr text = text.rstrip() - if file.isatty(): + if sys.platform != "win32" and file.isatty(): text = ('\x1b[31m' + # ANSI color code "red" text + '\x1b[0m') # ANSI color code "reset" From tismer at codespeak.net Fri Jan 28 14:05:48 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 28 Jan 2005 14:05:48 +0100 (MET) Subject: [pypy-svn] r8662 - pypy/dist/pypy/objspace/std Message-ID: <20050128130548.350E127B97@code1.codespeak.net> Author: tismer Date: Fri Jan 28 14:05:48 2005 New Revision: 8662 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: small cleanup to the way exceptions are initialized. There is much more to be done... Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Fri Jan 28 14:05:48 2005 @@ -207,7 +207,6 @@ ##for_builtins.update(self.clone_exception_hierarchy()) ## hacking things in from pypy.module import exceptionsinterp as ex - hold = self.call def call(w_type, w_args): space = self # too early for unpackiterable as well :-( @@ -222,6 +221,7 @@ return res w_dic = self.newdict([]) try: + # note that we hide the real call method by an instance variable! self.call = call ex.inittest_exceptions_1(self) for name, w_obj in ex.__dict__.items(): @@ -231,10 +231,10 @@ for_builtins[excname] = w_obj # into builtins self.setitem(w_dic, self.wrap(excname), w_obj) # into exc finally: - self.call = hold + del self.call # revert to the class' method self.make_builtins(for_builtins) - # XXX refine things,clean up, create a builtin module... + # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module m = Module(self, self.wrap("exceptions"), w_dic) From hpk at codespeak.net Fri Jan 28 17:28:53 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 28 Jan 2005 17:28:53 +0100 (MET) Subject: [pypy-svn] r8665 - in pypy/dist: lib-2.3.4 lib-python-2.3.4 pypy/lib pypy/lib/test pypy/module Message-ID: <20050128162853.9169D27B97@code1.codespeak.net> Author: hpk Date: Fri Jan 28 17:28:53 2005 New Revision: 8665 Added: pypy/dist/lib-2.3.4/ - copied from r8664, vendor/cpython/Python-r234/dist/src/Lib/ pypy/dist/pypy/lib/ (props changed) pypy/dist/pypy/lib/_exceptions.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/_exceptions.py pypy/dist/pypy/lib/_file.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/_file.py pypy/dist/pypy/lib/_float_formatting.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/_float_formatting.py pypy/dist/pypy/lib/_formatting.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/_formatting.py pypy/dist/pypy/lib/_types.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/_types.py pypy/dist/pypy/lib/cStringIO.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/cStringIO.py pypy/dist/pypy/lib/cmath.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/cmath.py pypy/dist/pypy/lib/dumbre.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/dumbre.py pypy/dist/pypy/lib/imp.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/imp.py pypy/dist/pypy/lib/md5.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/md5.py pypy/dist/pypy/lib/operator.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/operator.py pypy/dist/pypy/lib/plexre.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/plexre.py pypy/dist/pypy/lib/sha.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/sha.py pypy/dist/pypy/lib/sio.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/sio.py pypy/dist/pypy/lib/sre_parse.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/sre_parse.py pypy/dist/pypy/lib/struct.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/struct.py pypy/dist/pypy/lib/test/ (props changed) pypy/dist/pypy/lib/test/__init__.py (contents, props changed) pypy/dist/pypy/lib/test/conftest.py (contents, props changed) pypy/dist/pypy/lib/test/pystone.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/test/pystone.py pypy/dist/pypy/lib/test/test_sio.py - copied, changed from r8660, pypy/dist/lib-python-2.3.4/test/test_sio.py pypy/dist/pypy/lib/types.py - copied unchanged from r8660, pypy/dist/lib-python-2.3.4/types.py Removed: pypy/dist/lib-python-2.3.4/ Modified: pypy/dist/pypy/module/sysinterp.py Log: ok, after discussion with armin, samuele and christian this is the first step to implement the new structure: dist/lib-2.3.4 (soon to be dist/lib-python-2.3.4.) contains the original cpython 2.3.4 library + tests dist/pypy/lib contains the pypy overrides and modifications at applevel dist/pypy/module contains the pypy overrides at interplevel Probably we'll discover that we want to do it slightly differently at some point but this should provide a sane starting point and more exact references ... Added: pypy/dist/pypy/lib/test/__init__.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/test/__init__.py Fri Jan 28 17:28:53 2005 @@ -0,0 +1 @@ +# Added: pypy/dist/pypy/lib/test/conftest.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/test/conftest.py Fri Jan 28 17:28:53 2005 @@ -0,0 +1,5 @@ +import py + +class Directory(py.test.collect.Directory): + def __iter__(self): + return iter([]) Copied: pypy/dist/pypy/lib/test/test_sio.py (from r8660, pypy/dist/lib-python-2.3.4/test/test_sio.py) ============================================================================== --- pypy/dist/lib-python-2.3.4/test/test_sio.py (original) +++ pypy/dist/pypy/lib/test/test_sio.py Fri Jan 28 17:28:53 2005 @@ -4,8 +4,6 @@ import time from pypy.tool.udir import udir -from pypy.appspace import sio - class TestSource(object): def __init__(self, packets): Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Fri Jan 28 17:28:53 2005 @@ -61,14 +61,15 @@ import os from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) -appdir = os.path.join(autopath.pypydir, 'appspace') -python_std_lib = os.path.join(autopath.pypydir, '..','lib-python-2.3.4') +python_std_lib = os.path.normpath( + os.path.join(autopath.pypydir, '..','lib-2.3.4')) +pypy_override_lib = os.path.join(autopath.pypydir, 'lib') assert os.path.exists(python_std_lib) del os, autopath # XXX for the translator. Something is very wrong around here. w_initialpath = space.newlist([space.wrap(''), + space.wrap(pypy_override_lib), space.wrap(python_std_lib), - #space.wrap(appdir), ] + [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) From hpk at codespeak.net Fri Jan 28 17:32:41 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 28 Jan 2005 17:32:41 +0100 (MET) Subject: [pypy-svn] r8666 - in pypy/dist: lib-2.3.4 lib-python-2.3.4 pypy/module Message-ID: <20050128163241.14FB827B96@code1.codespeak.net> Author: hpk Date: Fri Jan 28 17:32:40 2005 New Revision: 8666 Added: pypy/dist/lib-python-2.3.4/ - copied from r8665, pypy/dist/lib-2.3.4/ Removed: pypy/dist/lib-2.3.4/ Modified: pypy/dist/pypy/module/sysinterp.py Log: ok, and then move again to lib-python-2.3.4 because it is a more explicit name. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Fri Jan 28 17:32:40 2005 @@ -62,7 +62,7 @@ from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, '..','lib-2.3.4')) + os.path.join(autopath.pypydir, '..','lib-python-2.3.4')) pypy_override_lib = os.path.join(autopath.pypydir, 'lib') assert os.path.exists(python_std_lib) del os, autopath # XXX for the translator. Something is very wrong around here. From hpk at codespeak.net Fri Jan 28 18:08:53 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 28 Jan 2005 18:08:53 +0100 (MET) Subject: [pypy-svn] r8669 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050128170853.3AA4927B97@code1.codespeak.net> Author: hpk Date: Fri Jan 28 18:08:53 2005 New Revision: 8669 Added: pypy/dist/lib-python-2.3.4/test/conftest.py - copied unchanged from r8645, pypy/dist/lib-python-2.3.4/conftest.py pypy/dist/lib-python-2.3.4/test/pypy_unittest.py - copied unchanged from r8645, pypy/dist/lib-python-2.3.4/pypy_unittest.py Log: add minimal support for running cpython's (currently unmodified) regr-tests on applevel From ac at codespeak.net Fri Jan 28 18:09:58 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 28 Jan 2005 18:09:58 +0100 (MET) Subject: [pypy-svn] r8670 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050128170958.D207527B96@code1.codespeak.net> Author: ac Date: Fri Jan 28 18:09:58 2005 New Revision: 8670 Modified: pypy/dist/pypy/objspace/std/stringobject.py pypy/dist/pypy/objspace/std/test/test_stringobject.py Log: Handle the case of joining on an iterator that has unicode strings. Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Fri Jan 28 18:09:58 2005 @@ -334,7 +334,7 @@ if not space.is_true(space.isinstance(list[i], space.w_str)): if space.is_true(space.isinstance(list[i], space.w_unicode)): w_u = space.call_function(space.w_unicode, w_self) - return space.call_method(w_u, "join", w_list) + return space.call_method(w_u, "join", space.newlist(list)) raise OperationError( space.w_TypeError, space.wrap("sequence item %d: expected string, %s " Modified: pypy/dist/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_stringobject.py Fri Jan 28 18:09:58 2005 @@ -262,8 +262,7 @@ assert 'aaa'.count('a', -10) == 3 assert 'aaa'.count('a', 0, -1) == 2 assert 'aaa'.count('a', 0, -10) == 0 - - + def test_startswith(self): assert 'ab'.startswith('ab') == 1 assert 'ab'.startswith('a') == 1 @@ -375,6 +374,28 @@ raises(TypeError, ''.join, [1]) raises(TypeError, ''.join, [[1]]) + def test_unicode_join_endcase(self): + # This class inserts a Unicode object into its argument's natural + # iteration, in the 3rd position. + class OhPhooey: + def __init__(self, seq): + self.it = iter(seq) + self.i = 0 + + def __iter__(self): + return self + + def next(self): + i = self.i + self.i = i+1 + if i == 2: + return unicode("fooled you!") + return self.it.next() + + f = ('a\n', 'b\n', 'c\n') + got = " - ".join(OhPhooey(f)) + assert got == unicode("a\n - b\n - fooled you! - c\n") + def test_lower(self): assert "aaa AAA".lower() == "aaa aaa" assert "".lower() == "" From hpk at codespeak.net Fri Jan 28 18:13:10 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 28 Jan 2005 18:13:10 +0100 (MET) Subject: [pypy-svn] r8671 - in pypy/dist/pypy/lib: test test2 Message-ID: <20050128171310.CDC0827B96@code1.codespeak.net> Author: hpk Date: Fri Jan 28 18:13:10 2005 New Revision: 8671 Added: pypy/dist/pypy/lib/test2/ - copied from r8665, pypy/dist/pypy/lib/test/ Removed: pypy/dist/pypy/lib/test/ Log: move our override's lib/test out of the way because it interfers with lib-python-2.3.4/test From tismer at codespeak.net Fri Jan 28 18:48:02 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 28 Jan 2005 18:48:02 +0100 (MET) Subject: [pypy-svn] r8675 - pypy/dist/pypy/tool Message-ID: <20050128174802.9835D27B96@code1.codespeak.net> Author: tismer Date: Fri Jan 28 18:48:02 2005 New Revision: 8675 Added: pypy/dist/pypy/tool/sourcetools.py Log: extracting a few helpers which I need in multiple source generating applications Added: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/tool/sourcetools.py Fri Jan 28 18:48:02 2005 @@ -0,0 +1,23 @@ +# a couple of support functions which +# help with generating Python source. + +# this script is used for extracting +# the information available for exceptions +# via introspection. +# The idea is to use it once to create +# a template for a re-birth of exceptions.py + +def render_docstr(func, indent_str, q='"""', redo=True): + """render a docstring as a sequenceof lines """ + doc = func.__doc__ + if doc is None: + return [] + doc = indent_str + q + doc.replace(q, "\\"+q) + q + doc2 = doc + if q in doc and redo: + doc2 = render_docstr(func, indent_str, "'''", False) + if not redo: + return doc # recursion case + doc = (doc, doc2)[len(doc2) < len(doc)] + return [line for line in doc.split('\n')] + From hpk at codespeak.net Sat Jan 29 00:32:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 00:32:17 +0100 (MET) Subject: [pypy-svn] r8678 - pypy/dist/pypy/tool Message-ID: <20050128233217.A70AA27B96@code1.codespeak.net> Author: hpk Date: Sat Jan 29 00:32:17 2005 New Revision: 8678 Modified: pypy/dist/pypy/tool/fixeol Log: rewrote fixeol to be more careful (e.g. not modify eol-style if it is set already). It also now refuses to convert the content of a file because that leads to huge diffs that we usually don't want. This means that you need to run fixeol on the platform where the files were originally created. Modified: pypy/dist/pypy/tool/fixeol ============================================================================== --- pypy/dist/pypy/tool/fixeol (original) +++ pypy/dist/pypy/tool/fixeol Sat Jan 29 00:32:17 2005 @@ -1,7 +1,8 @@ #! /usr/bin/env python import sys, os - +import autopath +import py forbidden = range(0,32) forbidden.remove(9) # tab @@ -17,70 +18,81 @@ return True return False - -def binary2text(filename): - "Convert a file to the platform's native end-of-line format if needed." - f = open(filename, 'rb') - data = f.read() - f.close() - if looksbinary(data): - return False +def can_set_eol_style(path): + "check to see if we could set eol-style on the path." + data = path.read(mode='rb') + if looksbinary(data): + print "%s looks like a binary, ignoring" % path + return False original = data data = data.replace('\r\n', '\n') data = data.replace('\r', '\n') data = data.replace('\n', os.linesep) if data != original: - f = open(filename, 'wb') - f.write(data) - f.close() + print "*"*30 + print "---> %s <---" % path + print ("Hum, in order to run fixeol on this file " + "you need to be on the platform which " + "matches its line-endings. Modifying " + "the file content here would otherwise " + "lead to huge diffs!") + print "*"*30 + return False return True +def checkeolfile(path): + return path.ext in ('.txt', '.py', '.asc') -def asserttextfile(fname): - "Assert a file is a text file or issue a warning otherwise." - # safety check to nail binary files - try: - if not binary2text(fname): - print >> sys.stderr, "*** warning, looks like a binary file:", - print >> sys.stderr, fname - return - except IOError, e: - print "skipping %r because of %s" %(fname, e) - else: - # change end-of-line style of each .py and .txt file to 'native' - os.system('svn propset svn:eol-style native %s' % fname) - - -def fixpyfiles(ignored, dirname, fnames): - "Fix Python files in some directory." - numpyfiles = 0 - for fname in fnames: - if fname.endswith('.py') or fname.endswith('.txt') or fname.endswith('.asc'): - asserttextfile(os.path.join(dirname, fname)) - numpyfiles += 1 - if numpyfiles: - # ignore '*.pyc' and '*.pyo' in any directory containing .py files - g = os.popen('svn propget svn:ignore %s' % dirname) - content = g.readlines() - g.close() - oldlen = len(content) - if '*.pyc\n' not in content: - content.append('*.pyc\n') - if '*.pyo\n' not in content: - content.append('*.pyo\n') - if len(content) > oldlen: - g = open('svn-ignore.tmp', 'w') - g.writelines(content) - g.close() - os.system('svn propset svn:ignore -F svn-ignore.tmp %s' % dirname) - os.unlink('svn-ignore.tmp') - if '.svn' in fnames: - fnames.remove('.svn') - - +def fixdirectory(path): + print "+ checking directory", path, + fns = path.listdir(checkeolfile) + if fns: + ignores = path.propget('svn:ignore') + newignores = ignores + l = ignores.split('\n') + for x in ('*.pyc', '*.pyo'): + if x not in l: + l.append(x) + newignores = "\n".join(l) + print "setting ignores", newignores + path.propset('svn:ignore', newignores) + else: + print + for fn in fns: + fixfile(fn) + + for x in path.listdir(py.path.checker(dir=1, versioned=True)): + fixdirectory(x) + +def fixfile(path): + x = path.localpath.relto(py.path.local()) + if not x: + x = path.localpath + print "checking", x, + if path.check(versioned=0): + return False + oldprop = path.propget('svn:eol-style') + if oldprop: + print "eol-style already set (%r)" %(oldprop, ) + else: + if can_set_eol_style(path): + print "setting eol-style native" + path.propset('svn:eol-style', 'native') + else: + print "cannot set eol-style" + if __name__ == '__main__': if len(sys.argv) > 1: for fname in sys.argv[1:]: - asserttextfile(fname) + paths = [py.path.svnwc(x) for x in sys.argv[1:]] else: - os.path.walk(os.curdir, fixpyfiles, None) + paths = [py.path.svnwc()] + + for path in paths: + if path.check(dir=1): + fixdirectory(path) + elif path.check(file=1): + fixfile(path) + else: + print "ignoring", path + From hpk at codespeak.net Sat Jan 29 00:43:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 00:43:52 +0100 (MET) Subject: [pypy-svn] r8679 - in pypy/dist/lib-python-2.3.4: . bsddb bsddb/test compiler curses distutils distutils/command email email/test email/test/data encodings hotshot idlelib lib-old lib-tk logging plat-aix3 plat-aix4 plat-atheos plat-beos5 plat-darwin plat-freebsd2 plat-freebsd3 plat-freebsd4 plat-freebsd5 plat-irix5 plat-irix6 plat-linux1 plat-linux2 plat-mac plat-mac/Carbon plat-mac/lib-scriptpackages/CodeWarrior plat-mac/lib-scriptpackages/Explorer plat-mac/lib-scriptpackages/Finder plat-mac/lib-scriptpackages/Netscape plat-mac/lib-scriptpackages/StdSuites plat-mac/lib-scriptpackages/SystemEvents plat-mac/lib-scriptpackages/Terminal plat-mac/lib-scriptpackages/_builtinSuites plat-netbsd1 plat-os2emx plat-riscos plat-sunos4 plat-sunos5 plat-unixware7 test xml xml/dom xml/parsers xml/sax Message-ID: <20050128234352.099A527B96@code1.codespeak.net> Author: hpk Date: Sat Jan 29 00:43:52 2005 New Revision: 8679 Modified: pypy/dist/lib-python-2.3.4/ (props changed) pypy/dist/lib-python-2.3.4/BaseHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/Bastion.py (props changed) pypy/dist/lib-python-2.3.4/CGIHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/ConfigParser.py (props changed) pypy/dist/lib-python-2.3.4/Cookie.py (props changed) pypy/dist/lib-python-2.3.4/DocXMLRPCServer.py (props changed) pypy/dist/lib-python-2.3.4/FCNTL.py (props changed) pypy/dist/lib-python-2.3.4/HTMLParser.py (props changed) pypy/dist/lib-python-2.3.4/MimeWriter.py (props changed) pypy/dist/lib-python-2.3.4/Queue.py (props changed) pypy/dist/lib-python-2.3.4/SimpleHTTPServer.py (props changed) pypy/dist/lib-python-2.3.4/SimpleXMLRPCServer.py (props changed) pypy/dist/lib-python-2.3.4/SocketServer.py (props changed) pypy/dist/lib-python-2.3.4/StringIO.py (props changed) pypy/dist/lib-python-2.3.4/TERMIOS.py (props changed) pypy/dist/lib-python-2.3.4/UserDict.py (props changed) pypy/dist/lib-python-2.3.4/UserList.py (props changed) pypy/dist/lib-python-2.3.4/UserString.py (props changed) pypy/dist/lib-python-2.3.4/__future__.py (props changed) pypy/dist/lib-python-2.3.4/__phello__.foo.py (props changed) pypy/dist/lib-python-2.3.4/_strptime.py (props changed) pypy/dist/lib-python-2.3.4/aifc.py (props changed) pypy/dist/lib-python-2.3.4/anydbm.py (props changed) pypy/dist/lib-python-2.3.4/asynchat.py (props changed) pypy/dist/lib-python-2.3.4/asyncore.py (props changed) pypy/dist/lib-python-2.3.4/atexit.py (props changed) pypy/dist/lib-python-2.3.4/audiodev.py (props changed) pypy/dist/lib-python-2.3.4/base64.py (props changed) pypy/dist/lib-python-2.3.4/bdb.py (props changed) pypy/dist/lib-python-2.3.4/binhex.py (props changed) pypy/dist/lib-python-2.3.4/bisect.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/ (props changed) pypy/dist/lib-python-2.3.4/bsddb/__init__.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/db.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbobj.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbrecio.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbshelve.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbtables.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/dbutils.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/ (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_all.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_associate.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_basics.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_compat.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbobj.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbshelve.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_dbtables.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_env_close.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_get_none.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_join.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_lock.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_misc.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_queue.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_recno.py (props changed) pypy/dist/lib-python-2.3.4/bsddb/test/test_thread.py (props changed) pypy/dist/lib-python-2.3.4/calendar.py (props changed) pypy/dist/lib-python-2.3.4/cgi.py (props changed) pypy/dist/lib-python-2.3.4/cgitb.py (props changed) pypy/dist/lib-python-2.3.4/chunk.py (props changed) pypy/dist/lib-python-2.3.4/cmd.py (props changed) pypy/dist/lib-python-2.3.4/code.py (props changed) pypy/dist/lib-python-2.3.4/codecs.py (props changed) pypy/dist/lib-python-2.3.4/codeop.py (props changed) pypy/dist/lib-python-2.3.4/colorsys.py (props changed) pypy/dist/lib-python-2.3.4/commands.py (props changed) pypy/dist/lib-python-2.3.4/compileall.py (props changed) pypy/dist/lib-python-2.3.4/compiler/ (props changed) pypy/dist/lib-python-2.3.4/compiler/__init__.py (props changed) pypy/dist/lib-python-2.3.4/compiler/ast.py (props changed) pypy/dist/lib-python-2.3.4/compiler/consts.py (props changed) pypy/dist/lib-python-2.3.4/compiler/future.py (props changed) pypy/dist/lib-python-2.3.4/compiler/misc.py (props changed) pypy/dist/lib-python-2.3.4/compiler/pyassem.py (props changed) pypy/dist/lib-python-2.3.4/compiler/pycodegen.py (props changed) pypy/dist/lib-python-2.3.4/compiler/symbols.py (props changed) pypy/dist/lib-python-2.3.4/compiler/syntax.py (props changed) pypy/dist/lib-python-2.3.4/compiler/transformer.py (props changed) pypy/dist/lib-python-2.3.4/compiler/visitor.py (props changed) pypy/dist/lib-python-2.3.4/copy.py (props changed) pypy/dist/lib-python-2.3.4/copy_reg.py (props changed) pypy/dist/lib-python-2.3.4/csv.py (props changed) pypy/dist/lib-python-2.3.4/curses/ (props changed) pypy/dist/lib-python-2.3.4/curses/__init__.py (props changed) pypy/dist/lib-python-2.3.4/curses/ascii.py (props changed) pypy/dist/lib-python-2.3.4/curses/has_key.py (props changed) pypy/dist/lib-python-2.3.4/curses/panel.py (props changed) pypy/dist/lib-python-2.3.4/curses/textpad.py (props changed) pypy/dist/lib-python-2.3.4/curses/wrapper.py (props changed) pypy/dist/lib-python-2.3.4/dbhash.py (props changed) pypy/dist/lib-python-2.3.4/difflib.py (props changed) pypy/dist/lib-python-2.3.4/dircache.py (props changed) pypy/dist/lib-python-2.3.4/dis.py (props changed) pypy/dist/lib-python-2.3.4/distutils/ (props changed) pypy/dist/lib-python-2.3.4/distutils/__init__.py (props changed) pypy/dist/lib-python-2.3.4/distutils/archive_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/bcppcompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/ccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/cmd.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/ (props changed) pypy/dist/lib-python-2.3.4/distutils/command/__init__.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_dumb.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_rpm.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/bdist_wininst.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_clib.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_ext.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_py.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/build_scripts.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/clean.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/config.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_data.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_headers.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_lib.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/install_scripts.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/register.py (props changed) pypy/dist/lib-python-2.3.4/distutils/command/sdist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/core.py (props changed) pypy/dist/lib-python-2.3.4/distutils/cygwinccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/debug.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dep_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dir_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/dist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/emxccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/errors.py (props changed) pypy/dist/lib-python-2.3.4/distutils/extension.py (props changed) pypy/dist/lib-python-2.3.4/distutils/fancy_getopt.py (props changed) pypy/dist/lib-python-2.3.4/distutils/file_util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/filelist.py (props changed) pypy/dist/lib-python-2.3.4/distutils/log.py (props changed) pypy/dist/lib-python-2.3.4/distutils/msvccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/mwerkscompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/spawn.py (props changed) pypy/dist/lib-python-2.3.4/distutils/sysconfig.py (props changed) pypy/dist/lib-python-2.3.4/distutils/text_file.py (props changed) pypy/dist/lib-python-2.3.4/distutils/unixccompiler.py (props changed) pypy/dist/lib-python-2.3.4/distutils/util.py (props changed) pypy/dist/lib-python-2.3.4/distutils/version.py (props changed) pypy/dist/lib-python-2.3.4/doctest.py (props changed) pypy/dist/lib-python-2.3.4/dumbdbm.py (props changed) pypy/dist/lib-python-2.3.4/dummy_thread.py (props changed) pypy/dist/lib-python-2.3.4/dummy_threading.py (props changed) pypy/dist/lib-python-2.3.4/email/ (props changed) pypy/dist/lib-python-2.3.4/email/Charset.py (props changed) pypy/dist/lib-python-2.3.4/email/Encoders.py (props changed) pypy/dist/lib-python-2.3.4/email/Errors.py (props changed) pypy/dist/lib-python-2.3.4/email/Generator.py (props changed) pypy/dist/lib-python-2.3.4/email/Header.py (props changed) pypy/dist/lib-python-2.3.4/email/Iterators.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEAudio.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEBase.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEImage.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEMessage.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEMultipart.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMENonMultipart.py (props changed) pypy/dist/lib-python-2.3.4/email/MIMEText.py (props changed) pypy/dist/lib-python-2.3.4/email/Message.py (props changed) pypy/dist/lib-python-2.3.4/email/Parser.py (props changed) pypy/dist/lib-python-2.3.4/email/Utils.py (props changed) pypy/dist/lib-python-2.3.4/email/__init__.py (props changed) pypy/dist/lib-python-2.3.4/email/_compat21.py (props changed) pypy/dist/lib-python-2.3.4/email/_compat22.py (props changed) pypy/dist/lib-python-2.3.4/email/_parseaddr.py (props changed) pypy/dist/lib-python-2.3.4/email/base64MIME.py (props changed) pypy/dist/lib-python-2.3.4/email/quopriMIME.py (props changed) pypy/dist/lib-python-2.3.4/email/test/ (props changed) pypy/dist/lib-python-2.3.4/email/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/email/test/data/ (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_01.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_02.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_03.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_04.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_05.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_06.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_07.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_08.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_09.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_10.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_11.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_12.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_13.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_14.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_15.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_16.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_17.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_18.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_19.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_20.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_21.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_22.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_23.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_24.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_25.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_27.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_28.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_29.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_30.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_31.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_32.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_33.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_34.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/data/msg_35.txt (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email.py (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email_codecs.py (props changed) pypy/dist/lib-python-2.3.4/email/test/test_email_torture.py (props changed) pypy/dist/lib-python-2.3.4/encodings/ (props changed) pypy/dist/lib-python-2.3.4/encodings/__init__.py (props changed) pypy/dist/lib-python-2.3.4/encodings/aliases.py (props changed) pypy/dist/lib-python-2.3.4/encodings/ascii.py (props changed) pypy/dist/lib-python-2.3.4/encodings/base64_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/charmap.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp037.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1006.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1026.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1140.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1250.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1251.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1252.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1253.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1254.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1255.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1256.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1257.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp1258.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp424.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp437.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp500.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp737.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp775.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp850.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp852.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp855.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp856.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp857.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp860.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp861.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp862.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp863.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp864.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp865.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp866.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp869.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp874.py (props changed) pypy/dist/lib-python-2.3.4/encodings/cp875.py (props changed) pypy/dist/lib-python-2.3.4/encodings/hex_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/idna.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_1.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_10.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_13.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_14.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_15.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_2.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_3.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_4.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_5.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_6.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_7.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_8.py (props changed) pypy/dist/lib-python-2.3.4/encodings/iso8859_9.py (props changed) pypy/dist/lib-python-2.3.4/encodings/koi8_r.py (props changed) pypy/dist/lib-python-2.3.4/encodings/koi8_u.py (props changed) pypy/dist/lib-python-2.3.4/encodings/latin_1.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_cyrillic.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_greek.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_iceland.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_latin2.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_roman.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mac_turkish.py (props changed) pypy/dist/lib-python-2.3.4/encodings/mbcs.py (props changed) pypy/dist/lib-python-2.3.4/encodings/palmos.py (props changed) pypy/dist/lib-python-2.3.4/encodings/punycode.py (props changed) pypy/dist/lib-python-2.3.4/encodings/quopri_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/raw_unicode_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/rot_13.py (props changed) pypy/dist/lib-python-2.3.4/encodings/string_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/undefined.py (props changed) pypy/dist/lib-python-2.3.4/encodings/unicode_escape.py (props changed) pypy/dist/lib-python-2.3.4/encodings/unicode_internal.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16_be.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_16_le.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_7.py (props changed) pypy/dist/lib-python-2.3.4/encodings/utf_8.py (props changed) pypy/dist/lib-python-2.3.4/encodings/uu_codec.py (props changed) pypy/dist/lib-python-2.3.4/encodings/zlib_codec.py (props changed) pypy/dist/lib-python-2.3.4/filecmp.py (props changed) pypy/dist/lib-python-2.3.4/fileinput.py (props changed) pypy/dist/lib-python-2.3.4/fnmatch.py (props changed) pypy/dist/lib-python-2.3.4/formatter.py (props changed) pypy/dist/lib-python-2.3.4/fpformat.py (props changed) pypy/dist/lib-python-2.3.4/ftplib.py (props changed) pypy/dist/lib-python-2.3.4/getopt.py (props changed) pypy/dist/lib-python-2.3.4/getpass.py (props changed) pypy/dist/lib-python-2.3.4/gettext.py (props changed) pypy/dist/lib-python-2.3.4/glob.py (props changed) pypy/dist/lib-python-2.3.4/gopherlib.py (props changed) pypy/dist/lib-python-2.3.4/gzip.py (props changed) pypy/dist/lib-python-2.3.4/heapq.py (props changed) pypy/dist/lib-python-2.3.4/hmac.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/ (props changed) pypy/dist/lib-python-2.3.4/hotshot/__init__.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/log.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/stats.py (props changed) pypy/dist/lib-python-2.3.4/hotshot/stones.py (props changed) pypy/dist/lib-python-2.3.4/htmlentitydefs.py (props changed) pypy/dist/lib-python-2.3.4/htmllib.py (props changed) pypy/dist/lib-python-2.3.4/httplib.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ (props changed) pypy/dist/lib-python-2.3.4/idlelib/AutoExpand.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Bindings.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/CREDITS.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/CallTipWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/CallTips.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ClassBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ColorDelegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Debugger.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Delegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/EditorWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/FileList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/FormatParagraph.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/GrepDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/HISTORY.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/IOBinding.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/IdleHistory.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/MultiStatusBar.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/NEWS.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/ObjectBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/OutputWindow.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ParenMatch.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PathBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/Percolator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PyParse.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/PyShell.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/README.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/RemoteDebugger.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/RemoteObjectBrowser.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ReplaceDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ScriptBinding.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ScrolledList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchDialogBase.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/SearchEngine.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/StackViewer.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/TODO.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/ToolTip.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/TreeWidget.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/UndoDelegator.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/WidgetRedirector.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/WindowList.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/ZoomHeight.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/__init__.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/aboutDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/buildapp.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configHandler.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configHelpSourceEdit.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/configSectionNameDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/dynOptionMenuWidget.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/extend.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/help.txt (props changed) pypy/dist/lib-python-2.3.4/idlelib/idle.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/idlever.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/keybindingDialog.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/rpc.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/run.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/tabpage.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/testcode.py (props changed) pypy/dist/lib-python-2.3.4/idlelib/textView.py (props changed) pypy/dist/lib-python-2.3.4/ihooks.py (props changed) pypy/dist/lib-python-2.3.4/imaplib.py (props changed) pypy/dist/lib-python-2.3.4/imghdr.py (props changed) pypy/dist/lib-python-2.3.4/imputil.py (props changed) pypy/dist/lib-python-2.3.4/inspect.py (props changed) pypy/dist/lib-python-2.3.4/keyword.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/ (props changed) pypy/dist/lib-python-2.3.4/lib-old/Para.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/addpack.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/cmp.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/cmpcache.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/codehack.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/dircmp.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/dump.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/find.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/fmt.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/grep.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/lockfile.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/newdir.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/ni.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/packmail.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/poly.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/rand.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/tb.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/util.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/whatsound.py (props changed) pypy/dist/lib-python-2.3.4/lib-old/zmod.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/ (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Canvas.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Dialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/FileDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/FixTk.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/ScrolledText.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/SimpleDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tix.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkconstants.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkdnd.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/Tkinter.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkColorChooser.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkCommonDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkFileDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkFont.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkMessageBox.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/tkSimpleDialog.py (props changed) pypy/dist/lib-python-2.3.4/lib-tk/turtle.py (props changed) pypy/dist/lib-python-2.3.4/linecache.py (props changed) pypy/dist/lib-python-2.3.4/locale.py (props changed) pypy/dist/lib-python-2.3.4/logging/ (props changed) pypy/dist/lib-python-2.3.4/logging/__init__.py (props changed) pypy/dist/lib-python-2.3.4/logging/config.py (props changed) pypy/dist/lib-python-2.3.4/logging/handlers.py (props changed) pypy/dist/lib-python-2.3.4/macpath.py (props changed) pypy/dist/lib-python-2.3.4/macurl2path.py (props changed) pypy/dist/lib-python-2.3.4/mailbox.py (props changed) pypy/dist/lib-python-2.3.4/mailcap.py (props changed) pypy/dist/lib-python-2.3.4/markupbase.py (props changed) pypy/dist/lib-python-2.3.4/mhlib.py (props changed) pypy/dist/lib-python-2.3.4/mimetools.py (props changed) pypy/dist/lib-python-2.3.4/mimetypes.py (props changed) pypy/dist/lib-python-2.3.4/mimify.py (props changed) pypy/dist/lib-python-2.3.4/modulefinder.py (props changed) pypy/dist/lib-python-2.3.4/multifile.py (props changed) pypy/dist/lib-python-2.3.4/mutex.py (props changed) pypy/dist/lib-python-2.3.4/netrc.py (props changed) pypy/dist/lib-python-2.3.4/new.py (props changed) pypy/dist/lib-python-2.3.4/nntplib.py (props changed) pypy/dist/lib-python-2.3.4/ntpath.py (props changed) pypy/dist/lib-python-2.3.4/nturl2path.py (props changed) pypy/dist/lib-python-2.3.4/opcode.py (props changed) pypy/dist/lib-python-2.3.4/optparse.py (props changed) pypy/dist/lib-python-2.3.4/os.py (props changed) pypy/dist/lib-python-2.3.4/os2emxpath.py (props changed) pypy/dist/lib-python-2.3.4/pdb.py (props changed) pypy/dist/lib-python-2.3.4/pickle.py (props changed) pypy/dist/lib-python-2.3.4/pickletools.py (props changed) pypy/dist/lib-python-2.3.4/pipes.py (props changed) pypy/dist/lib-python-2.3.4/pkgutil.py (props changed) pypy/dist/lib-python-2.3.4/plat-aix3/ (props changed) pypy/dist/lib-python-2.3.4/plat-aix3/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-aix4/ (props changed) pypy/dist/lib-python-2.3.4/plat-aix4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/ (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-atheos/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-beos5/ (props changed) pypy/dist/lib-python-2.3.4/plat-beos5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-darwin/ (props changed) pypy/dist/lib-python-2.3.4/plat-darwin/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd2/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd2/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd3/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd3/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd4/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd5/ (props changed) pypy/dist/lib-python-2.3.4/plat-freebsd5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/ (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/AL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CD.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/CL_old.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/DEVICE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/ERRNO.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/FILE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/FL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GET.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/GLWS.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/IOCTL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/SV.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/cddb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/cdplayer.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/flp.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/jpeg.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/panel.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/panelparser.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/readcd.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix5/torgb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/ (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/AL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/CD.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/CL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/DEVICE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/ERRNO.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/FILE.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/FL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GET.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/GLWS.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/IOCTL.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/SV.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/cddb.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/cdplayer.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/flp.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/jpeg.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/panel.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/panelparser.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/readcd.py (props changed) pypy/dist/lib-python-2.3.4/plat-irix6/torgb.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux1/ (props changed) pypy/dist/lib-python-2.3.4/plat-linux1/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/ (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/CDROM.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/DLFCN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-linux2/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Audio_mac.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AE.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AH.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Alias.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Aliases.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/App.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Appearance.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AppleEvents.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/AppleHelp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CF.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CG.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CarbonEvents.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CarbonEvt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Cm.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Components.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/ControlAccessor.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Controls.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CoreFoundation.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/CoreGraphics.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Ctl.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dialogs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dlg.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Drag.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Dragconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Events.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Evt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/File.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Files.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Fm.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Folder.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Folders.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Fonts.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Help.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/IBCarbon.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/IBCarbonRuntime.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Icn.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Icons.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/List.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Lists.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MacHelp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MacTextEditor.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/MediaDescr.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Menu.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Menus.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Mlte.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QDOffscreen.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qd.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qdoffs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Qt.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QuickDraw.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/QuickTime.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Res.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Resources.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Scrap.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Snd.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Sndihooks.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Sound.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/TE.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/TextEdit.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/WASTEconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Win.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/Carbon/Windows.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/EasyDialogs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/FrameWork.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/MiniAEFrame.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/PixMapWrapper.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/WASTEconst.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aepack.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aetools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/aetypes.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/applesingle.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/appletrawmain.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/appletrunner.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/argvemulator.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/bgenlocations.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/buildtools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/bundlebuilder.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/cfmfile.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/findertools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/gensuitemodule.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/ic.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/icopen.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Required.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Microsoft_Internet_Explorer.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Netscape_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/URL_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Explorer/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Containers_and_folders.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Enumerations.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Files.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Finder_Basics.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Finder_items.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Legacy_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Type_Definitions.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/Window_classes.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Finder/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Required_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/Text.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Netscape/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suppleme.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Required_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/Type_Names_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/StdSuites/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Hidden_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Login_Items_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Power_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Processes_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/System_Events_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/SystemEvents/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Terminal_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/Text_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/Terminal/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/ (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macerrors.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macfs.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macostools.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/macresource.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/pimp.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/plistlib.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/terminalcommand.py (props changed) pypy/dist/lib-python-2.3.4/plat-mac/videoreader.py (props changed) pypy/dist/lib-python-2.3.4/plat-netbsd1/ (props changed) pypy/dist/lib-python-2.3.4/plat-netbsd1/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/ (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/SOCKET.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/grp.py (props changed) pypy/dist/lib-python-2.3.4/plat-os2emx/pwd.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/ (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/riscosenviron.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/riscospath.py (props changed) pypy/dist/lib-python-2.3.4/plat-riscos/rourl2path.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/ (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/SUNAUDIODEV.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos4/WAIT.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/ (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/CDIO.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/DLFCN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/STROPTS.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/SUNAUDIODEV.py (props changed) pypy/dist/lib-python-2.3.4/plat-sunos5/TYPES.py (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/ (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/IN.py (props changed) pypy/dist/lib-python-2.3.4/plat-unixware7/STROPTS.py (props changed) pypy/dist/lib-python-2.3.4/platform.py (props changed) pypy/dist/lib-python-2.3.4/popen2.py (props changed) pypy/dist/lib-python-2.3.4/poplib.py (props changed) pypy/dist/lib-python-2.3.4/posixfile.py (props changed) pypy/dist/lib-python-2.3.4/posixpath.py (props changed) pypy/dist/lib-python-2.3.4/pprint.py (props changed) pypy/dist/lib-python-2.3.4/pre.py (props changed) pypy/dist/lib-python-2.3.4/profile.py (props changed) pypy/dist/lib-python-2.3.4/pstats.py (props changed) pypy/dist/lib-python-2.3.4/pty.py (props changed) pypy/dist/lib-python-2.3.4/py_compile.py (props changed) pypy/dist/lib-python-2.3.4/pyclbr.py (props changed) pypy/dist/lib-python-2.3.4/pydoc.py (props changed) pypy/dist/lib-python-2.3.4/quopri.py (props changed) pypy/dist/lib-python-2.3.4/random.py (props changed) pypy/dist/lib-python-2.3.4/re.py (props changed) pypy/dist/lib-python-2.3.4/reconvert.py (props changed) pypy/dist/lib-python-2.3.4/regex_syntax.py (props changed) pypy/dist/lib-python-2.3.4/regsub.py (props changed) pypy/dist/lib-python-2.3.4/repr.py (props changed) pypy/dist/lib-python-2.3.4/rexec.py (props changed) pypy/dist/lib-python-2.3.4/rfc822.py (props changed) pypy/dist/lib-python-2.3.4/rlcompleter.py (props changed) pypy/dist/lib-python-2.3.4/robotparser.py (props changed) pypy/dist/lib-python-2.3.4/sched.py (props changed) pypy/dist/lib-python-2.3.4/sets.py (props changed) pypy/dist/lib-python-2.3.4/sgmllib.py (props changed) pypy/dist/lib-python-2.3.4/shelve.py (props changed) pypy/dist/lib-python-2.3.4/shlex.py (props changed) pypy/dist/lib-python-2.3.4/shutil.py (props changed) pypy/dist/lib-python-2.3.4/site.py (props changed) pypy/dist/lib-python-2.3.4/smtpd.py (props changed) pypy/dist/lib-python-2.3.4/smtplib.py (props changed) pypy/dist/lib-python-2.3.4/sndhdr.py (props changed) pypy/dist/lib-python-2.3.4/socket.py (props changed) pypy/dist/lib-python-2.3.4/sre.py (props changed) pypy/dist/lib-python-2.3.4/sre_compile.py (props changed) pypy/dist/lib-python-2.3.4/sre_constants.py (props changed) pypy/dist/lib-python-2.3.4/sre_parse.py (props changed) pypy/dist/lib-python-2.3.4/stat.py (props changed) pypy/dist/lib-python-2.3.4/statcache.py (props changed) pypy/dist/lib-python-2.3.4/statvfs.py (props changed) pypy/dist/lib-python-2.3.4/string.py (props changed) pypy/dist/lib-python-2.3.4/stringold.py (props changed) pypy/dist/lib-python-2.3.4/stringprep.py (props changed) pypy/dist/lib-python-2.3.4/sunau.py (props changed) pypy/dist/lib-python-2.3.4/sunaudio.py (props changed) pypy/dist/lib-python-2.3.4/symbol.py (props changed) pypy/dist/lib-python-2.3.4/symtable.py (props changed) pypy/dist/lib-python-2.3.4/tabnanny.py (props changed) pypy/dist/lib-python-2.3.4/tarfile.py (props changed) pypy/dist/lib-python-2.3.4/telnetlib.py (props changed) pypy/dist/lib-python-2.3.4/tempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/ (props changed) pypy/dist/lib-python-2.3.4/test/__init__.py (props changed) pypy/dist/lib-python-2.3.4/test/autotest.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future3.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future4.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future5.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future6.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_future7.py (props changed) pypy/dist/lib-python-2.3.4/test/badsyntax_nocaret.py (props changed) pypy/dist/lib-python-2.3.4/test/conftest.py (contents, props changed) pypy/dist/lib-python-2.3.4/test/double_const.py (props changed) pypy/dist/lib-python-2.3.4/test/pickletester.py (props changed) pypy/dist/lib-python-2.3.4/test/pydocfodder.py (props changed) pypy/dist/lib-python-2.3.4/test/pypy_unittest.py (props changed) pypy/dist/lib-python-2.3.4/test/pystone.py (props changed) pypy/dist/lib-python-2.3.4/test/re_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/regex_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/regrtest.py (props changed) pypy/dist/lib-python-2.3.4/test/reperf.py (props changed) pypy/dist/lib-python-2.3.4/test/sortperf.py (props changed) pypy/dist/lib-python-2.3.4/test/string_tests.py (props changed) pypy/dist/lib-python-2.3.4/test/test_MimeWriter.py (props changed) pypy/dist/lib-python-2.3.4/test/test_StringIO.py (props changed) pypy/dist/lib-python-2.3.4/test/test___all__.py (props changed) pypy/dist/lib-python-2.3.4/test/test___future__.py (props changed) pypy/dist/lib-python-2.3.4/test/test_aepack.py (props changed) pypy/dist/lib-python-2.3.4/test/test_al.py (props changed) pypy/dist/lib-python-2.3.4/test/test_anydbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_array.py (props changed) pypy/dist/lib-python-2.3.4/test/test_asynchat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_atexit.py (props changed) pypy/dist/lib-python-2.3.4/test/test_audioop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_augassign.py (props changed) pypy/dist/lib-python-2.3.4/test/test_base64.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bastion.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binascii.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binhex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_binop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bisect.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bool.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb185.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bsddb3.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bufio.py (props changed) pypy/dist/lib-python-2.3.4/test/test_builtin.py (props changed) pypy/dist/lib-python-2.3.4/test/test_bz2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_calendar.py (props changed) pypy/dist/lib-python-2.3.4/test/test_call.py (props changed) pypy/dist/lib-python-2.3.4/test/test_capi.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cd.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cfgparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cgi.py (props changed) pypy/dist/lib-python-2.3.4/test/test_charmapcodec.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_class.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cmath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codeccallbacks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codecs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_codeop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_coercion.py (props changed) pypy/dist/lib-python-2.3.4/test/test_commands.py (props changed) pypy/dist/lib-python-2.3.4/test/test_compare.py (props changed) pypy/dist/lib-python-2.3.4/test/test_compile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_complex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_contains.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cookie.py (props changed) pypy/dist/lib-python-2.3.4/test/test_copy.py (props changed) pypy/dist/lib-python-2.3.4/test/test_copy_reg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_cpickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_crypt.py (props changed) pypy/dist/lib-python-2.3.4/test/test_csv.py (props changed) pypy/dist/lib-python-2.3.4/test/test_curses.py (props changed) pypy/dist/lib-python-2.3.4/test/test_datetime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_descr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_descrtut.py (props changed) pypy/dist/lib-python-2.3.4/test/test_difflib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dircache.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dis.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_doctest.py (props changed) pypy/dist/lib-python-2.3.4/test/test_doctest2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dumbdbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dummy_thread.py (props changed) pypy/dist/lib-python-2.3.4/test/test_dummy_threading.py (props changed) pypy/dist/lib-python-2.3.4/test/test_email.py (props changed) pypy/dist/lib-python-2.3.4/test/test_email_codecs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_enumerate.py (props changed) pypy/dist/lib-python-2.3.4/test/test_eof.py (props changed) pypy/dist/lib-python-2.3.4/test/test_errno.py (props changed) pypy/dist/lib-python-2.3.4/test/test_exceptions.py (props changed) pypy/dist/lib-python-2.3.4/test/test_extcall.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fcntl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_file.py (props changed) pypy/dist/lib-python-2.3.4/test/test_filecmp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fileinput.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fnmatch.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fork1.py (props changed) pypy/dist/lib-python-2.3.4/test/test_format.py (props changed) pypy/dist/lib-python-2.3.4/test/test_fpformat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_frozen.py (props changed) pypy/dist/lib-python-2.3.4/test/test_funcattrs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future1.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_future3.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gdbm.py (props changed) pypy/dist/lib-python-2.3.4/test/test_generators.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getargs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getargs2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_getopt.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gettext.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_glob.py (props changed) pypy/dist/lib-python-2.3.4/test/test_global.py (props changed) pypy/dist/lib-python-2.3.4/test/test_grammar.py (props changed) pypy/dist/lib-python-2.3.4/test/test_grp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_gzip.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hash.py (props changed) pypy/dist/lib-python-2.3.4/test/test_heapq.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hexoct.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hmac.py (props changed) pypy/dist/lib-python-2.3.4/test/test_hotshot.py (props changed) pypy/dist/lib-python-2.3.4/test/test_htmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_htmlparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_httplib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imageop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imaplib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imgfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_imp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_import.py (props changed) pypy/dist/lib-python-2.3.4/test/test_importhooks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_inspect.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ioctl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_isinstance.py (props changed) pypy/dist/lib-python-2.3.4/test/test_iter.py (props changed) pypy/dist/lib-python-2.3.4/test/test_itertools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_largefile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_linuxaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_locale.py (props changed) pypy/dist/lib-python-2.3.4/test/test_logging.py (props changed) pypy/dist/lib-python-2.3.4/test/test_long.py (props changed) pypy/dist/lib-python-2.3.4/test/test_long_future.py (props changed) pypy/dist/lib-python-2.3.4/test/test_longexp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macfs.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macostools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_macpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mailbox.py (props changed) pypy/dist/lib-python-2.3.4/test/test_marshal.py (props changed) pypy/dist/lib-python-2.3.4/test/test_math.py (props changed) pypy/dist/lib-python-2.3.4/test/test_md5.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mhlib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mimetools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mimetypes.py (props changed) pypy/dist/lib-python-2.3.4/test/test_minidom.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mmap.py (props changed) pypy/dist/lib-python-2.3.4/test/test_module.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mpz.py (props changed) pypy/dist/lib-python-2.3.4/test/test_multifile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_mutants.py (props changed) pypy/dist/lib-python-2.3.4/test/test_netrc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_new.py (props changed) pypy/dist/lib-python-2.3.4/test/test_nis.py (props changed) pypy/dist/lib-python-2.3.4/test/test_normalization.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ntpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_opcodes.py (props changed) pypy/dist/lib-python-2.3.4/test/test_openpty.py (props changed) pypy/dist/lib-python-2.3.4/test/test_operations.py (props changed) pypy/dist/lib-python-2.3.4/test/test_operator.py (props changed) pypy/dist/lib-python-2.3.4/test/test_optparse.py (props changed) pypy/dist/lib-python-2.3.4/test/test_os.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ossaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_parser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep247.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep263.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pep277.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pickletools.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pkg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pkgimport.py (props changed) pypy/dist/lib-python-2.3.4/test/test_plistlib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_poll.py (props changed) pypy/dist/lib-python-2.3.4/test/test_popen.py (props changed) pypy/dist/lib-python-2.3.4/test/test_popen2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_posix.py (props changed) pypy/dist/lib-python-2.3.4/test/test_posixpath.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pow.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pprint.py (props changed) pypy/dist/lib-python-2.3.4/test/test_profile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_profilehooks.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pty.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pwd.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pyclbr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_pyexpat.py (props changed) pypy/dist/lib-python-2.3.4/test/test_queue.py (props changed) pypy/dist/lib-python-2.3.4/test/test_quopri.py (props changed) pypy/dist/lib-python-2.3.4/test/test_random.py (props changed) pypy/dist/lib-python-2.3.4/test/test_re.py (props changed) pypy/dist/lib-python-2.3.4/test/test_regex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_repr.py (props changed) pypy/dist/lib-python-2.3.4/test/test_resource.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rfc822.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rgbimg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_richcmp.py (props changed) pypy/dist/lib-python-2.3.4/test/test_robotparser.py (props changed) pypy/dist/lib-python-2.3.4/test/test_rotor.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sax.py (props changed) pypy/dist/lib-python-2.3.4/test/test_scope.py (props changed) pypy/dist/lib-python-2.3.4/test/test_scriptpackages.py (props changed) pypy/dist/lib-python-2.3.4/test/test_select.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sets.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sgmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sha.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shelve.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shlex.py (props changed) pypy/dist/lib-python-2.3.4/test/test_shutil.py (props changed) pypy/dist/lib-python-2.3.4/test/test_signal.py (props changed) pypy/dist/lib-python-2.3.4/test/test_slice.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socket.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socket_ssl.py (props changed) pypy/dist/lib-python-2.3.4/test/test_socketserver.py (props changed) pypy/dist/lib-python-2.3.4/test/test_softspace.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sort.py (props changed) pypy/dist/lib-python-2.3.4/test/test_str.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strftime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_string.py (props changed) pypy/dist/lib-python-2.3.4/test/test_stringprep.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strop.py (props changed) pypy/dist/lib-python-2.3.4/test/test_strptime.py (props changed) pypy/dist/lib-python-2.3.4/test/test_struct.py (props changed) pypy/dist/lib-python-2.3.4/test/test_structseq.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sunaudiodev.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sundry.py (props changed) pypy/dist/lib-python-2.3.4/test/test_support.py (props changed) pypy/dist/lib-python-2.3.4/test/test_symtable.py (props changed) pypy/dist/lib-python-2.3.4/test/test_syntax.py (props changed) pypy/dist/lib-python-2.3.4/test/test_sys.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tarfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_textwrap.py (props changed) pypy/dist/lib-python-2.3.4/test/test_thread.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threaded_import.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threadedtempfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_threading.py (props changed) pypy/dist/lib-python-2.3.4/test/test_time.py (props changed) pypy/dist/lib-python-2.3.4/test/test_timeout.py (props changed) pypy/dist/lib-python-2.3.4/test/test_timing.py (props changed) pypy/dist/lib-python-2.3.4/test/test_tokenize.py (props changed) pypy/dist/lib-python-2.3.4/test/test_trace.py (props changed) pypy/dist/lib-python-2.3.4/test/test_traceback.py (props changed) pypy/dist/lib-python-2.3.4/test/test_types.py (props changed) pypy/dist/lib-python-2.3.4/test/test_ucn.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unary.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicode.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicode_file.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unicodedata.py (props changed) pypy/dist/lib-python-2.3.4/test/test_univnewlines.py (props changed) pypy/dist/lib-python-2.3.4/test/test_unpack.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllib2.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urllibnet.py (props changed) pypy/dist/lib-python-2.3.4/test/test_urlparse.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userdict.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userlist.py (props changed) pypy/dist/lib-python-2.3.4/test/test_userstring.py (props changed) pypy/dist/lib-python-2.3.4/test/test_uu.py (props changed) pypy/dist/lib-python-2.3.4/test/test_warnings.py (props changed) pypy/dist/lib-python-2.3.4/test/test_wave.py (props changed) pypy/dist/lib-python-2.3.4/test/test_weakref.py (props changed) pypy/dist/lib-python-2.3.4/test/test_whichdb.py (props changed) pypy/dist/lib-python-2.3.4/test/test_winreg.py (props changed) pypy/dist/lib-python-2.3.4/test/test_winsound.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xmllib.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xmlrpc.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xpickle.py (props changed) pypy/dist/lib-python-2.3.4/test/test_xreadline.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zipfile.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zipimport.py (props changed) pypy/dist/lib-python-2.3.4/test/test_zlib.py (props changed) pypy/dist/lib-python-2.3.4/test/testall.py (props changed) pypy/dist/lib-python-2.3.4/test/testcodec.py (props changed) pypy/dist/lib-python-2.3.4/test/tf_inherit_check.py (props changed) pypy/dist/lib-python-2.3.4/test/tokenize_tests.txt (props changed) pypy/dist/lib-python-2.3.4/test/xmltests.py (props changed) pypy/dist/lib-python-2.3.4/textwrap.py (props changed) pypy/dist/lib-python-2.3.4/this.py (props changed) pypy/dist/lib-python-2.3.4/threading.py (props changed) pypy/dist/lib-python-2.3.4/timeit.py (props changed) pypy/dist/lib-python-2.3.4/toaiff.py (props changed) pypy/dist/lib-python-2.3.4/token.py (props changed) pypy/dist/lib-python-2.3.4/tokenize.py (props changed) pypy/dist/lib-python-2.3.4/trace.py (props changed) pypy/dist/lib-python-2.3.4/traceback.py (props changed) pypy/dist/lib-python-2.3.4/tty.py (props changed) pypy/dist/lib-python-2.3.4/types.py (props changed) pypy/dist/lib-python-2.3.4/tzparse.py (props changed) pypy/dist/lib-python-2.3.4/unittest.py (props changed) pypy/dist/lib-python-2.3.4/urllib.py (props changed) pypy/dist/lib-python-2.3.4/urllib2.py (props changed) pypy/dist/lib-python-2.3.4/urlparse.py (props changed) pypy/dist/lib-python-2.3.4/user.py (props changed) pypy/dist/lib-python-2.3.4/uu.py (props changed) pypy/dist/lib-python-2.3.4/warnings.py (props changed) pypy/dist/lib-python-2.3.4/wave.py (props changed) pypy/dist/lib-python-2.3.4/weakref.py (props changed) pypy/dist/lib-python-2.3.4/webbrowser.py (props changed) pypy/dist/lib-python-2.3.4/whichdb.py (props changed) pypy/dist/lib-python-2.3.4/whrandom.py (props changed) pypy/dist/lib-python-2.3.4/xdrlib.py (props changed) pypy/dist/lib-python-2.3.4/xml/ (props changed) pypy/dist/lib-python-2.3.4/xml/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/ (props changed) pypy/dist/lib-python-2.3.4/xml/dom/NodeFilter.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/domreg.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/expatbuilder.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/minicompat.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/minidom.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/pulldom.py (props changed) pypy/dist/lib-python-2.3.4/xml/dom/xmlbuilder.py (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/ (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/parsers/expat.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/ (props changed) pypy/dist/lib-python-2.3.4/xml/sax/__init__.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/_exceptions.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/expatreader.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/handler.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/saxutils.py (props changed) pypy/dist/lib-python-2.3.4/xml/sax/xmlreader.py (props changed) pypy/dist/lib-python-2.3.4/xmllib.py (props changed) pypy/dist/lib-python-2.3.4/xmlrpclib.py (props changed) pypy/dist/lib-python-2.3.4/zipfile.py (props changed) Log: set eol-style (but more carefully with the new fixeol) maybe some data files under email/test should have a fixed line-ending (and not eol-native) but we'll see when we get to running the email module against pypy :-) Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 00:43:52 2005 @@ -75,12 +75,8 @@ if hasattr(self, 'space'): return self.space = space = gettestobjspace('std') - #try: w_mod = make_module(space, 'unittest', mydir.join('pypy_unittest.py')) self.w_TestCase = space.getattr(w_mod, space.wrap('TestCase')) - #except OperationError, e: - # raise py.test.Item.Failed( - # excinfo=pytestsupport.AppExceptionInfo(self.space, e)) def __iter__(self): self._prepare() @@ -116,9 +112,6 @@ self.w_teardown = w_teardown def run(self, driver): - #if sys.version_info < (2,4): - # py.test.skip("CPython 2.4 required for " - # "running CPython 2.4 regrtests") try: self.space.call_function(self.w_setup) try: From tismer at codespeak.net Sat Jan 29 01:44:32 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 01:44:32 +0100 (MET) Subject: [pypy-svn] r8680 - in pypy/dist/pypy: lib module objspace/std tool translator Message-ID: <20050129004432.AA8D127B96@code1.codespeak.net> Author: tismer Date: Sat Jan 29 01:44:32 2005 New Revision: 8680 Modified: pypy/dist/pypy/lib/_exceptions.py pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/tool/_enum_exceptions.py pypy/dist/pypy/tool/sourcetools.py pypy/dist/pypy/translator/geninterplevel.py Log: module docstrings are now fully supported. They appear in _exceptions.py and are transported to the generated exceptionsinterp.py . Modified: pypy/dist/pypy/lib/_exceptions.py ============================================================================== --- pypy/dist/pypy/lib/_exceptions.py (original) +++ pypy/dist/pypy/lib/_exceptions.py Sat Jan 29 01:44:32 2005 @@ -1,3 +1,92 @@ +"""Python's standard exception class hierarchy. + +Before Python 1.5, the standard exceptions were all simple string objects. +In Python 1.5, the standard exceptions were converted to classes organized +into a relatively flat hierarchy. String-based standard exceptions were +optional, or used as a fallback if some problem occurred while importing +the exception module. With Python 1.6, optional string-based standard +exceptions were removed (along with the -X command line flag). + +The class exceptions were implemented in such a way as to be almost +completely backward compatible. Some tricky uses of IOError could +potentially have broken, but by Python 1.6, all of these should have +been fixed. As of Python 1.6, the class-based standard exceptions are +now implemented in C, and are guaranteed to exist in the Python +interpreter. + +Here is a rundown of the class hierarchy. The classes found here are +inserted into both the exceptions module and the `built-in' module. It is +recommended that user defined class based exceptions be derived from the +`Exception' class, although this is currently not enforced. + +Exception + | + +-- SystemExit + +-- TaskletExit + +-- StopIteration + +-- StandardError + | | + | +-- KeyboardInterrupt + | +-- ImportError + | +-- EnvironmentError + | | | + | | +-- IOError + | | +-- OSError + | | | + | | +-- WindowsError + | | +-- VMSError + | | + | +-- EOFError + | +-- RuntimeError + | | | + | | +-- NotImplementedError + | | + | +-- NameError + | | | + | | +-- UnboundLocalError + | | + | +-- AttributeError + | +-- SyntaxError + | | | + | | +-- IndentationError + | | | + | | +-- TabError + | | + | +-- TypeError + | +-- AssertionError + | +-- LookupError + | | | + | | +-- IndexError + | | +-- KeyError + | | + | +-- ArithmeticError + | | | + | | +-- OverflowError + | | +-- ZeroDivisionError + | | +-- FloatingPointError + | | + | +-- ValueError + | | | + | | +-- UnicodeError + | | | + | | +-- UnicodeEncodeError + | | +-- UnicodeDecodeError + | | +-- UnicodeTranslateError + | | + | +-- ReferenceError + | +-- SystemError + | +-- MemoryError + | + +---Warning + | + +-- UserWarning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- SyntaxWarning + +-- OverflowWarning + +-- RuntimeWarning + +-- FutureWarning""" + class Exception: """Common base class for all exceptions.""" @@ -295,4 +384,3 @@ class WindowsError(OSError): """MS-Windows OS system call failed.""" - Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Sat Jan 29 01:44:32 2005 @@ -1,9 +1,99 @@ #!/bin/env python # -*- coding: LATIN-1 -*- + +"""Python's standard exception class hierarchy. + +Before Python 1.5, the standard exceptions were all simple string objects. +In Python 1.5, the standard exceptions were converted to classes organized +into a relatively flat hierarchy. String-based standard exceptions were +optional, or used as a fallback if some problem occurred while importing +the exception module. With Python 1.6, optional string-based standard +exceptions were removed (along with the -X command line flag). + +The class exceptions were implemented in such a way as to be almost +completely backward compatible. Some tricky uses of IOError could +potentially have broken, but by Python 1.6, all of these should have +been fixed. As of Python 1.6, the class-based standard exceptions are +now implemented in C, and are guaranteed to exist in the Python +interpreter. + +Here is a rundown of the class hierarchy. The classes found here are +inserted into both the exceptions module and the `built-in' module. It is +recommended that user defined class based exceptions be derived from the +`Exception' class, although this is currently not enforced. + +Exception + | + +-- SystemExit + +-- TaskletExit + +-- StopIteration + +-- StandardError + | | + | +-- KeyboardInterrupt + | +-- ImportError + | +-- EnvironmentError + | | | + | | +-- IOError + | | +-- OSError + | | | + | | +-- WindowsError + | | +-- VMSError + | | + | +-- EOFError + | +-- RuntimeError + | | | + | | +-- NotImplementedError + | | + | +-- NameError + | | | + | | +-- UnboundLocalError + | | + | +-- AttributeError + | +-- SyntaxError + | | | + | | +-- IndentationError + | | | + | | +-- TabError + | | + | +-- TypeError + | +-- AssertionError + | +-- LookupError + | | | + | | +-- IndexError + | | +-- KeyError + | | + | +-- ArithmeticError + | | | + | | +-- OverflowError + | | +-- ZeroDivisionError + | | +-- FloatingPointError + | | + | +-- ValueError + | | | + | | +-- UnicodeError + | | | + | | +-- UnicodeEncodeError + | | +-- UnicodeDecodeError + | | +-- UnicodeTranslateError + | | + | +-- ReferenceError + | +-- SystemError + | +-- MemoryError + | + +---Warning + | + +-- UserWarning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- SyntaxWarning + +-- OverflowWarning + +-- RuntimeWarning + +-- FutureWarning""" + ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__getitem__' -## firstlineno 5 +## firstlineno 94 ##SECTION## def __getitem__(space, *args_w): kwlist = ["self", "idx"] @@ -16,7 +106,7 @@ def __getitem__(space, w_self_1, w_idx_3): - w_0=w_0=w_2=w_4=None + w_0=w_2=w_4=None goto = 1 # startblock while True: @@ -32,9 +122,9 @@ fastf_Exception___getitem__ = globals().pop("__getitem__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 9 +## firstlineno 98 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] @@ -48,7 +138,7 @@ def __init__(space, w_self_1, w_args_2): - w_0=w_0=w_3=None + w_0=w_3=None goto = 1 # startblock while True: @@ -63,9 +153,9 @@ fastf_Exception___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 13 +## firstlineno 102 ##SECTION## # global declarations # global object gs_args @@ -83,9 +173,9 @@ def __str__(space, w_self_1): - w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None - w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None - w_14=w_14=w_15=w_19=w_20=w_21=None + w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=w_argc_17=None + w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=w_14=w_15=w_19=w_20=None + w_21=None goto = 1 # startblock while True: @@ -135,9 +225,9 @@ fastf_Exception___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 41 +## firstlineno 130 ##SECTION## # global declarations # global object gi_4 @@ -156,8 +246,8 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None + w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None + w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None goto = 1 # startblock while True: @@ -193,9 +283,9 @@ fastf_UnicodeTranslateError___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 51 +## firstlineno 140 ##SECTION## # global declarations # global object gs_start @@ -222,8 +312,8 @@ def __str__(space, w_self_1): - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_res_17=w_18=None + w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_16=w_res_17=w_18=None goto = 1 # startblock while True: @@ -260,9 +350,9 @@ fastf_UnicodeTranslateError___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 69 +## firstlineno 158 ##SECTION## def __str__(space, *args_w): kwlist = ["self"] @@ -275,9 +365,9 @@ def __str__(space, w_self_1): - w_0=w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=None - w_argc_17=w_argc_17=w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=None - w_14=w_14=w_15=w_19=w_20=w_21=None + w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=w_argc_17=None + w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=w_14=w_15=w_19=w_20=None + w_21=None goto = 1 # startblock while True: @@ -326,9 +416,9 @@ fastf_KeyError___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 91 +## firstlineno 183 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] @@ -342,12 +432,11 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=None - w_argc_20=w_argc_20=w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=None - v37=v37=w_43=w_self_38=w_args_39=w_argc_40=w_41=w_42=w_44=w_45=None - w_46=w_46=w_47=w_48=w_49=w_self_24=w_args_25=w_argc_26=w_27=w_28=None - w_32=w_32=w_33=w_34=w_35=w_self_9=w_args_10=w_argc_11=w_12=w_13=None - w_14=w_14=w_15=w_16=w_17=w_22=None + w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=w_argc_20=None + w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=v37=w_43=w_self_38=None + w_args_39=w_argc_40=w_41=w_42=w_44=w_45=w_46=w_47=w_48=w_49=w_self_24=None + w_args_25=w_argc_26=w_27=w_28=w_32=w_33=w_34=w_35=w_self_9=w_args_10=None + w_argc_11=w_12=w_13=w_14=w_15=w_16=w_17=w_22=None goto = 1 # startblock while True: @@ -423,9 +512,9 @@ fastf_EnvironmentError___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 105 +## firstlineno 197 ##SECTION## # global declarations # global object gs_errno @@ -433,7 +522,6 @@ # global object gs_strerror # global object gs_strerror_ # global object gs_filename_ -# global object gbltinmethod_join_1 def __str__(space, *args_w): kwlist = ["self"] @@ -446,8 +534,8 @@ def __str__(space, w_self_1): - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None - w_15=w_15=None + w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None + w_15=None goto = 1 # startblock while True: @@ -471,7 +559,7 @@ w_12 = space.add(gs_filename_, w_11) w_13 = space.newlist([w_3, w_6, w_9, w_12]) _tup = space.newtuple([w_13]) - w_res_14 = space.call(gbltinmethod_join_1, _tup) + w_res_14 = space.call(gbltinmethod_join, _tup) w_15 = w_res_14 goto = 2 @@ -480,9 +568,128 @@ fastf_EnvironmentError___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## function '__init__' +## firstlineno 217 +##SECTION## +# global declaration +# global object gi_5 + +def __init__(space, *args_w): + kwlist = ["self"] + w_args_1 = space.newtuple(list(args_w[1:])) + _args_w = args_w[:1] + defaults_w = () + funcname = "__init__" + w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) +f_UnicodeEncodeError___init__ = globals().pop("__init__") + +def __init__(space, w_self_3, w_args_1): + + w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None + w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=w_22=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_argc_0 = space.len(w_args_1) + w_2 = space.setattr(w_self_3, gs_args, w_args_1) + w_4 = space.eq(w_argc_0, gi_5) + v5 = space.is_true(w_4) + if v5 == True: + (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, + w_args_1, w_argc_0, w_2, w_4, v5) + goto = 2 + else: + assert v5 == False + w_12 = space.w_None + goto = 3 + + if goto == 2: + w_13 = space.getitem(w_args_7, gi_0) + w_14 = space.setattr(w_self_6, gs_encoding, w_13) + w_15 = space.getitem(w_args_7, gi_1) + w_16 = space.setattr(w_self_6, gs_object, w_15) + w_17 = space.getitem(w_args_7, gi_2) + w_18 = space.setattr(w_self_6, gs_start, w_17) + w_19 = space.getitem(w_args_7, gi_3) + w_20 = space.setattr(w_self_6, gs_end, w_19) + w_21 = space.getitem(w_args_7, gi_4) + w_22 = space.setattr(w_self_6, gs_reason, w_21) + w_12 = space.w_None + goto = 3 + + if goto == 3: + return w_12 +fastf_UnicodeEncodeError___init__ = globals().pop("__init__") + +##SECTION## +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## function '__str__' +## firstlineno 228 +##SECTION## +# global declarations +# global object gs_encoding +# global object gs_encoding_ + +def __str__(space, *args_w): + kwlist = ["self"] + _args_w = args_w + defaults_w = () + funcname = "__str__" + w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___str__(space, w_self_1) +f_UnicodeEncodeError___str__ = globals().pop("__str__") + +def __str__(space, w_self_1): + + w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.getattr(w_self_1, gs_object) + _tup = space.newtuple([w_0]) + w_2 = space.call(space.w_str, _tup) + w_3 = space.add(gs_object_, w_2) + w_4 = space.getattr(w_self_1, gs_end) + _tup = space.newtuple([w_4]) + w_5 = space.call(space.w_str, _tup) + w_6 = space.add(gs_end_, w_5) + w_7 = space.getattr(w_self_1, gs_encoding) + _tup = space.newtuple([w_7]) + w_8 = space.call(space.w_str, _tup) + w_9 = space.add(gs_encoding_, w_8) + w_10 = space.getattr(w_self_1, gs_args) + _tup = space.newtuple([w_10]) + w_11 = space.call(space.w_str, _tup) + w_12 = space.add(gs_args_, w_11) + w_13 = space.getattr(w_self_1, gs_start) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_15 = space.add(gs_start_, w_14) + w_16 = space.getattr(w_self_1, gs_reason) + _tup = space.newtuple([w_16]) + w_17 = space.call(space.w_str, _tup) + w_18 = space.add(gs_reason_, w_17) + w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) + _tup = space.newtuple([w_19]) + w_res_20 = space.call(gbltinmethod_join, _tup) + w_21 = w_res_20 + goto = 2 + + if goto == 2: + return w_21 +fastf_UnicodeEncodeError___str__ = globals().pop("__str__") + +##SECTION## +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 149 +## firstlineno 268 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] @@ -496,10 +703,10 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=None - v18=v18=w_24=w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=None - w_27=w_27=w_28=w_29=w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=None - w_args_7=w_args_7=w_argc_8=w_9=w_10=w_11=w_15=w_16=None + w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=v18=w_24=None + w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=w_27=w_28=w_29=None + w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=w_args_7=w_argc_8=None + w_9=w_10=w_11=w_15=w_16=None goto = 1 # startblock while True: @@ -557,13 +764,10 @@ fastf_SyntaxError___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 161 +## firstlineno 280 ##SECTION## -# global declaration -# global object gbltinmethod_join_2 - def __str__(space, *args_w): kwlist = ["self"] _args_w = args_w @@ -575,7 +779,7 @@ def __str__(space, w_self_1): - w_0=w_0=w_2=w_3=w_4=w_res_5=w_6=None + w_0=w_2=w_3=w_4=w_res_5=w_6=None goto = 1 # startblock while True: @@ -587,7 +791,7 @@ w_3 = space.add(gs_args_, w_2) w_4 = space.newlist([w_3]) _tup = space.newtuple([w_4]) - w_res_5 = space.call(gbltinmethod_join_2, _tup) + w_res_5 = space.call(gbltinmethod_join, _tup) w_6 = w_res_5 goto = 2 @@ -596,9 +800,9 @@ fastf_SyntaxError___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 175 +## firstlineno 294 ##SECTION## # global declaration # global object gs_code @@ -615,11 +819,10 @@ def __init__(space, w_self_4, w_args_1): - w_argc_0=w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=None - v16=v16=w_self_23=w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=None - w_args_31=w_args_31=w_argc_32=w_33=w_34=w_36=w_self_17=w_args_18=None - w_argc_19=w_argc_19=w_20=w_21=w_22=w_26=w_27=w_self_5=w_args_6=None - w_argc_7=w_argc_7=w_8=w_9=w_13=None + w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=v16=w_self_23=None + w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=w_args_31=w_argc_32=None + w_33=w_34=w_36=w_self_17=w_args_18=w_argc_19=w_20=w_21=w_22=w_26=None + w_27=w_self_5=w_args_6=w_argc_7=w_8=w_9=w_13=None goto = 1 # startblock while True: @@ -683,9 +886,9 @@ fastf_SystemExit___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 210 +## firstlineno 329 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] @@ -699,9 +902,8 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None - w_22=w_22=None + w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None + w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=w_22=None goto = 1 # startblock while True: @@ -739,13 +941,10 @@ fastf_UnicodeDecodeError___init__ = globals().pop("__init__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' +## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 221 +## firstlineno 340 ##SECTION## -# global declaration -# global object gbltinmethod_join_4 - def __str__(space, *args_w): kwlist = ["self"] _args_w = args_w @@ -757,8 +956,8 @@ def __str__(space, w_self_1): - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None + w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None goto = 1 # startblock while True: @@ -790,7 +989,7 @@ w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join_4, _tup) + w_res_20 = space.call(gbltinmethod_join, _tup) w_21 = w_res_20 goto = 2 @@ -799,135 +998,14 @@ fastf_UnicodeDecodeError___str__ = globals().pop("__str__") ##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' -## function '__init__' -## firstlineno 270 -##SECTION## -# global declaration -# global object gi_5 - -def __init__(space, *args_w): - kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () - funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) -f_UnicodeEncodeError___init__ = globals().pop("__init__") - -def __init__(space, w_self_3, w_args_1): - - w_argc_0=w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=None - w_9=w_9=w_10=w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None - w_22=w_22=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_5) - v5 = space.is_true(w_4) - if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) - goto = 2 - else: - assert v5 == False - w_12 = space.w_None - goto = 3 - - if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_encoding, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_object, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_start, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_end, w_19) - w_21 = space.getitem(w_args_7, gi_4) - w_22 = space.setattr(w_self_6, gs_reason, w_21) - w_12 = space.w_None - goto = 3 - - if goto == 3: - return w_12 -fastf_UnicodeEncodeError___init__ = globals().pop("__init__") - -##SECTION## -## filename '/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.py' -## function '__str__' -## firstlineno 281 -##SECTION## -# global declarations -# global object gs_encoding -# global object gs_encoding_ -# global object gbltinmethod_join_3 - -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () - funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___str__(space, w_self_1) -f_UnicodeEncodeError___str__ = globals().pop("__str__") - -def __str__(space, w_self_1): - - w_0=w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.getattr(w_self_1, gs_object) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) - w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self_1, gs_end) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) - w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self_1, gs_encoding) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) - w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self_1, gs_args) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) - w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self_1, gs_start) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) - w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self_1, gs_reason) - _tup = space.newtuple([w_16]) - w_17 = space.call(space.w_str, _tup) - w_18 = space.add(gs_reason_, w_17) - w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) - _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join_3, _tup) - w_21 = w_res_20 - goto = 2 - - if goto == 2: - return w_21 -fastf_UnicodeEncodeError___str__ = globals().pop("__str__") - -##SECTION## -## filename 'geninterplevel.py' +## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' ## function 'test_exceptions' -## firstlineno 1253 +## firstlineno 1246 ##SECTION## # global declarations # global object gfunc_test_exceptions # global object gbltinmethod_keys -# global object g46dict +# global object g47dict # global object gs_keys def test_exceptions(space, *args_w): @@ -943,7 +1021,7 @@ def test_exceptions(space, ): """ enumerate all exceptions """ - w_0=w_0=w_1=None + w_0=w_1=None goto = 1 # startblock while True: @@ -964,7 +1042,7 @@ # global object gcls_StandardError # global object gcls_Exception # global object gs___module__ -# global object gs_pypy_appspace__exceptions +# global object gs_exceptions # global object gs___doc__ # global object gs_Exception # global object gs_StandardError @@ -982,10 +1060,14 @@ # global object gcls_KeyError # global object gcls_LookupError # global object gs_LookupError +# global object gs_TaskletExit +# global object gcls_TaskletExit +# global object gcls_SystemExit +# global object gs_SystemExit # global object gs_StopIteration # global object gcls_StopIteration -# global object gs_SyntaxWarning -# global object gcls_SyntaxWarning +# global object gs_PendingDeprecationWarning +# global object gcls_PendingDeprecationWarning # global object gcls_Warning # global object gs_Warning # global object gs_EnvironmentError @@ -998,8 +1080,12 @@ # global object gcls_FloatingPointError # global object gcls_ArithmeticError # global object gs_ArithmeticError -# global object gs_ReferenceError -# global object gcls_ReferenceError +# global object gs_AttributeError +# global object gcls_AttributeError +# global object gs_IndentationError +# global object gcls_IndentationError +# global object gcls_SyntaxError +# global object gs_SyntaxError # global object gs_NameError # global object gcls_NameError # global object gs_OverflowWarning @@ -1010,23 +1096,17 @@ # global object gcls_FutureWarning # global object gs_ZeroDivisionError # global object gcls_ZeroDivisionError -# global object gs_SystemExit -# global object gcls_SystemExit # global object gs_EOFError # global object gcls_EOFError -# global object gs___file__ -# global object gs__home_arigo_svn_pypy_dist_pypy_a # global object gs_TabError # global object gcls_TabError -# global object gcls_IndentationError -# global object gcls_SyntaxError -# global object gs_SyntaxError -# global object gs_IndentationError # global object gs_UnicodeEncodeError # global object gcls_UnicodeEncodeError -# global object gs_SystemError -# global object gcls_SystemError +# global object gs_UnboundLocalError +# global object gcls_UnboundLocalError # global object gs___name__ +# global object gs_ReferenceError +# global object gcls_ReferenceError # global object gs_AssertionError # global object gcls_AssertionError # global object gs_UnicodeDecodeError @@ -1041,16 +1121,16 @@ # global object gcls_KeyboardInterrupt # global object gs_UserWarning # global object gcls_UserWarning -# global object gs_PendingDeprecationWarning -# global object gcls_PendingDeprecationWarning -# global object gs_UnboundLocalError -# global object gcls_UnboundLocalError +# global object gs_SyntaxWarning +# global object gcls_SyntaxWarning # global object gs_NotImplementedError # global object gcls_NotImplementedError -# global object gs_AttributeError -# global object gcls_AttributeError +# global object gs_SystemError +# global object gcls_SystemError # global object gs_OverflowError # global object gcls_OverflowError +# global object gs_WindowsError +# global object gcls_WindowsError # global object gs___init__ # global object gfunc_UnicodeDecodeError___init__ # global object gs___str__ @@ -1066,9 +1146,9 @@ # global object gs_offset # global object gs_print_file_and_line # global object gs_text -# global object gfunc_SystemExit___init__ # global object gfunc_EnvironmentError___init__ # global object gfunc_EnvironmentError___str__ +# global object gfunc_SystemExit___init__ # global object gfunc_KeyError___str__ # global object gfunc_UnicodeTranslateError___init__ # global object gfunc_UnicodeTranslateError___str__ @@ -1087,9 +1167,10 @@ from pypy.interpreter.gateway import interp2app m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) - m.g46dict = space.newdict([]) + m.__doc__ = space.wrap(m.__doc__) + m.g47dict = space.newdict([]) m.gs_keys = space.wrap('keys') - m.gbltinmethod_keys = space.getattr(g46dict, gs_keys) + m.gbltinmethod_keys = space.getattr(g47dict, gs_keys) def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): err = None if len(args_w) < minargs: @@ -1125,8 +1206,8 @@ m.gs_MemoryError = space.wrap('MemoryError') _dic = space.newdict([]) m.gs___module__ = space.wrap('__module__') - m.gs_pypy_appspace__exceptions = space.wrap('pypy.appspace._exceptions') - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + m.gs_exceptions = space.wrap('exceptions') + space.setitem(_dic, gs___module__, gs_exceptions) m.gs___doc__ = space.wrap('__doc__') _doc = space.wrap("""Common base class for all exceptions.""") space.setitem(_dic, gs___doc__, _doc) @@ -1135,7 +1216,7 @@ _args = space.newtuple([gs_Exception, _bases, _dic]) m.gcls_Exception = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for all standard Python exceptions.""") space.setitem(_dic, gs___doc__, _doc) m.gs_StandardError = space.wrap('StandardError') @@ -1143,34 +1224,34 @@ _args = space.newtuple([gs_StandardError, _bases, _dic]) m.gcls_StandardError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Out of memory.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_MemoryError, _bases, _dic]) m.gcls_MemoryError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_MemoryError, gcls_MemoryError) + space.setitem(g47dict, gs_MemoryError, gcls_MemoryError) m.gs_ImportError = space.wrap('ImportError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Import can't find module, or can't find name in module.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_ImportError, _bases, _dic]) m.gcls_ImportError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_ImportError, gcls_ImportError) + space.setitem(g47dict, gs_ImportError, gcls_ImportError) m.gs_RuntimeError = space.wrap('RuntimeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Unspecified run-time error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_RuntimeError, _bases, _dic]) m.gcls_RuntimeError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_RuntimeError, gcls_RuntimeError) + space.setitem(g47dict, gs_RuntimeError, gcls_RuntimeError) m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Inappropriate argument value (of correct type).""") space.setitem(_dic, gs___doc__, _doc) m.gs_ValueError = space.wrap('ValueError') @@ -1178,7 +1259,7 @@ _args = space.newtuple([gs_ValueError, _bases, _dic]) m.gcls_ValueError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Unicode related error.""") space.setitem(_dic, gs___doc__, _doc) m.gs_UnicodeError = space.wrap('UnicodeError') @@ -1186,16 +1267,16 @@ _args = space.newtuple([gs_UnicodeError, _bases, _dic]) m.gcls_UnicodeError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Unicode translation error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeTranslateError, _bases, _dic]) m.gcls_UnicodeTranslateError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) + space.setitem(g47dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) m.gs_KeyError = space.wrap('KeyError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for lookup errors.""") space.setitem(_dic, gs___doc__, _doc) m.gs_LookupError = space.wrap('LookupError') @@ -1203,25 +1284,42 @@ _args = space.newtuple([gs_LookupError, _bases, _dic]) m.gcls_LookupError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Mapping key not found.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_LookupError]) _args = space.newtuple([gs_KeyError, _bases, _dic]) m.gcls_KeyError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_KeyError, gcls_KeyError) + space.setitem(g47dict, gs_KeyError, gcls_KeyError) + m.gs_TaskletExit = space.wrap('TaskletExit') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Request to exit from the interpreter.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_SystemExit = space.wrap('SystemExit') + _bases = space.newtuple([gcls_Exception]) + _args = space.newtuple([gs_SystemExit, _bases, _dic]) + m.gcls_SystemExit = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Request to exit from a tasklet.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_SystemExit]) + _args = space.newtuple([gs_TaskletExit, _bases, _dic]) + m.gcls_TaskletExit = space.call(space.w_type, _args) + space.setitem(g47dict, gs_TaskletExit, gcls_TaskletExit) m.gs_StopIteration = space.wrap('StopIteration') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Signal the end from iterator.next().""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Exception]) _args = space.newtuple([gs_StopIteration, _bases, _dic]) m.gcls_StopIteration = space.call(space.w_type, _args) - space.setitem(g46dict, gs_StopIteration, gcls_StopIteration) - m.gs_SyntaxWarning = space.wrap('SyntaxWarning') + space.setitem(g47dict, gs_StopIteration, gcls_StopIteration) + m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warning categories.""") space.setitem(_dic, gs___doc__, _doc) m.gs_Warning = space.wrap('Warning') @@ -1229,45 +1327,45 @@ _args = space.newtuple([gs_Warning, _bases, _dic]) m.gcls_Warning = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about dubious syntax.""") + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) - m.gcls_SyntaxWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_SyntaxWarning, gcls_SyntaxWarning) + _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) + m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) + space.setitem(g47dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) m.gs_EnvironmentError = space.wrap('EnvironmentError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for I/O related errors.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_EnvironmentError, _bases, _dic]) m.gcls_EnvironmentError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_EnvironmentError, gcls_EnvironmentError) - space.setitem(g46dict, gs_LookupError, gcls_LookupError) + space.setitem(g47dict, gs_EnvironmentError, gcls_EnvironmentError) + space.setitem(g47dict, gs_LookupError, gcls_LookupError) m.gs_OSError = space.wrap('OSError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""OS system call failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_EnvironmentError]) _args = space.newtuple([gs_OSError, _bases, _dic]) m.gcls_OSError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_OSError, gcls_OSError) + space.setitem(g47dict, gs_OSError, gcls_OSError) m.gs_DeprecationWarning = space.wrap('DeprecationWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warnings about deprecated features.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_DeprecationWarning, _bases, _dic]) m.gcls_DeprecationWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_DeprecationWarning, gcls_DeprecationWarning) - space.setitem(g46dict, gs_UnicodeError, gcls_UnicodeError) + space.setitem(g47dict, gs_DeprecationWarning, gcls_DeprecationWarning) + space.setitem(g47dict, gs_UnicodeError, gcls_UnicodeError) m.gs_FloatingPointError = space.wrap('FloatingPointError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for arithmetic errors.""") space.setitem(_dic, gs___doc__, _doc) m.gs_ArithmeticError = space.wrap('ArithmeticError') @@ -1275,252 +1373,250 @@ _args = space.newtuple([gs_ArithmeticError, _bases, _dic]) m.gcls_ArithmeticError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Floating point operation failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_FloatingPointError, _bases, _dic]) m.gcls_FloatingPointError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_FloatingPointError, gcls_FloatingPointError) - m.gs_ReferenceError = space.wrap('ReferenceError') + space.setitem(g47dict, gs_FloatingPointError, gcls_FloatingPointError) + m.gs_AttributeError = space.wrap('AttributeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Weak ref proxy used after referent went away.""") + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Attribute not found.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_ReferenceError, _bases, _dic]) - m.gcls_ReferenceError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_ReferenceError, gcls_ReferenceError) + _args = space.newtuple([gs_AttributeError, _bases, _dic]) + m.gcls_AttributeError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_AttributeError, gcls_AttributeError) + m.gs_IndentationError = space.wrap('IndentationError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Invalid syntax.""") + space.setitem(_dic, gs___doc__, _doc) + m.gs_SyntaxError = space.wrap('SyntaxError') + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_SyntaxError, _bases, _dic]) + m.gcls_SyntaxError = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Improper indentation.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_SyntaxError]) + _args = space.newtuple([gs_IndentationError, _bases, _dic]) + m.gcls_IndentationError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_IndentationError, gcls_IndentationError) m.gs_NameError = space.wrap('NameError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Name not found globally.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_NameError, _bases, _dic]) m.gcls_NameError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_NameError, gcls_NameError) + space.setitem(g47dict, gs_NameError, gcls_NameError) m.gs_OverflowWarning = space.wrap('OverflowWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warnings about numeric overflow.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_OverflowWarning, _bases, _dic]) m.gcls_OverflowWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_OverflowWarning, gcls_OverflowWarning) + space.setitem(g47dict, gs_OverflowWarning, gcls_OverflowWarning) m.gs_IOError = space.wrap('IOError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""I/O operation failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_EnvironmentError]) _args = space.newtuple([gs_IOError, _bases, _dic]) m.gcls_IOError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_IOError, gcls_IOError) - space.setitem(g46dict, gs_ValueError, gcls_ValueError) + space.setitem(g47dict, gs_IOError, gcls_IOError) + space.setitem(g47dict, gs_ValueError, gcls_ValueError) m.gs_FutureWarning = space.wrap('FutureWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warnings about constructs that will change semantically in the future.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_FutureWarning, _bases, _dic]) m.gcls_FutureWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_FutureWarning, gcls_FutureWarning) + space.setitem(g47dict, gs_FutureWarning, gcls_FutureWarning) m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Second argument to a division or modulo operation was zero.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_ZeroDivisionError, _bases, _dic]) m.gcls_ZeroDivisionError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) - m.gs_SystemExit = space.wrap('SystemExit') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Request to exit from the interpreter.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_Exception]) - _args = space.newtuple([gs_SystemExit, _bases, _dic]) - m.gcls_SystemExit = space.call(space.w_type, _args) - space.setitem(g46dict, gs_SystemExit, gcls_SystemExit) - space.setitem(g46dict, gs_Exception, gcls_Exception) + space.setitem(g47dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) + space.setitem(g47dict, gs_SystemExit, gcls_SystemExit) + space.setitem(g47dict, gs_Exception, gcls_Exception) m.gs_EOFError = space.wrap('EOFError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Read beyond end of file.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_EOFError, _bases, _dic]) m.gcls_EOFError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_EOFError, gcls_EOFError) - space.setitem(g46dict, gs_StandardError, gcls_StandardError) - m.gs___file__ = space.wrap('__file__') - m.gs__home_arigo_svn_pypy_dist_pypy_a = space.wrap('/home/arigo/svn/pypy/dist/pypy/appspace/_exceptions.pyc') - space.setitem(g46dict, gs___file__, gs__home_arigo_svn_pypy_dist_pypy_a) + space.setitem(g47dict, gs_EOFError, gcls_EOFError) + space.setitem(g47dict, gs_StandardError, gcls_StandardError) m.gs_TabError = space.wrap('TabError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Invalid syntax.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_SyntaxError = space.wrap('SyntaxError') - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_SyntaxError, _bases, _dic]) - m.gcls_SyntaxError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Improper indentation.""") - space.setitem(_dic, gs___doc__, _doc) - m.gs_IndentationError = space.wrap('IndentationError') - _bases = space.newtuple([gcls_SyntaxError]) - _args = space.newtuple([gs_IndentationError, _bases, _dic]) - m.gcls_IndentationError = space.call(space.w_type, _args) - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Improper mixture of spaces and tabs.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_IndentationError]) _args = space.newtuple([gs_TabError, _bases, _dic]) m.gcls_TabError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_TabError, gcls_TabError) - space.setitem(g46dict, gs_SyntaxError, gcls_SyntaxError) + space.setitem(g47dict, gs_TabError, gcls_TabError) + space.setitem(g47dict, gs_SyntaxError, gcls_SyntaxError) m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Unicode encoding error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeEncodeError, _bases, _dic]) m.gcls_UnicodeEncodeError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) - m.gs_SystemError = space.wrap('SystemError') + space.setitem(g47dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) + m.gs_UnboundLocalError = space.wrap('UnboundLocalError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Internal error in the Python interpreter. - - Please report this to the Python maintainer, along with the traceback, - the Python version, and the hardware/OS platform and version.""") + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Local name referenced but not bound to a value.""") space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_SystemError, _bases, _dic]) - m.gcls_SystemError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_SystemError, gcls_SystemError) + _bases = space.newtuple([gcls_NameError]) + _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) + m.gcls_UnboundLocalError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_UnboundLocalError, gcls_UnboundLocalError) m.gs___name__ = space.wrap('__name__') - space.setitem(g46dict, gs___name__, gs_pypy_appspace__exceptions) - space.setitem(g46dict, gs_IndentationError, gcls_IndentationError) + space.setitem(g47dict, gs___name__, gs_exceptions) + m.gs_ReferenceError = space.wrap('ReferenceError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Weak ref proxy used after referent went away.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_StandardError]) + _args = space.newtuple([gs_ReferenceError, _bases, _dic]) + m.gcls_ReferenceError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_ReferenceError, gcls_ReferenceError) m.gs_AssertionError = space.wrap('AssertionError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Assertion failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_AssertionError, _bases, _dic]) m.gcls_AssertionError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_AssertionError, gcls_AssertionError) + space.setitem(g47dict, gs_AssertionError, gcls_AssertionError) m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Unicode decoding error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeDecodeError, _bases, _dic]) m.gcls_UnicodeDecodeError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) + space.setitem(g47dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) m.gs_TypeError = space.wrap('TypeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Inappropriate argument type.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_TypeError, _bases, _dic]) m.gcls_TypeError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_TypeError, gcls_TypeError) + space.setitem(g47dict, gs_TypeError, gcls_TypeError) m.gs_IndexError = space.wrap('IndexError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Sequence index out of range.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_LookupError]) _args = space.newtuple([gs_IndexError, _bases, _dic]) m.gcls_IndexError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_IndexError, gcls_IndexError) + space.setitem(g47dict, gs_IndexError, gcls_IndexError) m.gs_RuntimeWarning = space.wrap('RuntimeWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warnings about dubious runtime behavior.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_RuntimeWarning, _bases, _dic]) m.gcls_RuntimeWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_RuntimeWarning, gcls_RuntimeWarning) + space.setitem(g47dict, gs_RuntimeWarning, gcls_RuntimeWarning) m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Program interrupted by user.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_KeyboardInterrupt, _bases, _dic]) m.gcls_KeyboardInterrupt = space.call(space.w_type, _args) - space.setitem(g46dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) - space.setitem(g46dict, gs___doc__, space.w_None) + space.setitem(g47dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) m.gs_UserWarning = space.wrap('UserWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Base class for warnings generated by user code.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_UserWarning, _bases, _dic]) m.gcls_UserWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_UserWarning, gcls_UserWarning) - m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') + space.setitem(g47dict, gs_UserWarning, gcls_UserWarning) + m.gs_SyntaxWarning = space.wrap('SyntaxWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Base class for warnings about dubious syntax.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) - _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) - m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) - space.setitem(g46dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) - m.gs_UnboundLocalError = space.wrap('UnboundLocalError') - _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Local name referenced but not bound to a value.""") - space.setitem(_dic, gs___doc__, _doc) - _bases = space.newtuple([gcls_NameError]) - _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) - m.gcls_UnboundLocalError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_UnboundLocalError, gcls_UnboundLocalError) - space.setitem(g46dict, gs_ArithmeticError, gcls_ArithmeticError) - space.setitem(g46dict, gs_Warning, gcls_Warning) + _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) + m.gcls_SyntaxWarning = space.call(space.w_type, _args) + space.setitem(g47dict, gs_SyntaxWarning, gcls_SyntaxWarning) + space.setitem(g47dict, gs___doc__, __doc__) + space.setitem(g47dict, gs_ArithmeticError, gcls_ArithmeticError) + space.setitem(g47dict, gs_Warning, gcls_Warning) m.gs_NotImplementedError = space.wrap('NotImplementedError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Method or function hasn't been implemented yet.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_RuntimeError]) _args = space.newtuple([gs_NotImplementedError, _bases, _dic]) m.gcls_NotImplementedError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_NotImplementedError, gcls_NotImplementedError) - m.gs_AttributeError = space.wrap('AttributeError') + space.setitem(g47dict, gs_NotImplementedError, gcls_NotImplementedError) + m.gs_SystemError = space.wrap('SystemError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) - _doc = space.wrap("""Attribute not found.""") + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""Internal error in the Python interpreter. + + Please report this to the Python maintainer, along with the traceback, + the Python version, and the hardware/OS platform and version.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) - _args = space.newtuple([gs_AttributeError, _bases, _dic]) - m.gcls_AttributeError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_AttributeError, gcls_AttributeError) + _args = space.newtuple([gs_SystemError, _bases, _dic]) + m.gcls_SystemError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_SystemError, gcls_SystemError) m.gs_OverflowError = space.wrap('OverflowError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_pypy_appspace__exceptions) + space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Result too large to be represented.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_OverflowError, _bases, _dic]) m.gcls_OverflowError = space.call(space.w_type, _args) - space.setitem(g46dict, gs_OverflowError, gcls_OverflowError) + space.setitem(g47dict, gs_OverflowError, gcls_OverflowError) + m.gs_WindowsError = space.wrap('WindowsError') + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs_exceptions) + _doc = space.wrap("""MS-Windows OS system call failed.""") + space.setitem(_dic, gs___doc__, _doc) + _bases = space.newtuple([gcls_OSError]) + _args = space.newtuple([gs_WindowsError, _bases, _dic]) + m.gcls_WindowsError = space.call(space.w_type, _args) + space.setitem(g47dict, gs_WindowsError, gcls_WindowsError) m.gs___init__ = space.wrap('__init__') m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) @@ -1548,12 +1644,12 @@ space.setattr(gcls_SyntaxError, gs_print_file_and_line, space.w_None) m.gs_text = space.wrap('text') space.setattr(gcls_SyntaxError, gs_text, space.w_None) - m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) - space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) m.gfunc_EnvironmentError___init__ = space.wrap(interp2app(f_EnvironmentError___init__)) space.setattr(gcls_EnvironmentError, gs___init__, gfunc_EnvironmentError___init__) m.gfunc_EnvironmentError___str__ = space.wrap(interp2app(f_EnvironmentError___str__)) space.setattr(gcls_EnvironmentError, gs___str__, gfunc_EnvironmentError___str__) + m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) + space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) m.gfunc_KeyError___str__ = space.wrap(interp2app(f_KeyError___str__)) space.setattr(gcls_KeyError, gs___str__, gfunc_KeyError___str__) m.gfunc_UnicodeTranslateError___init__ = space.wrap(interp2app(f_UnicodeTranslateError___init__)) @@ -1585,19 +1681,15 @@ m.gi_4 = space.newint(4) m.gi_2 = space.newint(2) m.gi_3 = space.newint(3) + m.gs_code = space.wrap('code') m.gs_errno = space.wrap('errno') m.gs_errno_ = space.wrap('errno=') m.gs_strerror = space.wrap('strerror') m.gs_strerror_ = space.wrap('strerror=') m.gs_filename_ = space.wrap('filename=') - m.gbltinmethod_join_1 = space.getattr(gs__, gs_join) - m.gs_code = space.wrap('code') - m.gbltinmethod_join_2 = space.getattr(gs__, gs_join) m.gs_encoding = space.wrap('encoding') m.gs_encoding_ = space.wrap('encoding=') - m.gbltinmethod_join_3 = space.getattr(gs__, gs_join) m.gi_5 = space.newint(5) - m.gbltinmethod_join_4 = space.getattr(gs__, gs_join) # entry point: test_exceptions, gfunc_test_exceptions) if __name__ == "__main__": Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Sat Jan 29 01:44:32 2005 @@ -230,6 +230,7 @@ setattr(self, "w_"+excname, w_obj) # into space for_builtins[excname] = w_obj # into builtins self.setitem(w_dic, self.wrap(excname), w_obj) # into exc + self.setitem(w_dic, self.wrap("__doc__"), ex.__doc__) finally: del self.call # revert to the class' method @@ -237,6 +238,7 @@ # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module + m = Module(self, self.wrap("exceptions"), w_dic) w_exceptions = self.wrap(m) self.sys.setbuiltinmodule(w_exceptions, 'exceptions') Modified: pypy/dist/pypy/tool/_enum_exceptions.py ============================================================================== --- pypy/dist/pypy/tool/_enum_exceptions.py (original) +++ pypy/dist/pypy/tool/_enum_exceptions.py Sat Jan 29 01:44:32 2005 @@ -6,6 +6,8 @@ import types +from pypy.tool.sourcetools import render_docstr + def classOfAttribute(klass, attname): if attname in klass.__dict__: return klass @@ -19,8 +21,7 @@ def makeExceptionsTemplate(f=None): - def enumExceptionsInOrder(): - import exceptions + def enumClassesInOrder(module): seen = {} ordered = [] @@ -31,7 +32,7 @@ enumerateOne(each) ordered.append(exc) - for each in exceptions.__dict__.values(): + for each in module.__dict__.values(): if isinstance(each, (types.ClassType, type)) and \ each not in seen: enumerateOne(each) @@ -41,7 +42,11 @@ if not f: f = sys.stdout - for exc in enumExceptionsInOrder(): + import exceptions + for line in render_docstr(exceptions, ""): + print >> f, line + + for exc in enumClassesInOrder(exceptions): name = exc.__name__ bases = exc.__bases__ doc = exc.__doc__ @@ -57,6 +62,7 @@ if classOfAttribute(exc, attname) is exc: obj = getattr(exc, attname) (simple, difficult)[callable(obj)].append( (attname, obj) ) + print >> f print >> f, "class %s%s:" % (name, bases) if doc: print >> f, ' """%s"""' % doc @@ -78,7 +84,6 @@ except ValueError, e: print >> f, " # %s" % e print >> f, " # please implement %s.%s (%r)" % (name, attname, meth) - print >> f def tryGenerate__getitem__(exc): for args in (), (1, 2, 3): @@ -325,7 +330,9 @@ yield " return res" if __name__ == "__main__": - import pypy.appspace, os - targetdir = os.path.dirname(pypy.appspace.__file__) - fname = os.path.join(targetdir, "_exceptions.py") - makeExceptionsTemplate(file(fname, "w")) + import pypy, os + prefix = os.path.dirname(pypy.__file__) + libdir = os.path.join(prefix, "lib") + fname = "_exceptions.pre.py" + fpath = os.path.join(libdir, fname) + makeExceptionsTemplate(file(fpath, "w")) Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Sat Jan 29 01:44:32 2005 @@ -1,21 +1,19 @@ # a couple of support functions which # help with generating Python source. -# this script is used for extracting -# the information available for exceptions -# via introspection. -# The idea is to use it once to create -# a template for a re-birth of exceptions.py - -def render_docstr(func, indent_str, q='"""', redo=True): - """render a docstring as a sequenceof lines """ - doc = func.__doc__ +def render_docstr(func, indent_str='', closing_str='', q='"""', redo=True): + """ Render a docstring as a sequence of lines. + The argument is either a docstring or an object""" + if type(func) is not str: + doc = func.__doc__ + else: + doc = func if doc is None: return [] - doc = indent_str + q + doc.replace(q, "\\"+q) + q + doc = indent_str + q + doc.replace(q, "\\"+q) + q + closing_str doc2 = doc if q in doc and redo: - doc2 = render_docstr(func, indent_str, "'''", False) + doc2 = render_docstr(func, indent_str, closing_str, "'''", False) if not redo: return doc # recursion case doc = (doc, doc2)[len(doc2) < len(doc)] Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Sat Jan 29 01:44:32 2005 @@ -42,6 +42,7 @@ from pypy.interpreter.gateway import app2interp, interp2app +from pypy.tool.sourcetools import render_docstr # ____________________________________________________________ @@ -103,6 +104,7 @@ self.translator = translator self.modname = self.trans_funcname(modname or uniquemodulename(translator.functions[0].__name__)) + self.moddict = None # the dict if we translate a module self.rpynames = {Constant(None).key: 'space.w_None', Constant(False).key: 'space.w_False', Constant(True).key: 'space.w_True', @@ -125,11 +127,6 @@ for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - # XXX I guess it is cleaner to use the flow space? - # we just want to look into the operations, - # but we don't break into the implementation. - # Or should it be the base space, ARMIN? - #self.space = StdObjSpace() # for introspection self.space = FlowObjSpace() # for introspection self.use_fast_call = False @@ -219,7 +216,8 @@ ass = var+"=" if not res or len(res[-1]) >= margin: res.append(ass) - res[-1] += ass + else: + res[-1] += ass res = [line + nonestr for line in res] return res @@ -570,8 +568,7 @@ if cls.__doc__ is not None: sdoc = self.nameof("__doc__") - lines = list(self.render_docstr(cls, "_doc = space.wrap(")) - lines[-1] +=")" + lines = list(render_docstr(cls, "_doc = space.wrap(", ")")) self.initcode.extend(lines) self.initcode.appendnew("space.setitem(_dic, %s, _doc)" % ( self.nameof("__doc__"),)) @@ -754,7 +751,19 @@ } # header print >> f, self.RPY_HEADER + print >> f + # doc + if self.moddict and self.moddict.get("__doc__"): + doc = self.moddict["__doc__"] + for line in render_docstr(doc): + print >> f, line + print >> f + # make sure it is not rendered again + key = Constant(doc).key + self.rpynames[key] = "__doc__" + self.seennames["__doc__"] = 1 + self.initcode.append("m.__doc__ = space.wrap(m.__doc__)") # function implementations while self.pendingfunctions: func = self.pendingfunctions.pop() @@ -792,20 +801,6 @@ for name in g: pass # self.initcode.append('# REGISTER_GLOBAL(%s)' % (name,)) del g[:] - - - def render_docstr(self, func, indent_str, q='"""', redo=True): - doc = func.__doc__ - if doc is None: - return [] - doc = indent_str + q + doc.replace(q, "\\"+q) + q - doc2 = doc - if q in doc and redo: - doc2 = self.render_docstr(func, indent_str, "'''", False) - if not redo: - return doc # recursion case - doc = (doc, doc2)[len(doc2) < len(doc)] - return [line for line in doc.split('\n')] def gen_rpyfunction(self, func): @@ -825,7 +820,7 @@ self.gen_global_declarations() # print header - doc_lines = self.render_docstr(func, " ") + doc_lines = render_docstr(func, " ") cname = self.nameof(func) assert cname.startswith('gfunc_') f_name = 'f_' + cname[6:] @@ -1240,21 +1235,19 @@ return res1, res2 def test_exceptions_helper(): - def demoduliseDict(mod): - # get the raw dict without module stuff like __builtins__ - dic = mod.__dict__.copy() - bad = ("__builtins__", ) # anything else? - for name in bad: - if name in dic: - del dic[name] - return dic - from pypy.appspace import _exceptions - a = demoduliseDict(_exceptions) + import pypy + prefix = os.path.dirname(pypy.__file__) + libdir = os.path.join(prefix, "lib") + fname = "_exceptions.py" + fpath = os.path.join(libdir, fname) + dic = {"__name__": "exceptions"} + execfile(fpath, dic) + del dic["__builtins__"] def test_exceptions(): """ enumerate all exceptions """ - return a.keys() + return dic.keys() #return [thing for thing in _exceptions.__dict__.values()] - return test_exceptions + return dic, test_exceptions def all_entries(): res = [func() for func in entrypoints[:-1]] @@ -1284,11 +1277,13 @@ if appdir not in sys.path: sys.path.insert(0, appdir) + dic = None if entrypoint.__name__.endswith("_helper"): - entrypoint = entrypoint() + dic, entrypoint = entrypoint() t = Translator(entrypoint, verbose=False, simplifying=True) gen = GenRpy(t) gen.use_fast_call = True + if dic: gen.moddict = dic import pypy.appspace.generated as tmp pth = os.path.dirname(tmp.__file__) ftmpname = "/tmp/look.py" @@ -1305,7 +1300,7 @@ """ this thingy is generating the whole interpreter in itself""" # but doesn't work, my goto's give a problem for flow space dic = {"__builtins__": __builtins__, "__name__": "__main__"} - execfile("d:/tmp/look.py", dic) + execfile("/tmp/look.py", dic) def test(): f_ff(space, 2, 3) @@ -1313,4 +1308,4 @@ t = Translator(test, verbose=False, simplifying=True) gen = GenRpy(t) - gen.gen_source("d:/tmp/look2.py") + gen.gen_source("/tmp/look2.py") From tismer at codespeak.net Sat Jan 29 02:33:41 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 02:33:41 +0100 (MET) Subject: [pypy-svn] r8681 - pypy/dist/pypy/module Message-ID: <20050129013341.EB1B927B96@code1.codespeak.net> Author: tismer Date: Sat Jan 29 02:33:41 2005 New Revision: 8681 Modified: pypy/dist/pypy/module/sysmodule.py Log: a subtle bug about exceptions. Holger tried to blame me about the generated exceptions module, but we could not find anything wrong. Finally we found out that everything was fine but the exit() function. This needs to use the com.ma version of raise. Why? CPython does it the same way, and by this way, normalize_exception does an extra de-tupelizing on the argument. :-) I think this is really an artifact, a wart in CPython. But well, right now we stay compatible. By the way, it would be easy and really nice to allow to raise any object,not just Exceptions. And in the case of any object, we would *not* create tracebacks, but treat that as an intended control flow exception. Holger and I are dreaming of raise 42 and try:... except int, val: # do something :-) Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Sat Jan 29 02:33:41 2005 @@ -41,7 +41,10 @@ __excepthook__ = excepthook # this is exactly like in CPython def exit(exitcode=0): - raise SystemExit(exitcode) + # note that we cannot use SystemExit(exitcode) here. + # The comma version leads to an extra de-tupelizing + # in normalize_exception, which is exactlylike CPython. + raise SystemExit, exitcode def displayhook(obj): if obj is not None: From sanxiyn at codespeak.net Sat Jan 29 06:27:47 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 06:27:47 +0100 (MET) Subject: [pypy-svn] r8682 - in pypy/dist/pypy: appspace lib Message-ID: <20050129052747.5DEE727B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 06:27:47 2005 New Revision: 8682 Added: pypy/dist/pypy/lib/re.py - copied unchanged from r8681, pypy/dist/pypy/appspace/re.py Removed: pypy/dist/pypy/appspace/re.py Log: file move Deleted: /pypy/dist/pypy/appspace/re.py ============================================================================== --- /pypy/dist/pypy/appspace/re.py Sat Jan 29 06:27:47 2005 +++ (empty file) @@ -1,29 +0,0 @@ -from dumbre import Pattern -# from plexre import Pattern - - -# From CPython -def escape(pattern): - "Escape all non-alphanumeric characters in pattern." - s = list(pattern) - for i in range(len(pattern)): - c = pattern[i] - if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"): - if c == "\000": - s[i] = "\\000" - else: - s[i] = "\\" + c - return ''.join(s) - - -_cache = {} - -def compile(pattern, flags=0): - if (pattern, flags) in _cache: - return _cache[pattern, flags] - compiled = Pattern(pattern, flags) - _cache[pattern, flags] = compiled - return compiled - -def match(pattern, string, flags=0): - return compile(pattern, flags).match(string) From sanxiyn at codespeak.net Sat Jan 29 06:35:16 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 06:35:16 +0100 (MET) Subject: [pypy-svn] r8683 - pypy/dist/pypy/lib Message-ID: <20050129053516.A5DA227B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 06:35:16 2005 New Revision: 8683 Added: pypy/dist/pypy/lib/sre_adapt.py Modified: pypy/dist/pypy/lib/re.py Log: sre_adapt, providing Pattern just like dumbre and plexre Modified: pypy/dist/pypy/lib/re.py ============================================================================== --- pypy/dist/pypy/lib/re.py (original) +++ pypy/dist/pypy/lib/re.py Sat Jan 29 06:35:16 2005 @@ -1,5 +1,6 @@ from dumbre import Pattern # from plexre import Pattern +# from sre_adapt import Pattern # From CPython Added: pypy/dist/pypy/lib/sre_adapt.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/sre_adapt.py Sat Jan 29 06:35:16 2005 @@ -0,0 +1,2 @@ +import sre_compile +Pattern = sre_compile.compile From sanxiyn at codespeak.net Sat Jan 29 06:43:29 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 06:43:29 +0100 (MET) Subject: [pypy-svn] r8684 - in pypy/dist/pypy: appspace lib Message-ID: <20050129054329.D9A0B27B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 06:43:29 2005 New Revision: 8684 Added: pypy/dist/pypy/lib/warnings.py - copied unchanged from r8683, pypy/dist/pypy/appspace/warnings.py Removed: pypy/dist/pypy/appspace/warnings.py Log: file move Deleted: /pypy/dist/pypy/appspace/warnings.py ============================================================================== --- /pypy/dist/pypy/appspace/warnings.py Sat Jan 29 06:43:29 2005 +++ (empty file) @@ -1,253 +0,0 @@ -"""Python part of the warnings subsystem.""" - -# Note: function level imports should *not* be used -# in this module as it may cause import lock deadlock. -# See bug 683658. -import sys, types -import linecache - -__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", - "resetwarnings"] - -# filters contains a sequence of filter 5-tuples -# The components of the 5-tuple are: -# - an action: error, ignore, always, default, module, or once -# - a compiled regex that must match the warning message -# - a class representing the warning category -# - a compiled regex that must match the module that is being warned -# - a line number for the line being warning, or 0 to mean any line -# If either if the compiled regexs are None, match anything. -filters = [] -defaultaction = "default" -onceregistry = {} - -def warn(message, category=None, stacklevel=1): - """Issue a warning, or maybe ignore it or raise an exception.""" - # Check if message is already a Warning object - if isinstance(message, Warning): - category = message.__class__ - # Check category argument - if category is None: - category = UserWarning - assert issubclass(category, Warning) - # Get context information - try: - caller = sys._getframe(stacklevel) - except ValueError: - globals = sys.__dict__ - lineno = 1 - else: - globals = caller.f_globals - lineno = caller.f_lineno - if '__name__' in globals: - module = globals['__name__'] - else: - module = "" - filename = globals.get('__file__') - if filename: - fnl = filename.lower() - if fnl.endswith(".pyc") or fnl.endswith(".pyo"): - filename = filename[:-1] - else: - if module == "__main__": - filename = sys.argv[0] - if not filename: - filename = module - registry = globals.setdefault("__warningregistry__", {}) - warn_explicit(message, category, filename, lineno, module, registry) - -def warn_explicit(message, category, filename, lineno, - module=None, registry=None): - if module is None: - module = filename - if module[-3:].lower() == ".py": - module = module[:-3] # XXX What about leading pathname? - if registry is None: - registry = {} - if isinstance(message, Warning): - text = str(message) - category = message.__class__ - else: - text = message - message = category(message) - key = (text, category, lineno) - # Quick test for common case - if registry.get(key): - return - # Search the filters - for item in filters: - action, msg, cat, mod, ln = item - if ((msg is None or msg.match(text)) and - issubclass(category, cat) and - (msg is None or mod.match(module)) and - (ln == 0 or lineno == ln)): - break - else: - action = defaultaction - # Early exit actions - if action == "ignore": - registry[key] = 1 - return - if action == "error": - raise message - # Other actions - if action == "once": - registry[key] = 1 - oncekey = (text, category) - if onceregistry.get(oncekey): - return - onceregistry[oncekey] = 1 - elif action == "always": - pass - elif action == "module": - registry[key] = 1 - altkey = (text, category, 0) - if registry.get(altkey): - return - registry[altkey] = 1 - elif action == "default": - registry[key] = 1 - else: - # Unrecognized actions are errors - raise RuntimeError( - "Unrecognized action (%s) in warnings.filters:\n %s" % - (`action`, str(item))) - # Print message and context - showwarning(message, category, filename, lineno) - -def showwarning(message, category, filename, lineno, file=None): - """Hook to write a warning to a file; replace if you like.""" - if file is None: - file = sys.stderr - try: - file.write(formatwarning(message, category, filename, lineno)) - except IOError: - pass # the file (probably stderr) is invalid - this warning gets lost. - -def formatwarning(message, category, filename, lineno): - """Function to format a warning the standard way.""" - s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) - line = linecache.getline(filename, lineno).strip() - if line: - s = s + " " + line + "\n" - return s - -def filterwarnings(action, message="", category=Warning, module="", lineno=0, - append=0): - """Insert an entry into the list of warnings filters (at the front). - - Use assertions to check that all arguments have the right type.""" - import re - assert action in ("error", "ignore", "always", "default", "module", - "once"), "invalid action: %s" % `action` - assert isinstance(message, basestring), "message must be a string" - #assert isinstance(category, types.ClassType), "category must be a class" - assert issubclass(category, Warning), "category must be a Warning subclass" - assert isinstance(module, basestring), "module must be a string" - assert isinstance(lineno, int) and lineno >= 0, \ - "lineno must be an int >= 0" - item = (action, re.compile(message, re.I), category, - re.compile(module), lineno) - if append: - filters.append(item) - else: - filters.insert(0, item) - -def simplefilter(action, category=Warning, lineno=0, append=0): - """Insert a simple entry into the list of warnings filters (at the front). - - A simple filter matches all modules and messages. - """ - assert action in ("error", "ignore", "always", "default", "module", - "once"), "invalid action: %s" % `action` - assert isinstance(lineno, int) and lineno >= 0, \ - "lineno must be an int >= 0" - item = (action, None, category, None, lineno) - if append: - filters.append(item) - else: - filters.insert(0, item) - -def resetwarnings(): - """Clear the list of warning filters, so that no filters are active.""" - filters[:] = [] - -class _OptionError(Exception): - """Exception used by option processing helpers.""" - pass - -# Helper to process -W options passed via sys.warnoptions -def _processoptions(args): - for arg in args: - try: - _setoption(arg) - except _OptionError, msg: - print >>sys.stderr, "Invalid -W option ignored:", msg - -# Helper for _processoptions() -def _setoption(arg): - import re - parts = arg.split(':') - if len(parts) > 5: - raise _OptionError("too many fields (max 5): %s" % `arg`) - while len(parts) < 5: - parts.append('') - action, message, category, module, lineno = [s.strip() - for s in parts] - action = _getaction(action) - message = re.escape(message) - category = _getcategory(category) - module = re.escape(module) - if module: - module = module + '$' - if lineno: - try: - lineno = int(lineno) - if lineno < 0: - raise ValueError - except (ValueError, OverflowError): - raise _OptionError("invalid lineno %s" % `lineno`) - else: - lineno = 0 - filterwarnings(action, message, category, module, lineno) - -# Helper for _setoption() -def _getaction(action): - if not action: - return "default" - if action == "all": return "always" # Alias - for a in ['default', 'always', 'ignore', 'module', 'once', 'error']: - if a.startswith(action): - return a - raise _OptionError("invalid action: %s" % `action`) - -# Helper for _setoption() -def _getcategory(category): - import re - if not category: - return Warning - if re.match("^[a-zA-Z0-9_]+$", category): - try: - cat = eval(category) - except NameError: - raise _OptionError("unknown warning category: %s" % `category`) - else: - i = category.rfind(".") - module = category[:i] - klass = category[i+1:] - try: - m = __import__(module, None, None, [klass]) - except ImportError: - raise _OptionError("invalid module name: %s" % `module`) - try: - cat = getattr(m, klass) - except AttributeError: - raise _OptionError("unknown warning category: %s" % `category`) - if not issubclass(cat, Warning): # or not isinstance(cat, types.ClassType) - raise _OptionError("invalid warning category: %s" % `category`) - return cat - -# Module initialization -_processoptions(sys.warnoptions) -simplefilter("ignore", category=OverflowWarning, append=1) -simplefilter("ignore", category=PendingDeprecationWarning, append=1) From sanxiyn at codespeak.net Sat Jan 29 06:47:24 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 06:47:24 +0100 (MET) Subject: [pypy-svn] r8685 - pypy/dist/pypy/lib Message-ID: <20050129054724.6610627B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 06:47:24 2005 New Revision: 8685 Removed: pypy/dist/pypy/lib/sre_parse.py Log: This is identical to one in lib-python-2.3.4 Deleted: /pypy/dist/pypy/lib/sre_parse.py ============================================================================== --- /pypy/dist/pypy/lib/sre_parse.py Sat Jan 29 06:47:24 2005 +++ (empty file) @@ -1,739 +0,0 @@ -# -# Secret Labs' Regular Expression Engine -# -# convert re-style regular expression to sre pattern -# -# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. -# -# See the sre.py file for information on usage and redistribution. -# - -"""Internal support module for sre""" - -# XXX: show string offset and offending character for all errors - -# this module works under 1.5.2 and later. don't use string methods -import string, sys - -from sre_constants import * - -SPECIAL_CHARS = ".\\[{()*+?^$|" -REPEAT_CHARS = "*+?{" - -DIGITS = tuple("0123456789") - -OCTDIGITS = tuple("01234567") -HEXDIGITS = tuple("0123456789abcdefABCDEF") - -WHITESPACE = tuple(" \t\n\r\v\f") - -ESCAPES = { - r"\a": (LITERAL, ord("\a")), - r"\b": (LITERAL, ord("\b")), - r"\f": (LITERAL, ord("\f")), - r"\n": (LITERAL, ord("\n")), - r"\r": (LITERAL, ord("\r")), - r"\t": (LITERAL, ord("\t")), - r"\v": (LITERAL, ord("\v")), - r"\\": (LITERAL, ord("\\")) -} - -CATEGORIES = { - r"\A": (AT, AT_BEGINNING_STRING), # start of string - r"\b": (AT, AT_BOUNDARY), - r"\B": (AT, AT_NON_BOUNDARY), - r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]), - r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]), - r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]), - r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]), - r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]), - r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]), - r"\Z": (AT, AT_END_STRING), # end of string -} - -FLAGS = { - # standard flags - "i": SRE_FLAG_IGNORECASE, - "L": SRE_FLAG_LOCALE, - "m": SRE_FLAG_MULTILINE, - "s": SRE_FLAG_DOTALL, - "x": SRE_FLAG_VERBOSE, - # extensions - "t": SRE_FLAG_TEMPLATE, - "u": SRE_FLAG_UNICODE, -} - -# figure out best way to convert hex/octal numbers to integers -try: - int("10", 8) - atoi = int # 2.0 and later -except TypeError: - atoi = string.atoi # 1.5.2 - -class Pattern: - # master pattern object. keeps track of global attributes - def __init__(self): - self.flags = 0 - self.open = [] - self.groups = 1 - self.groupdict = {} - def opengroup(self, name=None): - gid = self.groups - self.groups = gid + 1 - if name is not None: - ogid = self.groupdict.get(name, None) - if ogid is not None: - raise error, ("redefinition of group name %s as group %d; " - "was group %d" % (repr(name), gid, ogid)) - self.groupdict[name] = gid - self.open.append(gid) - return gid - def closegroup(self, gid): - self.open.remove(gid) - def checkgroup(self, gid): - return gid < self.groups and gid not in self.open - -class SubPattern: - # a subpattern, in intermediate form - def __init__(self, pattern, data=None): - self.pattern = pattern - if data is None: - data = [] - self.data = data - self.width = None - def dump(self, level=0): - nl = 1 - for op, av in self.data: - print level*" " + op,; nl = 0 - if op == "in": - # member sublanguage - print; nl = 1 - for op, a in av: - print (level+1)*" " + op, a - elif op == "branch": - print; nl = 1 - i = 0 - for a in av[1]: - if i > 0: - print level*" " + "or" - a.dump(level+1); nl = 1 - i = i + 1 - elif type(av) in (type(()), type([])): - for a in av: - if isinstance(a, SubPattern): - if not nl: print - a.dump(level+1); nl = 1 - else: - print a, ; nl = 0 - else: - print av, ; nl = 0 - if not nl: print - def __repr__(self): - return repr(self.data) - def __len__(self): - return len(self.data) - def __delitem__(self, index): - del self.data[index] - def __getitem__(self, index): - return self.data[index] - def __setitem__(self, index, code): - self.data[index] = code - def __getslice__(self, start, stop): - return SubPattern(self.pattern, self.data[start:stop]) - def insert(self, index, code): - self.data.insert(index, code) - def append(self, code): - self.data.append(code) - def getwidth(self): - # determine the width (min, max) for this subpattern - if self.width: - return self.width - lo = hi = 0L - for op, av in self.data: - if op is BRANCH: - i = sys.maxint - j = 0 - for av in av[1]: - l, h = av.getwidth() - i = min(i, l) - j = max(j, h) - lo = lo + i - hi = hi + j - elif op is CALL: - i, j = av.getwidth() - lo = lo + i - hi = hi + j - elif op is SUBPATTERN: - i, j = av[1].getwidth() - lo = lo + i - hi = hi + j - elif op in (MIN_REPEAT, MAX_REPEAT): - i, j = av[2].getwidth() - lo = lo + long(i) * av[0] - hi = hi + long(j) * av[1] - elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY): - lo = lo + 1 - hi = hi + 1 - elif op == SUCCESS: - break - self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint)) - return self.width - -class Tokenizer: - def __init__(self, string): - self.string = string - self.index = 0 - self.__next() - def __next(self): - if self.index >= len(self.string): - self.next = None - return - char = self.string[self.index] - if char[0] == "\\": - try: - c = self.string[self.index + 1] - except IndexError: - raise error, "bogus escape (end of line)" - char = char + c - self.index = self.index + len(char) - self.next = char - def match(self, char, skip=1): - if char == self.next: - if skip: - self.__next() - return 1 - return 0 - def get(self): - this = self.next - self.__next() - return this - def tell(self): - return self.index, self.next - def seek(self, index): - self.index, self.next = index - -def isident(char): - return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_" - -def isdigit(char): - return "0" <= char <= "9" - -def isname(name): - # check that group name is a valid string - if not isident(name[0]): - return False - for char in name: - if not isident(char) and not isdigit(char): - return False - return True - -def _group(escape, groups): - # check if the escape string represents a valid group - try: - gid = atoi(escape[1:]) - if gid and gid < groups: - return gid - except ValueError: - pass - return None # not a valid group - -def _class_escape(source, escape): - # handle escape code inside character class - code = ESCAPES.get(escape) - if code: - return code - code = CATEGORIES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape (exactly two digits) - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - escape = escape[2:] - if len(escape) != 2: - raise error, "bogus escape: %s" % repr("\\" + escape) - return LITERAL, atoi(escape, 16) & 0xff - elif escape[1:2] in OCTDIGITS: - # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 5: - escape = escape + source.get() - escape = escape[1:] - return LITERAL, atoi(escape, 8) & 0xff - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _escape(source, escape, state): - # handle escape code in expression - code = CATEGORIES.get(escape) - if code: - return code - code = ESCAPES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - if len(escape) != 4: - raise ValueError - return LITERAL, atoi(escape[2:], 16) & 0xff - elif escape[1:2] == "0": - # octal escape - while source.next in OCTDIGITS and len(escape) < 4: - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - elif escape[1:2] in DIGITS: - # octal escape *or* decimal group reference (sigh) - if source.next in DIGITS: - escape = escape + source.get() - if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and - source.next in OCTDIGITS): - # got three octal digits; this is an octal escape - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - # got at least one decimal digit; this is a group reference - group = _group(escape, state.groups) - if group: - if not state.checkgroup(group): - raise error, "cannot refer to open group" - return GROUPREF, group - raise ValueError - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _parse_sub(source, state, nested=1): - # parse an alternation: a|b|c - - items = [] - while 1: - items.append(_parse(source, state)) - if source.match("|"): - continue - if not nested: - break - if not source.next or source.match(")", 0): - break - else: - raise error, "pattern not properly closed" - - if len(items) == 1: - return items[0] - - subpattern = SubPattern(state) - - # check if all items share a common prefix - while 1: - prefix = None - for item in items: - if not item: - break - if prefix is None: - prefix = item[0] - elif item[0] != prefix: - break - else: - # all subitems start with a common "prefix". - # move it out of the branch - for item in items: - del item[0] - subpattern.append(prefix) - continue # check next one - break - - # check if the branch can be replaced by a character set - for item in items: - if len(item) != 1 or item[0][0] != LITERAL: - break - else: - # we can store this as a character set instead of a - # branch (the compiler may optimize this even more) - set = [] - for item in items: - set.append(item[0]) - subpattern.append((IN, set)) - return subpattern - - subpattern.append((BRANCH, (None, items))) - return subpattern - -def _parse(source, state): - # parse a simple pattern - - subpattern = SubPattern(state) - - while 1: - - if source.next in ("|", ")"): - break # end of subpattern - this = source.get() - if this is None: - break # end of pattern - - if state.flags & SRE_FLAG_VERBOSE: - # skip whitespace and comments - if this in WHITESPACE: - continue - if this == "#": - while 1: - this = source.get() - if this in (None, "\n"): - break - continue - - if this and this[0] not in SPECIAL_CHARS: - subpattern.append((LITERAL, ord(this))) - - elif this == "[": - # character set - set = [] -## if source.match(":"): -## pass # handle character classes - if source.match("^"): - set.append((NEGATE, None)) - # check remaining characters - start = set[:] - while 1: - this = source.get() - if this == "]" and set != start: - break - elif this and this[0] == "\\": - code1 = _class_escape(source, this) - elif this: - code1 = LITERAL, ord(this) - else: - raise error, "unexpected end of regular expression" - if source.match("-"): - # potential range - this = source.get() - if this == "]": - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - set.append((LITERAL, ord("-"))) - break - elif this: - if this[0] == "\\": - code2 = _class_escape(source, this) - else: - code2 = LITERAL, ord(this) - if code1[0] != LITERAL or code2[0] != LITERAL: - raise error, "bad character range" - lo = code1[1] - hi = code2[1] - if hi < lo: - raise error, "bad character range" - set.append((RANGE, (lo, hi))) - else: - raise error, "unexpected end of regular expression" - else: - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - - # XXX: should move set optimization to compiler! - if len(set)==1 and set[0][0] is LITERAL: - subpattern.append(set[0]) # optimization - elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: - subpattern.append((NOT_LITERAL, set[1][1])) # optimization - else: - # XXX: should add charmap optimization here - subpattern.append((IN, set)) - - elif this and this[0] in REPEAT_CHARS: - # repeat previous item - if this == "?": - min, max = 0, 1 - elif this == "*": - min, max = 0, MAXREPEAT - - elif this == "+": - min, max = 1, MAXREPEAT - elif this == "{": - here = source.tell() - min, max = 0, MAXREPEAT - lo = hi = "" - while source.next in DIGITS: - lo = lo + source.get() - if source.match(","): - while source.next in DIGITS: - hi = hi + source.get() - else: - hi = lo - if not source.match("}"): - subpattern.append((LITERAL, ord(this))) - source.seek(here) - continue - if lo: - min = atoi(lo) - if hi: - max = atoi(hi) - if max < min: - raise error, "bad repeat interval" - else: - raise error, "not supported" - # figure out which item to repeat - if subpattern: - item = subpattern[-1:] - else: - item = None - if not item or (len(item) == 1 and item[0][0] == AT): - raise error, "nothing to repeat" - if item[0][0] in (MIN_REPEAT, MAX_REPEAT): - raise error, "multiple repeat" - if source.match("?"): - subpattern[-1] = (MIN_REPEAT, (min, max, item)) - else: - subpattern[-1] = (MAX_REPEAT, (min, max, item)) - - elif this == ".": - subpattern.append((ANY, None)) - - elif this == "(": - group = 1 - name = None - if source.match("?"): - group = 0 - # options - if source.match("P"): - # python extensions - if source.match("<"): - # named group: skip forward to end of name - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ">": - break - name = name + char - group = 1 - if not isname(name): - raise error, "bad character in group name" - elif source.match("="): - # named backreference - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ")": - break - name = name + char - if not isname(name): - raise error, "bad character in group name" - gid = state.groupdict.get(name) - if gid is None: - raise error, "unknown group name" - subpattern.append((GROUPREF, gid)) - continue - else: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - raise error, "unknown specifier: ?P%s" % char - elif source.match(":"): - # non-capturing group - group = 2 - elif source.match("#"): - # comment - while 1: - if source.next is None or source.next == ")": - break - source.get() - if not source.match(")"): - raise error, "unbalanced parenthesis" - continue - elif source.next in ("=", "!", "<"): - # lookahead assertions - char = source.get() - dir = 1 - if char == "<": - if source.next not in ("=", "!"): - raise error, "syntax error" - dir = -1 # lookbehind - char = source.get() - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if char == "=": - subpattern.append((ASSERT, (dir, p))) - else: - subpattern.append((ASSERT_NOT, (dir, p))) - continue - else: - # flags - if not source.next in FLAGS: - raise error, "unexpected end of pattern" - while source.next in FLAGS: - state.flags = state.flags | FLAGS[source.get()] - if group: - # parse group contents - if group == 2: - # anonymous group - group = None - else: - group = state.opengroup(name) - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if group is not None: - state.closegroup(group) - subpattern.append((SUBPATTERN, (group, p))) - else: - while 1: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - if char == ")": - break - raise error, "unknown extension" - - elif this == "^": - subpattern.append((AT, AT_BEGINNING)) - - elif this == "$": - subpattern.append((AT, AT_END)) - - elif this and this[0] == "\\": - code = _escape(source, this, state) - subpattern.append(code) - - else: - raise error, "parser error" - - return subpattern - -def parse(str, flags=0, pattern=None): - # parse 're' pattern into list of (opcode, argument) tuples - - source = Tokenizer(str) - - if pattern is None: - pattern = Pattern() - pattern.flags = flags - pattern.str = str - - p = _parse_sub(source, pattern, 0) - - tail = source.get() - if tail == ")": - raise error, "unbalanced parenthesis" - elif tail: - raise error, "bogus characters at end of regular expression" - - if flags & SRE_FLAG_DEBUG: - p.dump() - - if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: - # the VERBOSE flag was switched on inside the pattern. to be - # on the safe side, we'll parse the whole thing again... - return parse(str, p.pattern.flags) - - return p - -def parse_template(source, pattern): - # parse 're' replacement string into list of literals and - # group references - s = Tokenizer(source) - p = [] - a = p.append - def literal(literal, p=p): - if p and p[-1][0] is LITERAL: - p[-1] = LITERAL, p[-1][1] + literal - else: - p.append((LITERAL, literal)) - sep = source[:0] - if type(sep) is type(""): - makechar = chr - else: - makechar = unichr - while 1: - this = s.get() - if this is None: - break # end of replacement string - if this and this[0] == "\\": - # group - if this == "\\g": - name = "" - if s.match("<"): - while 1: - char = s.get() - if char is None: - raise error, "unterminated group name" - if char == ">": - break - name = name + char - if not name: - raise error, "bad group name" - try: - index = atoi(name) - except ValueError: - if not isname(name): - raise error, "bad character in group name" - try: - index = pattern.groupindex[name] - except KeyError: - raise IndexError, "unknown group name" - a((MARK, index)) - elif len(this) > 1 and this[1] in DIGITS: - code = None - while 1: - group = _group(this, pattern.groups+1) - if group: - if (s.next not in DIGITS or - not _group(this + s.next, pattern.groups+1)): - code = MARK, group - break - elif s.next in OCTDIGITS: - this = this + s.get() - else: - break - if not code: - this = this[1:] - code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff) - if code[0] is LITERAL: - literal(code[1]) - else: - a(code) - else: - try: - this = makechar(ESCAPES[this][1]) - except KeyError: - pass - literal(this) - else: - literal(this) - # convert template to groups and literals lists - i = 0 - groups = [] - literals = [] - for c, s in p: - if c is MARK: - groups.append((i, s)) - literals.append(None) - else: - literals.append(s) - i = i + 1 - return groups, literals - -def expand_template(template, match): - g = match.group - sep = match.string[:0] - groups, literals = template - literals = literals[:] - try: - for index, group in groups: - literals[index] = s = g(group) - if s is None: - raise IndexError - except IndexError: - raise error, "empty group" - return string.join(literals, sep) From sanxiyn at codespeak.net Sat Jan 29 06:50:56 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 06:50:56 +0100 (MET) Subject: [pypy-svn] r8686 - pypy/dist/pypy/lib Message-ID: <20050129055056.8F88027B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 06:50:56 2005 New Revision: 8686 Added: pypy/dist/pypy/lib/sre_parse.py - copied unchanged from r8631, pypy/dist/pypy/appspace/sre_parse.py Log: Restore patched copy from r8631 From sanxiyn at codespeak.net Sat Jan 29 07:11:26 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 07:11:26 +0100 (MET) Subject: [pypy-svn] r8687 - pypy/dist/pypy/lib Message-ID: <20050129061126.ED86327B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 07:11:26 2005 New Revision: 8687 Modified: pypy/dist/pypy/lib/sre_adapt.py (props changed) Log: fixeol Someone on CRLF platform please fix tool/sourcetools.py From sanxiyn at codespeak.net Sat Jan 29 07:41:04 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 07:41:04 +0100 (MET) Subject: [pypy-svn] r8689 - pypy/dist/pypy/lib Message-ID: <20050129064104.46C6127B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 07:41:04 2005 New Revision: 8689 Added: pypy/dist/pypy/lib/random.py (contents, props changed) Log: Pure Python random module, from Python 2.2.3. (one under appspace/ is from 2.2, but there were some bugfixes between 2.2 and 2.2.3) Added: pypy/dist/pypy/lib/random.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/random.py Sat Jan 29 07:41:04 2005 @@ -0,0 +1,779 @@ +"""Random variable generators. + + integers + -------- + uniform within range + + sequences + --------- + pick random element + generate random permutation + + distributions on the real line: + ------------------------------ + uniform + normal (Gaussian) + lognormal + negative exponential + gamma + beta + + distributions on the circle (angles 0 to 2pi) + --------------------------------------------- + circular uniform + von Mises + +Translated from anonymously contributed C/C++ source. + +Multi-threading note: the random number generator used here is not thread- +safe; it is possible that two calls return the same random value. However, +you can instantiate a different instance of Random() in each thread to get +generators that don't share state, then use .setstate() and .jumpahead() to +move the generators to disjoint segments of the full period. For example, + +def create_generators(num, delta, firstseed=None): + ""\"Return list of num distinct generators. + Each generator has its own unique segment of delta elements from + Random.random()'s full period. + Seed the first generator with optional arg firstseed (default is + None, to seed from current time). + ""\" + + from random import Random + g = Random(firstseed) + result = [g] + for i in range(num - 1): + laststate = g.getstate() + g = Random() + g.setstate(laststate) + g.jumpahead(delta) + result.append(g) + return result + +gens = create_generators(10, 1000000) + +That creates 10 distinct generators, which can be passed out to 10 distinct +threads. The generators don't share state so can be called safely in +parallel. So long as no thread calls its g.random() more than a million +times (the second argument to create_generators), the sequences seen by +each thread will not overlap. + +The period of the underlying Wichmann-Hill generator is 6,953,607,871,644, +and that limits how far this technique can be pushed. + +Just for fun, note that since we know the period, .jumpahead() can also be +used to "move backward in time": + +>>> g = Random(42) # arbitrary +>>> g.random() +0.25420336316883324 +>>> g.jumpahead(6953607871644L - 1) # move *back* one +>>> g.random() +0.25420336316883324 +""" +# XXX The docstring sucks. + +from math import log as _log, exp as _exp, pi as _pi, e as _e +from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin +from math import floor as _floor + +__all__ = ["Random","seed","random","uniform","randint","choice", + "randrange","shuffle","normalvariate","lognormvariate", + "cunifvariate","expovariate","vonmisesvariate","gammavariate", + "stdgamma","gauss","betavariate","paretovariate","weibullvariate", + "getstate","setstate","jumpahead","whseed"] + +def _verify(name, computed, expected): + if abs(computed - expected) > 1e-7: + raise ValueError( + "computed value for %s deviates too much " + "(computed %g, expected %g)" % (name, computed, expected)) + +NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0) +_verify('NV_MAGICCONST', NV_MAGICCONST, 1.71552776992141) + +TWOPI = 2.0*_pi +_verify('TWOPI', TWOPI, 6.28318530718) + +LOG4 = _log(4.0) +_verify('LOG4', LOG4, 1.38629436111989) + +SG_MAGICCONST = 1.0 + _log(4.5) +_verify('SG_MAGICCONST', SG_MAGICCONST, 2.50407739677627) + +del _verify + +# Translated by Guido van Rossum from C source provided by +# Adrian Baddeley. + +class Random: + """Random number generator base class used by bound module functions. + + Used to instantiate instances of Random to get generators that don't + share state. Especially useful for multi-threaded programs, creating + a different instance of Random for each thread, and using the jumpahead() + method to ensure that the generated sequences seen by each thread don't + overlap. + + Class Random can also be subclassed if you want to use a different basic + generator of your own devising: in that case, override the following + methods: random(), seed(), getstate(), setstate() and jumpahead(). + + """ + + VERSION = 1 # used by getstate/setstate + + def __init__(self, x=None): + """Initialize an instance. + + Optional argument x controls seeding, as for Random.seed(). + """ + + self.seed(x) + +## -------------------- core generator ------------------- + + # Specific to Wichmann-Hill generator. Subclasses wishing to use a + # different core generator should override the seed(), random(), + # getstate(), setstate() and jumpahead() methods. + + def seed(self, a=None): + """Initialize internal state from hashable object. + + None or no argument seeds from current time. + + If a is not None or an int or long, hash(a) is used instead. + + If a is an int or long, a is used directly. Distinct values between + 0 and 27814431486575L inclusive are guaranteed to yield distinct + internal states (this guarantee is specific to the default + Wichmann-Hill generator). + """ + + if a is None: + # Initialize from current time + import time + a = long(time.time() * 256) + + if type(a) not in (type(3), type(3L)): + a = hash(a) + + a, x = divmod(a, 30268) + a, y = divmod(a, 30306) + a, z = divmod(a, 30322) + self._seed = int(x)+1, int(y)+1, int(z)+1 + + self.gauss_next = None + + def random(self): + """Get the next random number in the range [0.0, 1.0).""" + + # Wichman-Hill random number generator. + # + # Wichmann, B. A. & Hill, I. D. (1982) + # Algorithm AS 183: + # An efficient and portable pseudo-random number generator + # Applied Statistics 31 (1982) 188-190 + # + # see also: + # Correction to Algorithm AS 183 + # Applied Statistics 33 (1984) 123 + # + # McLeod, A. I. (1985) + # A remark on Algorithm AS 183 + # Applied Statistics 34 (1985),198-200 + + # This part is thread-unsafe: + # BEGIN CRITICAL SECTION + x, y, z = self._seed + x = (171 * x) % 30269 + y = (172 * y) % 30307 + z = (170 * z) % 30323 + self._seed = x, y, z + # END CRITICAL SECTION + + # Note: on a platform using IEEE-754 double arithmetic, this can + # never return 0.0 (asserted by Tim; proof too long for a comment). + return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0 + + def getstate(self): + """Return internal state; can be passed to setstate() later.""" + return self.VERSION, self._seed, self.gauss_next + + def setstate(self, state): + """Restore internal state from object returned by getstate().""" + version = state[0] + if version == 1: + version, self._seed, self.gauss_next = state + else: + raise ValueError("state with version %s passed to " + "Random.setstate() of version %s" % + (version, self.VERSION)) + + def jumpahead(self, n): + """Act as if n calls to random() were made, but quickly. + + n is an int, greater than or equal to 0. + + Example use: If you have 2 threads and know that each will + consume no more than a million random numbers, create two Random + objects r1 and r2, then do + r2.setstate(r1.getstate()) + r2.jumpahead(1000000) + Then r1 and r2 will use guaranteed-disjoint segments of the full + period. + """ + + if not n >= 0: + raise ValueError("n must be >= 0") + x, y, z = self._seed + x = int(x * pow(171, n, 30269)) % 30269 + y = int(y * pow(172, n, 30307)) % 30307 + z = int(z * pow(170, n, 30323)) % 30323 + self._seed = x, y, z + + def __whseed(self, x=0, y=0, z=0): + """Set the Wichmann-Hill seed from (x, y, z). + + These must be integers in the range [0, 256). + """ + + if not type(x) == type(y) == type(z) == type(0): + raise TypeError('seeds must be integers') + if not (0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256): + raise ValueError('seeds must be in range(0, 256)') + if 0 == x == y == z: + # Initialize from current time + import time + t = long(time.time() * 256) + t = int((t&0xffffff) ^ (t>>24)) + t, x = divmod(t, 256) + t, y = divmod(t, 256) + t, z = divmod(t, 256) + # Zero is a poor seed, so substitute 1 + self._seed = (x or 1, y or 1, z or 1) + + self.gauss_next = None + + def whseed(self, a=None): + """Seed from hashable object's hash code. + + None or no argument seeds from current time. It is not guaranteed + that objects with distinct hash codes lead to distinct internal + states. + + This is obsolete, provided for compatibility with the seed routine + used prior to Python 2.1. Use the .seed() method instead. + """ + + if a is None: + self.__whseed() + return + a = hash(a) + a, x = divmod(a, 256) + a, y = divmod(a, 256) + a, z = divmod(a, 256) + x = (x + a) % 256 or 1 + y = (y + a) % 256 or 1 + z = (z + a) % 256 or 1 + self.__whseed(x, y, z) + +## ---- Methods below this point do not need to be overridden when +## ---- subclassing for the purpose of using a different core generator. + +## -------------------- pickle support ------------------- + + def __getstate__(self): # for pickle + return self.getstate() + + def __setstate__(self, state): # for pickle + self.setstate(state) + +## -------------------- integer methods ------------------- + + def randrange(self, start, stop=None, step=1, int=int, default=None): + """Choose a random item from range(start, stop[, step]). + + This fixes the problem with randint() which includes the + endpoint; in Python this is usually not what you want. + Do not supply the 'int' and 'default' arguments. + """ + + # This code is a bit messy to make it fast for the + # common case while still doing adequate error checking. + istart = int(start) + if istart != start: + raise ValueError, "non-integer arg 1 for randrange()" + if stop is default: + if istart > 0: + return int(self.random() * istart) + raise ValueError, "empty range for randrange()" + + # stop argument supplied. + istop = int(stop) + if istop != stop: + raise ValueError, "non-integer stop for randrange()" + if step == 1 and istart < istop: + try: + return istart + int(self.random()*(istop - istart)) + except OverflowError: + # This can happen if istop-istart > sys.maxint + 1, and + # multiplying by random() doesn't reduce it to something + # <= sys.maxint. We know that the overall result fits + # in an int, and can still do it correctly via math.floor(). + # But that adds another function call, so for speed we + # avoided that whenever possible. + return int(istart + _floor(self.random()*(istop - istart))) + if step == 1: + raise ValueError, "empty range for randrange()" + + # Non-unit step argument supplied. + istep = int(step) + if istep != step: + raise ValueError, "non-integer step for randrange()" + if istep > 0: + n = (istop - istart + istep - 1) / istep + elif istep < 0: + n = (istop - istart + istep + 1) / istep + else: + raise ValueError, "zero step for randrange()" + + if n <= 0: + raise ValueError, "empty range for randrange()" + return istart + istep*int(self.random() * n) + + def randint(self, a, b): + """Return random integer in range [a, b], including both end points. + """ + + return self.randrange(a, b+1) + +## -------------------- sequence methods ------------------- + + def choice(self, seq): + """Choose a random element from a non-empty sequence.""" + return seq[int(self.random() * len(seq))] + + def shuffle(self, x, random=None, int=int): + """x, random=random.random -> shuffle list x in place; return None. + + Optional arg random is a 0-argument function returning a random + float in [0.0, 1.0); by default, the standard random.random. + + Note that for even rather small len(x), the total number of + permutations of x is larger than the period of most random number + generators; this implies that "most" permutations of a long + sequence can never be generated. + """ + + if random is None: + random = self.random + for i in xrange(len(x)-1, 0, -1): + # pick an element in x[:i+1] with which to exchange x[i] + j = int(random() * (i+1)) + x[i], x[j] = x[j], x[i] + +## -------------------- real-valued distributions ------------------- + +## -------------------- uniform distribution ------------------- + + def uniform(self, a, b): + """Get a random number in the range [a, b).""" + return a + (b-a) * self.random() + +## -------------------- normal distribution -------------------- + + def normalvariate(self, mu, sigma): + """Normal distribution. + + mu is the mean, and sigma is the standard deviation. + + """ + # mu = mean, sigma = standard deviation + + # Uses Kinderman and Monahan method. Reference: Kinderman, + # A.J. and Monahan, J.F., "Computer generation of random + # variables using the ratio of uniform deviates", ACM Trans + # Math Software, 3, (1977), pp257-260. + + random = self.random + while 1: + u1 = random() + u2 = 1.0 - random() + z = NV_MAGICCONST*(u1-0.5)/u2 + zz = z*z/4.0 + if zz <= -_log(u2): + break + return mu + z*sigma + +## -------------------- lognormal distribution -------------------- + + def lognormvariate(self, mu, sigma): + """Log normal distribution. + + If you take the natural logarithm of this distribution, you'll get a + normal distribution with mean mu and standard deviation sigma. + mu can have any value, and sigma must be greater than zero. + + """ + return _exp(self.normalvariate(mu, sigma)) + +## -------------------- circular uniform -------------------- + + def cunifvariate(self, mean, arc): + """Circular uniform distribution. + + mean is the mean angle, and arc is the range of the distribution, + centered around the mean angle. Both values must be expressed in + radians. Returned values range between mean - arc/2 and + mean + arc/2 and are normalized to between 0 and pi. + + Deprecated in version 2.3. Use: + (mean + arc * (Random.random() - 0.5)) % Math.pi + + """ + # mean: mean angle (in radians between 0 and pi) + # arc: range of distribution (in radians between 0 and pi) + + return (mean + arc * (self.random() - 0.5)) % _pi + +## -------------------- exponential distribution -------------------- + + def expovariate(self, lambd): + """Exponential distribution. + + lambd is 1.0 divided by the desired mean. (The parameter would be + called "lambda", but that is a reserved word in Python.) Returned + values range from 0 to positive infinity. + + """ + # lambd: rate lambd = 1/mean + # ('lambda' is a Python reserved word) + + random = self.random + u = random() + while u <= 1e-7: + u = random() + return -_log(u)/lambd + +## -------------------- von Mises distribution -------------------- + + def vonmisesvariate(self, mu, kappa): + """Circular data distribution. + + mu is the mean angle, expressed in radians between 0 and 2*pi, and + kappa is the concentration parameter, which must be greater than or + equal to zero. If kappa is equal to zero, this distribution reduces + to a uniform random angle over the range 0 to 2*pi. + + """ + # mu: mean angle (in radians between 0 and 2*pi) + # kappa: concentration parameter kappa (>= 0) + # if kappa = 0 generate uniform random angle + + # Based upon an algorithm published in: Fisher, N.I., + # "Statistical Analysis of Circular Data", Cambridge + # University Press, 1993. + + # Thanks to Magnus Kessler for a correction to the + # implementation of step 4. + + random = self.random + if kappa <= 1e-6: + return TWOPI * random() + + a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa) + b = (a - _sqrt(2.0 * a))/(2.0 * kappa) + r = (1.0 + b * b)/(2.0 * b) + + while 1: + u1 = random() + + z = _cos(_pi * u1) + f = (1.0 + r * z)/(r + z) + c = kappa * (r - f) + + u2 = random() + + if not (u2 >= c * (2.0 - c) and u2 > c * _exp(1.0 - c)): + break + + u3 = random() + if u3 > 0.5: + theta = (mu % TWOPI) + _acos(f) + else: + theta = (mu % TWOPI) - _acos(f) + + return theta + +## -------------------- gamma distribution -------------------- + + def gammavariate(self, alpha, beta): + """Gamma distribution. Not the gamma function! + + Conditions on the parameters are alpha > 0 and beta > 0. + + """ + + # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 + + # Warning: a few older sources define the gamma distribution in terms + # of alpha > -1.0 + if alpha <= 0.0 or beta <= 0.0: + raise ValueError, 'gammavariate: alpha and beta must be > 0.0' + + random = self.random + if alpha > 1.0: + + # Uses R.C.H. Cheng, "The generation of Gamma + # variables with non-integral shape parameters", + # Applied Statistics, (1977), 26, No. 1, p71-74 + + ainv = _sqrt(2.0 * alpha - 1.0) + bbb = alpha - LOG4 + ccc = alpha + ainv + + while 1: + u1 = random() + if not 1e-7 < u1 < .9999999: + continue + u2 = 1.0 - random() + v = _log(u1/(1.0-u1))/ainv + x = alpha*_exp(v) + z = u1*u1*u2 + r = bbb+ccc*v-x + if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z): + return x * beta + + elif alpha == 1.0: + # expovariate(1) + u = random() + while u <= 1e-7: + u = random() + return -_log(u) * beta + + else: # alpha is between 0 and 1 (exclusive) + + # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle + + while 1: + u = random() + b = (_e + alpha)/_e + p = b*u + if p <= 1.0: + x = pow(p, 1.0/alpha) + else: + # p > 1 + x = -_log((b-p)/alpha) + u1 = random() + if not (((p <= 1.0) and (u1 > _exp(-x))) or + ((p > 1) and (u1 > pow(x, alpha - 1.0)))): + break + return x * beta + + + def stdgamma(self, alpha, ainv, bbb, ccc): + # This method was (and shall remain) undocumented. + # This method is deprecated + # for the following reasons: + # 1. Returns same as .gammavariate(alpha, 1.0) + # 2. Requires caller to provide 3 extra arguments + # that are functions of alpha anyway + # 3. Can't be used for alpha < 0.5 + + # ainv = sqrt(2 * alpha - 1) + # bbb = alpha - log(4) + # ccc = alpha + ainv + import warnings + warnings.warn("The stdgamma function is deprecated; " + "use gammavariate() instead", + DeprecationWarning) + return self.gammavariate(alpha, 1.0) + + + +## -------------------- Gauss (faster alternative) -------------------- + + def gauss(self, mu, sigma): + """Gaussian distribution. + + mu is the mean, and sigma is the standard deviation. This is + slightly faster than the normalvariate() function. + + Not thread-safe without a lock around calls. + + """ + + # When x and y are two variables from [0, 1), uniformly + # distributed, then + # + # cos(2*pi*x)*sqrt(-2*log(1-y)) + # sin(2*pi*x)*sqrt(-2*log(1-y)) + # + # are two *independent* variables with normal distribution + # (mu = 0, sigma = 1). + # (Lambert Meertens) + # (corrected version; bug discovered by Mike Miller, fixed by LM) + + # Multithreading note: When two threads call this function + # simultaneously, it is possible that they will receive the + # same return value. The window is very small though. To + # avoid this, you have to use a lock around all calls. (I + # didn't want to slow this down in the serial case by using a + # lock here.) + + random = self.random + z = self.gauss_next + self.gauss_next = None + if z is None: + x2pi = random() * TWOPI + g2rad = _sqrt(-2.0 * _log(1.0 - random())) + z = _cos(x2pi) * g2rad + self.gauss_next = _sin(x2pi) * g2rad + + return mu + z*sigma + +## -------------------- beta -------------------- +## See +## http://sourceforge.net/bugs/?func=detailbug&bug_id=130030&group_id=5470 +## for Ivan Frohne's insightful analysis of why the original implementation: +## +## def betavariate(self, alpha, beta): +## # Discrete Event Simulation in C, pp 87-88. +## +## y = self.expovariate(alpha) +## z = self.expovariate(1.0/beta) +## return z/(y+z) +## +## was dead wrong, and how it probably got that way. + + def betavariate(self, alpha, beta): + """Beta distribution. + + Conditions on the parameters are alpha > -1 and beta} > -1. + Returned values range between 0 and 1. + + """ + + # This version due to Janne Sinkkonen, and matches all the std + # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). + y = self.gammavariate(alpha, 1.) + if y == 0: + return 0.0 + else: + return y / (y + self.gammavariate(beta, 1.)) + +## -------------------- Pareto -------------------- + + def paretovariate(self, alpha): + """Pareto distribution. alpha is the shape parameter.""" + # Jain, pg. 495 + + u = 1.0 - self.random() + return 1.0 / pow(u, 1.0/alpha) + +## -------------------- Weibull -------------------- + + def weibullvariate(self, alpha, beta): + """Weibull distribution. + + alpha is the scale parameter and beta is the shape parameter. + + """ + # Jain, pg. 499; bug fix courtesy Bill Arms + + u = 1.0 - self.random() + return alpha * pow(-_log(u), 1.0/beta) + +## -------------------- test program -------------------- + +def _test_generator(n, funccall): + import time + print n, 'times', funccall + code = compile(funccall, funccall, 'eval') + sum = 0.0 + sqsum = 0.0 + smallest = 1e10 + largest = -1e10 + t0 = time.time() + for i in range(n): + x = eval(code) + sum = sum + x + sqsum = sqsum + x*x + smallest = min(x, smallest) + largest = max(x, largest) + t1 = time.time() + print round(t1-t0, 3), 'sec,', + avg = sum/n + stddev = _sqrt(sqsum/n - avg*avg) + print 'avg %g, stddev %g, min %g, max %g' % \ + (avg, stddev, smallest, largest) + +def _test(N=20000): + print 'TWOPI =', TWOPI + print 'LOG4 =', LOG4 + print 'NV_MAGICCONST =', NV_MAGICCONST + print 'SG_MAGICCONST =', SG_MAGICCONST + _test_generator(N, 'random()') + _test_generator(N, 'normalvariate(0.0, 1.0)') + _test_generator(N, 'lognormvariate(0.0, 1.0)') + _test_generator(N, 'cunifvariate(0.0, 1.0)') + _test_generator(N, 'expovariate(1.0)') + _test_generator(N, 'vonmisesvariate(0.0, 1.0)') + _test_generator(N, 'gammavariate(0.01, 1.0)') + _test_generator(N, 'gammavariate(0.1, 1.0)') + _test_generator(N, 'gammavariate(0.1, 2.0)') + _test_generator(N, 'gammavariate(0.5, 1.0)') + _test_generator(N, 'gammavariate(0.9, 1.0)') + _test_generator(N, 'gammavariate(1.0, 1.0)') + _test_generator(N, 'gammavariate(2.0, 1.0)') + _test_generator(N, 'gammavariate(20.0, 1.0)') + _test_generator(N, 'gammavariate(200.0, 1.0)') + _test_generator(N, 'gauss(0.0, 1.0)') + _test_generator(N, 'betavariate(3.0, 3.0)') + _test_generator(N, 'paretovariate(1.0)') + _test_generator(N, 'weibullvariate(1.0, 1.0)') + + # Test jumpahead. + s = getstate() + jumpahead(N) + r1 = random() + # now do it the slow way + setstate(s) + for i in range(N): + random() + r2 = random() + if r1 != r2: + raise ValueError("jumpahead test failed " + `(N, r1, r2)`) + +# Create one instance, seeded from current time, and export its methods +# as module-level functions. The functions are not threadsafe, and state +# is shared across all uses (both in the user's code and in the Python +# libraries), but that's fine for most programs and is easier for the +# casual user than making them instantiate their own Random() instance. +_inst = Random() +seed = _inst.seed +random = _inst.random +uniform = _inst.uniform +randint = _inst.randint +choice = _inst.choice +randrange = _inst.randrange +shuffle = _inst.shuffle +normalvariate = _inst.normalvariate +lognormvariate = _inst.lognormvariate +cunifvariate = _inst.cunifvariate +expovariate = _inst.expovariate +vonmisesvariate = _inst.vonmisesvariate +gammavariate = _inst.gammavariate +stdgamma = _inst.stdgamma +gauss = _inst.gauss +betavariate = _inst.betavariate +paretovariate = _inst.paretovariate +weibullvariate = _inst.weibullvariate +getstate = _inst.getstate +setstate = _inst.setstate +jumpahead = _inst.jumpahead +whseed = _inst.whseed + +if __name__ == '__main__': + _test() From sanxiyn at codespeak.net Sat Jan 29 07:42:10 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 07:42:10 +0100 (MET) Subject: [pypy-svn] r8690 - pypy/dist/pypy/appspace Message-ID: <20050129064210.5423B27B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 07:42:10 2005 New Revision: 8690 Removed: pypy/dist/pypy/appspace/ Log: Eradicate appspace From lac at codespeak.net Sat Jan 29 09:41:03 2005 From: lac at codespeak.net (lac at codespeak.net) Date: Sat, 29 Jan 2005 09:41:03 +0100 (MET) Subject: [pypy-svn] r8691 - pypy/dist/pypy/documentation Message-ID: <20050129084103.BDFA827B96@code1.codespeak.net> Author: lac Date: Sat Jan 29 09:41:03 2005 New Revision: 8691 Modified: pypy/dist/pypy/documentation/howtosvn.txt Log: Add a paragraph about how to avoid line ending hell on your client. Modified: pypy/dist/pypy/documentation/howtosvn.txt ============================================================================== --- pypy/dist/pypy/documentation/howtosvn.txt (original) +++ pypy/dist/pypy/documentation/howtosvn.txt Sat Jan 29 09:41:03 2005 @@ -135,6 +135,25 @@ http-proxy-host = codespeak.net http-proxy-port = 8080 +How to Avoid Line-ending Hell +----------------------------- + +We will assume that whenever you create a .txt or a .py file, you would +like other people to be able to read it with the line endings their +OS prefers, even if that is different from the one your OS likes. This +could occasionally be wrong -- say when you are specifically testing +that code you are writing handles line endings properly -- but this is +what you want by default. Binary files, on the other hand, should be +stored exactly as is. This has to be set on every client. Here is how: + +In your home directory edit .subversion/config and comment in :: + + enable-auto-props = yes + + *.txt = svn:eol-style=native + +and add a line for .py files. + -------------------------------------------------------------------------------- From arigo at codespeak.net Sat Jan 29 12:14:17 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 12:14:17 +0100 (MET) Subject: [pypy-svn] r8694 - pypy/dist/pypy/lib Message-ID: <20050129111417.0F1E927B95@code1.codespeak.net> Author: arigo Date: Sat Jan 29 12:14:16 2005 New Revision: 8694 Added: pypy/dist/pypy/lib/_sio.py - copied, changed from r8690, pypy/dist/pypy/lib/sio.py Removed: pypy/dist/pypy/lib/sio.py Modified: pypy/dist/pypy/lib/_file.py Log: A rewrite of sio and the class file. Still needs to be tested. Modified: pypy/dist/pypy/lib/_file.py ============================================================================== --- pypy/dist/pypy/lib/_file.py (original) +++ pypy/dist/pypy/lib/_file.py Sat Jan 29 12:14:16 2005 @@ -1,130 +1,239 @@ -import sio -from array import array +import os, _sio -class file_(object): - """An implementation of file objects in Python. it relies on Guido's - sio.py implementation. +## # This is not quite correct, since more letters are allowed after +## # these. However, the following are the only starting strings allowed +## # in the mode parameter. +## modes = { +## 'r' : os.O_RDONLY, +## 'rb' : os.O_RDONLY, +## 'rU' : os.O_RDONLY, +## 'U' : os.O_RDONLY, +## 'w' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, +## 'wb' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, +## 'a' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, +## 'ab' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, +## 'r+' : os.O_RDWR, +## 'rb+': os.O_RDWR, +## 'r+b': os.O_RDWR, +## 'w+' : os.O_RDWR | os.O_CREAT | os.O_TRUNC, +## 'wb+': os.O_RDWR | os.O_CREAT | os.O_TRUNC, +## 'w+b': os.O_RDWR | os.O_CREAT | os.O_TRUNC, +## 'a+' : os.O_RDWR | os.O_CREAT | os.O_EXCL, +## 'ab+': os.O_RDWR | os.O_CREAT | os.O_EXCL, +## 'a+b': os.O_RDWR | os.O_CREAT | os.O_EXCL, +## } +## def __init__(self, filename, mode="r"): +## self.filename = filename +## self.mode = mode +## try: +## flag = DiskFile.modes[mode] +## except KeyError: +## raise ValueError, "mode should be 'r', 'r+', 'w', 'w+' or 'a+'" + +## O_BINARY = getattr(os, "O_BINARY", 0) +## flag |= O_BINARY +## try: +## self.fd = os.open(filename, flag) +## except OSError: +## # Opening in mode 'a' or 'a+' and file already exists +## flag = flag & (os.O_RDWR | O_BINARY) +## self.fd = os.open(filename, flag) +## if mode[0] == 'a': +## try: +## os.lseek(self.fd, 0, 2) # Move to end of file +## except: +## os.close(self.fd) +## raise + + +from os import O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC +O_BINARY = getattr(os, "O_BINARY", 0) + +# (basemode, plus) +OS_MODE = {('r', False): O_RDONLY, + ('r', True): O_RDWR, + ('w', False): O_WRONLY | O_CREAT | O_TRUNC, + ('w', True): O_RDWR | O_CREAT | O_TRUNC, + ('a', False): O_WRONLY | O_CREAT, + ('a', True): O_RDWR | O_CREAT, + } + + +class file(object): + """file(name[, mode[, buffering]]) -> file object + +Open a file. The mode can be 'r', 'w' or 'a' for reading (default), +writing or appending. The file will be created if it doesn't exist +when opened for writing or appending; it will be truncated when +opened for writing. Add a 'b' to the mode for binary files. +Add a '+' to the mode to allow simultaneous reading and writing. +If the buffering argument is given, 0 means unbuffered, 1 means line +buffered, and larger numbers specify the buffer size. +Add a 'U' to mode to open the file for input with universal newline +support. Any line ending in the input file will be seen as a '\n' +in Python. Also, a file so opened gains the attribute 'newlines'; +the value for this attribute is one of None (no newline read yet), +'\r', '\n', '\r\n' or a tuple containing all the newline types seen. + +Note: open() is an alias for file(). """ - def __init__(self, name, mode='r', bufsize=None): - self.reading = False - self.writing = False - - if not mode: - raise IOError('invalid mode : ') - if mode[0] not in ['r', 'w', 'a', 'U']: + self.mode = mode + self.name = name + self.closed = False + self.softspace = 0 # Required according to file object docs + self.encoding = None # This is not used internally by file objects + + if not mode or mode[0] not in ['r', 'w', 'a', 'U']: raise IOError('invalid mode : %s' % mode) - else: - if mode[0] in ['r', 'U']: - self.reading = True - else: - self.writing = True - try: - if mode[1] == 'b': - plus = mode[2] + + if mode[0] == 'U': + mode = 'r' + mode + + basemode = mode[0] # 'r', 'w' or 'a' + plus = False + universal = False + binary = False + + for c in mode[1:]: + if c == '+': + plus = True + elif c == 'U': + universal = True + elif c == 'b': + binary = True else: - plus = mode[1] - if plus == '+': - self.reading = self.writing = True - except IndexError: + break + + flag = OS_MODE[basemode, plus] + if binary or universal: + flag |= O_BINARY + + fd = os.open(name, flag) + if basemode == 'a': + try: + os.lseek(fd, 0, 2) + except OSError: + pass + + self.stream = _sio.DiskFile(fd) + + reading = basemode == 'r' or plus + writing = basemode != 'r' or plus + + if universal: # Wants universal newlines + if writing: + self.stream = _sio.TextOutputFilter(self.stream) + if reading: + self.stream = _sio.TextInputFilter(self.stream) + + if bufsize == 0: # no buffering pass + elif bufsize == 1: # line-buffering + if writing: + self.stream = _sio.LineBufferingOutputStream(self.stream) + if reading: + self.stream = _sio.BufferingInputStream(self.stream) + + else: # default or explicit buffer sizes + if bufsize is not None and bufsize < 0: + bufsize = None + if writing: + self.stream = _sio.BufferingOutputStream(self.stream, bufsize) + if reading: + self.stream = _sio.BufferingInputStream(self.stream, bufsize) + + + def read(self, n=-1): + if self.closed: + raise ValueError('I/O operation on closed file') + if n < 0: + return self.stream.readall() + else: + result = [] + while n > 0: + data = self.stream.read(n) + if not data: + break + n -= len(data) + result.append(data) + return ''.join(data) + + def readall(self): + if self.closed: + raise ValueError('I/O operation on closed file') + return self.stream.readall() + + def readline(self): + if self.closed: + raise ValueError('I/O operation on closed file') + return self.stream.readline() + + def readlines(self, sizehint=0): + if self.closed: + raise ValueError('I/O operation on closed file') + return list(iter(self.stream.readline, "")) + + def write(self, data): + if self.closed: + raise ValueError('I/O operation on closed file') + return self.stream.write(data) + + def writelines(self, lines): + if self.closed: + raise ValueError('I/O operation on closed file') + for line in lines: + self.stream.write(line) - self._mode = mode - self._name = name - self._closed = False - self.softspace = 0 # Required according to file object docs - self._encoding = None # Fix when we find out how encoding should be - self.fd = sio.DiskFile(name, mode) - if mode in ['U', 'rU']: - # Wants universal newlines - self.fd = sio.TextInputFilter(self.fd) - if bufsize < 0: - bufsize = None - if not self.writing and (bufsize is None or bufsize > 0): - "Read only buffered stream." - self.fd = sio.BufferingInputStream(self.fd, bufsize) - if not self.reading: - if bufsize is None or bufsize > 1: - "Write only buffered stream." - self.fd = sio.BufferingOutputStream(self.fd, bufsize) - elif bufsize == 1: - self.fd = sio.LineBufferingOutputStream(self.fd) - if self.reading and self.writing: - if bufsize > 2: - "Read and write buffered stream." - self.fd = sio.BufferingInputOutputStream(self.fd, bufsize) + def tell(self): + if self.closed: + raise ValueError('I/O operation on closed file') + return self.stream.tell() + + def seek(self, offset, whence=0): + if self.closed: + raise ValueError('I/O operation on closed file') + self.stream.seek(offset, whence) def __iter__(self): - """ - Return an iterator for the file. - """ - if self._closed: + if self.closed: raise ValueError('I/O operation on closed file') return self xreadlines = __iter__ def next(self): - if self._closed: + if self.closed: raise ValueError('I/O operation on closed file') - line = self.fd.readline() + line = self.stream.readline() if line == '': raise StopIteration return line + def truncate(self, size=None): + if self.closed: + raise ValueError('I/O operation on closed file') + if size is None: + size = self.stream.tell() + self.stream.truncate(size) + + def flush(self): + if self.closed: + raise ValueError('I/O operation on closed file') + self.stream.flush() + def close(self): - """ - Close the file - """ - self._closed = True - try: - self.fd.close() - except AttributeError: - pass + if not self.closed: + self.closed = True + self.stream.close() - def __getattr__(self, attr): - """ - Handle the readonly attributes and then delegate the other - methods to the underlying file object, setting the 'closed' - attribute if you close the file. - """ - if attr in ['fd', 'softspace', 'reading', 'writing']: - return self.__dict__[attr] - elif attr in ['mode', 'name', 'closed', 'encoding']: - return self.__dict__['_' + attr] - - return getattr(self.fd, attr) - - def __setattr__(self, attr, val): - "Make some attributes readonly." - if attr in ['mode', 'name', 'closed', 'encoding']: - raise TypeError, "readonly attribute:'%s'" % attr - self.__dict__[attr] = val - - def seek(self, *args, **kw): - if self._closed: - raise ValueError('I/O operation on closed file') - self.fd.seek(*args, **kw) - - def write(self, *args, **kw): - if self._closed: - raise ValueError('I/O operation on closed file') - self.fd.write(*args, **kw) - - def writelines(self, seq = ()): - if self._closed: - raise ValueError('I/O operation on closed file') - for line in seq: - self.write(line) - def readinto(self, a=None): 'Obsolete method, do not use it.' - if self._closed: - raise ValueError('I/O operation on closed file') - if type(a) != array: + from array import array + if not isinstance(a, array): raise TypeError('Can only read into array objects') - i = 0 - for char in self.read(len(a)): - a[i] = char - i += 1 - return i + length = len(a) + data = self.read(length) + del a[:] + a.fromstring(data + '\x00' * (length-len(data))) + return len(data) Copied: pypy/dist/pypy/lib/_sio.py (from r8690, pypy/dist/pypy/lib/sio.py) ============================================================================== --- pypy/dist/pypy/lib/sio.py (original) +++ pypy/dist/pypy/lib/_sio.py Sat Jan 29 12:14:16 2005 @@ -1,53 +1,257 @@ """New standard I/O library. -This code is still very young and experimental! +Based on sio.py from Guido van Rossum. -There are fairly complete unit tests in test_sio.py. - -The design is simple: - -- A raw stream supports read(n), write(s), seek(offset, whence=0) and - tell(). This is generally unbuffered. Raw streams may support - Unicode. - -- A basis stream provides the raw stream API and builds on a much more - low-level API, e.g. the os, mmap or socket modules. - -- A filtering stream is raw stream built on top of another raw stream. - There are filtering streams for universal newline translation and - for unicode translation. - -- A buffering stream supports the full classic Python I/O API: - read(n=-1), readline(), readlines(sizehint=0), tell(), seek(offset, - whence=0), write(s), writelines(lst), as well as __iter__() and - next(). (There's also readall() but that's a synonym for read() - without arguments.) This is a superset of the raw stream API. I - haven't thought about fileno() and isatty() yet, nor about - truncate() or the various attributes like name and mode. Also, - close() is not implemented right. We really need only one buffering - stream implementation, which is a filtering stream. +- This module contains various stream classes which provide a subset of the + classic Python I/O API: read(n), write(s), tell(), seek(offset, whence=0), + readall(), readline(), truncate(size), flush(), close(). + +- This is not for general usage: + * read(n) may return less than n bytes, just like os.read(). + * some other methods also have no default parameters. + * close() should be called exactly once and no further operations performed; + there is no __del__() closing the stream for you. + * some methods may raise NotImplementedError. + +- A 'basis stream' provides I/O using a low-level API, like the os, mmap or + socket modules. + +- A 'filtering stream' builds on top of another stream. There are filtering + streams for universal newline translation, for unicode translation, and + for buffering. You typically take a basis stream, place zero or more filtering -streams on top of it, and then top it off with a buffering stream. +streams on top of it, and then top it off with an input-buffering and/or +an outout-buffering stream. """ import os +# ____________________________________________________________ + + class Stream(object): - "All streams except the base ones need to inherit from this class." - base = None - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - return getattr(self.base, name) + + """Base class for streams. Provides a default implementation of + some methods.""" + + def read(self, n): + raise NotImplementedError + + def write(self, data): + raise NotImplementedError + + def tell(self): + raise NotImplementedError + + def seek(self, offset, whence=0): + raise NotImplementedError + + def readall(self): + bufsize = 8192 + result = [] + while True: + data = self.read(bufsize) + if not data: + break + result.append(data) + if bufsize < 4194304: # 4 Megs + bufsize <<= 1 + return ''.join(result) + + def readline(self): + # very inefficient + result = [] + c = self.read(1) + while c: + result.append(c) + if c == '\n': + break + c = self.read(1) + return ''.join(result) + + def truncate(self, size): + raise NotImplementedError + + def flush(self): + pass + + def close(self): + pass + + +class DiskFile(Stream): + + """Standard I/O basis stream using os.open/close/read/write/lseek""" + + def __init__(self, fd): + self.fd = fd + + def seek(self, offset, whence=0): + os.lseek(self.fd, offset, whence) + + def tell(self): + return os.lseek(self.fd, 0, 1) + + def read(self, n): + return os.read(self.fd, n) + + def write(self, data): + while data: + n = os.write(self.fd, data) + data = data[n:] + + def close(self): + os.close(self.fd) + + def truncate(self, size): + try: + os.ftruncate(self.fd, size) + except AttributeError: + raise NotImplementedError + + +class MMapFile(Stream): + + """Standard I/O basis stream using mmap.""" + +## def __init__(self, filename, mode="r"): +## import mmap +## self.filename = filename +## self.mode = mode +## if mode == "r": +## flag = os.O_RDONLY +## self.access = mmap.ACCESS_READ +## else: +## if mode == "w": +## flag = os.O_RDWR | os.O_CREAT +## elif mode == "a": +## flag = os.O_RDWR +## else: +## raise ValueError, "mode should be 'r', 'w' or 'a'" +## self.access = mmap.ACCESS_WRITE +## if hasattr(os, "O_BINARY"): +## flag |= os.O_BINARY +## self.fd = os.open(filename, flag) +## try: +## self.mapfile() +## except: +## os.close(self.fd) +## raise +## self.pos = 0 + + def __init__(self, fd, mmapaccess): + self.fd = fd + self.access = mmapaccess + self.pos = 0 + self.remapfile() + + def remapfile(self): + import mmap + size = os.fstat(self.fd).st_size + self.mm = mmap.mmap(self.fd, size, access=self.access) + + def close(self): + self.mm.close() + os.close(self.fd) + + def tell(self): + return self.pos + + def seek(self, offset, whence=0): + if whence == 0: + self.pos = max(0, offset) + elif whence == 1: + self.pos = max(0, self.pos + offset) + elif whence == 2: + self.pos = max(0, self.mm.size() + offset) + else: + raise ValueError, "seek(): whence must be 0, 1 or 2" + + def readall(self): + filesize = self.mm.size() # Actual file size, may be more than mapped + n = filesize - self.pos + data = self.mm[self.pos:] + if len(data) < n: + del data + # File grew since opened; remap to get the new data + self.remapfile() + data = self.mm[self.pos:] + self.pos += len(data) + return data + + def read(self, n): + end = self.pos + n + data = self.mm[self.pos:end] + if not data: + # is there more data to read? + filesize = self.mm.size() #Actual file size, may be more than mapped + if filesize > self.pos: + # File grew since opened; remap to get the new data + self.remapfile() + data = self.mm[self.pos:end] + self.pos += len(data) + return data + + def readline(self): + hit = self.mm.find("\n", self.pos) + 1 + if not hit: + # is there more data to read? + filesize = self.mm.size() # Actual file size, may be more than mapped + if filesize <= len(self.mm): + return "" + # File grew since opened; remap to get the new data + self.remapfile() + hit = self.mm.find("\n", self.pos) + 1 + if hit: + # Got a whole line + data = self.mm[self.pos:hit] + self.pos = hit + else: + # Read whatever we've got -- may be empty + data = self.mm[self.pos:] + self.pos += len(data) + return data + + def write(self, data): + end = self.pos + len(data) + try: + self.mm[self.pos:end] = data + # This can raise IndexError on Windows, ValueError on Unix + except (IndexError, ValueError): + # XXX On Unix, this resize() call doesn't work + self.mm.resize(end) + self.mm[self.pos:end] = data + self.pos = end + + def flush(self): + self.mm.flush() + +# ____________________________________________________________ + + +def PassThrough(meth_name, flush_buffers): + if flush_buffers: + code = """def %s(self, *args): + self.flush_buffers() + return self.base.%s(*args) +""" + else: + code = """def %s(self, *args): + return self.base.%s(*args) +""" + d = {} + exec code % (meth_name, meth_name) in d + return d[meth_name] + class BufferingInputStream(Stream): """Standard buffering input stream. - This is typically the top of the stack. + This, and BufferingOutputStream if needed, are typically at the top of + the stack of streams. """ bigsize = 2**19 # Half a Meg @@ -55,14 +259,9 @@ def __init__(self, base, bufsize=None): self.base = base - self.do_read = getattr(base, "read", None) - # function to fill buffer some more - self.do_tell = getattr(base, "tell", None) - # None, or return a byte offset - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.close = base.close - + self.do_read = base.read # function to fill buffer some more + self.do_tell = base.tell # return a byte offset + self.do_seek = base.seek # seek to a byte offset if bufsize is None: # Get default from the class bufsize = self.bufsize self.bufsize = bufsize # buffer size (hint only) @@ -72,6 +271,16 @@ # self.lines contains no "\n" # self.buf may contain "\n" + def flush_buffers(self): + if self.lines or self.buf: + try: + self.do_seek(self.tell()) + except NotImplementedError: + pass + else: + self.lines = [] + self.buf = "" + def tell(self): bytes = self.do_tell() # This may fail offset = len(self.buf) @@ -84,15 +293,46 @@ # This may fail on the do_seek() or do_tell() call. # But it won't call either on a relative forward seek. # Nor on a seek to the very end. - if whence == 0 or (whence == 2 and self.do_seek is not None): - self.do_seek(offset, whence) + if whence == 0: + self.do_seek(offset, 0) self.lines = [] self.buf = "" return + if whence == 1: + if offset < 0: + self.do_seek(self.tell() + offset, 0) + self.lines = [] + self.buf = "" + return + while self.lines: + line = self.lines[0] + if offset <= len(line): + self.lines[0] = line[offset:] + return + offset -= len(self.lines[0]) - 1 + del self.lines[0] + assert not self.lines + if offset <= len(self.buf): + self.buf = self.buf[offset:] + return + offset -= len(self.buf) + self.buf = "" + try: + self.do_seek(offset, 1) + except NotImplementedError: + self.read(offset) + return if whence == 2: + try: + self.do_seek(offset, 2) + except NotImplementedError: + pass + else: + self.lines = [] + self.buf = "" + return # Skip relative to EOF by reading and saving only just as # much as needed - assert self.do_seek is None data = "\n".join(self.lines + [self.buf]) total = len(data) buffers = [data] @@ -115,30 +355,6 @@ self.buf = "".join(buffers) self.lines = [] return - if whence == 1: - if offset < 0: - self.do_seek(self.tell() + offset, 0) - self.lines = [] - self.buf = "" - return - while self.lines: - line = self.lines[0] - if offset <= len(line): - self.lines[0] = line[offset:] - return - offset -= len(self.lines[0]) - 1 - del self.lines[0] - assert not self.lines - if offset <= len(self.buf): - self.buf = self.buf[offset:] - return - offset -= len(self.buf) - self.buf = "" - if self.do_seek is None: - self.read(offset) - else: - self.do_seek(offset, 1) - return raise ValueError, "whence should be 0, 1 or 2" def readall(self): @@ -155,10 +371,7 @@ bufsize = max(bufsize*2, self.bigsize) return "".join(more) - def read(self, n=-1): - if n < 0: - return self.readall() - + def read(self, n): if self.lines: # See if this can be satisfied from self.lines[0] line = self.lines[0] @@ -217,10 +430,7 @@ more[-1] = data[:cutoff] return "".join(more) - def __iter__(self): - return self - - def next(self): + def readline(self): if self.lines: return self.lines.pop(0) + "\n" @@ -244,89 +454,60 @@ break buf.append(self.buf) - line = "".join(buf) - if not line: - raise StopIteration - return line + return "".join(buf) - def readline(self): - try: - return self.next() - except StopIteration: - return "" + write = PassThrough("write", flush_buffers=True) + truncate = PassThrough("truncate", flush_buffers=True) + flush = PassThrough("flush", flush_buffers=True) + close = PassThrough("close", flush_buffers=False) - def readlines(self, sizehint=0): - return list(self) class BufferingOutputStream(Stream): """Standard buffering output stream. - This is typically the top of the stack. + This, and BufferingInputStream if needed, are typically at the top of + the stack of streams. """ - bigsize = 2**19 # Half a Meg - bufsize = 2**13 # 8 K - def __init__(self, base, bufsize=None): self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - + self.do_write = base.write # write more data + self.do_tell = base.tell # return a byte offset if bufsize is None: # Get default from the class bufsize = self.bufsize self.bufsize = bufsize # buffer size (hint only) self.buf = "" - self.tell() - - def tell(self): - assert self.do_tell is not None - if not hasattr(self, 'pos'): - self.pos = self.do_tell() - return self.pos - - def seek(self, offset, whence=0): - self.flush() - self.do_seek(offset, whence) - self.pos = self.do_tell() + def flush_buffers(self): + if self.buf: + self.do_write(self.buf) + self.buf = "" + + def tell(self): + return self.do_tell() + len(self.buf) - def flush(self): - self.do_write(self.buf) - self.buf = '' - self.base.flush() - def write(self, data): buflen = len(self.buf) datalen = len(data) - if datalen + buflen < self.bufsize: + if datalen + buflen <= self.bufsize: self.buf += data - self.pos += datalen - else: + elif buflen: self.buf += data[:self.bufsize-buflen] - self.pos += self.bufsize-buflen self.do_write(self.buf) - self.buf = '' + self.buf = "" self.write(data[self.bufsize-buflen:]) + else: + self.do_write(data) - def writelines(self, sequence): - for s in sequence: - self.write(s) - - def close(self): - if (self.buf): - self.do_write(self.buf) - self.buf = '' - self.do_close() + read = PassThrough("read", flush_buffers=True) + readall = PassThrough("readall", flush_buffers=True) + readline = PassThrough("readline", flush_buffers=True) + seek = PassThrough("seek", flush_buffers=True) + truncate = PassThrough("truncate", flush_buffers=True) + flush = PassThrough("flush", flush_buffers=True) + close = PassThrough("close", flush_buffers=True) - def truncate(self, size=None): - self.flush() - self.do_truncate(size) class LineBufferingOutputStream(BufferingOutputStream): @@ -335,116 +516,15 @@ This is typically the top of the stack. """ - def __init__(self, base, bufsize=None): - self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - - self.linesep = os.linesep - self.buf = "" # raw data (may contain "\n") - self.tell() - - def write(self, data): - all_lines = data.split(self.linesep) - full_lines = all_lines[:-1] - for line in full_lines: - line += self.linesep - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - self.do_write(self.buf) - self.buf = '' - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - # The last part of the split data never has a terminating linesep. - # If the data has a terminating linesep, the last element is an - # empty string. - - line = all_lines[-1] - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - def flush(self): - if self.buf: - self.do_write(self.buf) - self.buf = '' - self.base.flush() - - -class BufferingInputOutputStream(Stream): - """To handle buffered input and output at the same time, we are - switching back and forth between using BuffereingInputStream - and BufferingOutputStream as reads and writes are done. - A more optimal solution would be to read and write on the same - buffer, but it would take a fair bit of time to implement. - """ - - def __init__(self, base, bufsize=None): - self.base = base - self.bufsize = bufsize - self.reader = None - self.writer = None - - def read(self, n=-1): - if not self.reader: - if self.writer: - self.writer.flush() - self.writer = None - self.reader = BufferingInputStream(self.base, self.bufsize) - return self.reader.read(n) - def write(self, data): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.write(data) - - def truncate(self, size=None): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.truncate(size) + super(LineBufferingOutputStream, self).write(data) + p = self.buf.rfind('\n') + 1 + if p: + self.do_write(self.buf[:p]) + self.buf = self.buf[p:] - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - if not self.reader and not self.writer: - self.reader = BufferingInputStream(self.base, self.bufsize) +# ____________________________________________________________ - if self.reader: - return getattr(self.reader, name) - - return getattr(self.writer, name) class CRLFFilter(Stream): @@ -458,9 +538,8 @@ self.base = base self.do_read = base.read self.atcr = False - self.close = base.close - def read(self, n=-1): + def read(self, n): data = self.do_read(n) if self.atcr: if data.startswith("\n"): @@ -472,259 +551,9 @@ data = data.replace("\r", "\n") # Remaining \r are standalone return data -class MMapFile(object): + flush = PassThrough("flush", flush_buffers=False) + close = PassThrough("close", flush_buffers=False) - """Standard I/O basis stream using mmap.""" - - def __init__(self, filename, mode="r"): - import mmap - self.filename = filename - self.mode = mode - if mode == "r": - flag = os.O_RDONLY - self.access = mmap.ACCESS_READ - else: - if mode == "w": - flag = os.O_RDWR | os.O_CREAT - elif mode == "a": - flag = os.O_RDWR - else: - raise ValueError, "mode should be 'r', 'w' or 'a'" - self.access = mmap.ACCESS_WRITE - if hasattr(os, "O_BINARY"): - flag |= os.O_BINARY - self.fd = os.open(filename, flag) - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - self.pos = 0 - - def __del__(self): - self.close() - - mm = fd = None - - def close(self): - if self.mm is not None: - self.mm.close() - self.mm = None - if self.fd is not None: - os.close(self.fd) - self.fd = None - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 0: - self.pos = max(0, offset) - elif whence == 1: - self.pos = max(0, self.pos + offset) - elif whence == 2: - self.pos = max(0, self.mm.size() + offset) - else: - raise ValueError, "seek(): whence must be 0, 1 or 2" - - def readall(self): - return self.read() - - def read(self, n=-1): - import mmap - if n >= 0: - aim = self.pos + n - else: - aim = self.mm.size() # Actual file size, may be more than mapped - n = aim - self.pos - data = self.mm[self.pos:aim] - if len(data) < n: - del data - # File grew since opened; remap to get the new data - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - data = self.mm[self.pos:aim] - self.pos += len(data) - return data - - def __iter__(self): - return self - - def readline(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - self.pos += len(data) - return data - - def next(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - if not data: - raise StopIteration - self.pos += len(data) - return data - - def readlines(self, sizehint=0): - return list(iter(self.readline, "")) - - def write(self, data): - end = self.pos + len(data) - try: - self.mm[self.pos:end] = data - # This can raise IndexError on Windows, ValueError on Unix - except (IndexError, ValueError): - # XXX On Unix, this resize() call doesn't work - self.mm.resize(end) - self.mm[self.pos:end] = data - self.pos = end - - def writelines(self, lines): - filter(self.write, lines) - - def flush(self): - if self.mm is None: - raise ValueError('I/O operation on closed file') - self.mm.flush() - -class DiskFile(object): - - """Standard I/O basis stream using os.open/close/read/write/lseek""" - - # This is not quite correct, since more letters are allowed after - # these. However, the following are the only starting strings allowed - # in the mode parameter. - modes = { - 'r' : os.O_RDONLY, - 'rb' : os.O_RDONLY, - 'rU' : os.O_RDONLY, - 'U' : os.O_RDONLY, - 'w' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'wb' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'a' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'ab' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'r+' : os.O_RDWR, - 'rb+': os.O_RDWR, - 'r+b': os.O_RDWR, - 'w+' : os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'wb+': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'w+b': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'a+' : os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'ab+': os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'a+b': os.O_RDWR | os.O_CREAT | os.O_EXCL, - } - def __init__(self, filename, mode="r"): - self.filename = filename - self.mode = mode - try: - flag = DiskFile.modes[mode] - except KeyError: - raise ValueError, "mode should be 'r', 'r+', 'w', 'w+' or 'a+'" - - O_BINARY = getattr(os, "O_BINARY", 0) - flag |= O_BINARY - try: - self.fd = os.open(filename, flag) - except OSError: - # Opening in mode 'a' or 'a+' and file already exists - flag = flag & (os.O_RDWR | O_BINARY) - self.fd = os.open(filename, flag) - if mode[0] == 'a': - os.lseek(self.fd, 0, 2) # Move to end of file - - def seek(self, offset, whence=0): - if self.fd is None: - raise ValueError('I/O operation on closed file') - os.lseek(self.fd, offset, whence) - - def tell(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return os.lseek(self.fd, 0, 1) - - def read(self, n=-1): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if n >= 0: - return os.read(self.fd, n) - data = [] - while 1: - moreData = os.read(self.fd, 2**20) - if len(moreData) == 0: - return ''.join(data) - data.append(moreData) - - def write(self, data): - if self.fd is None: - raise ValueError('I/O operation on closed file') - while data: - n = os.write(self.fd, data) - data = data[n:] - - def close(self): - fd = self.fd - if fd is not None: - self.fd = None - os.close(fd) - - def truncate(self, size=None): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if size is None: - size = self.tell() - try: - os.ftruncate(self.fd, size) - except AttributeError: - raise NotImplementedError - - def isatty(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - try: - return os.isatty(self.fd) - except AttributeError: - raise NotImplementedError - - def fileno(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return self.fd - - def flush(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - - def __del__(self): - try: - self.close() - except: - pass class TextInputFilter(Stream): @@ -732,45 +561,42 @@ def __init__(self, base): self.base = base # must implement read, may implement tell, seek + self.do_read = base.read self.atcr = False # Set when last char read was \r self.buf = "" # Optional one-character read-ahead buffer - self.close = base.close self.CR = False self.NL = False self.CRLF = False - - def __getattr__(self, name): - if name == 'newlines': - foundchars = self.CR * 1 + self.NL * 2 + self.CRLF * 4 - if not foundchars: - return None - if foundchars in [1, 2, 4]: - if self.CR: - return '\r' - elif self.NL: - return '\n' - else: - return '\r\n' + + def getnewlines(self): + foundchars = self.CR * 1 + self.NL * 2 + self.CRLF * 4 + if not foundchars: + return None + if foundchars in [1, 2, 4]: + if self.CR: + return '\r' + elif self.NL: + return '\n' else: - result = [] - if self.CR: - result.append('\r') - if self.NL: - result.append('\n') - if self.CRLF: - result.append('\r\n') - return tuple(result) - + return '\r\n' + else: + result = [] + if self.CR: + result.append('\r') + if self.NL: + result.append('\n') + if self.CRLF: + result.append('\r\n') + return tuple(result) + def read(self, n): """Read up to n bytes.""" - if n <= 0: - return "" if self.buf: assert not self.atcr data = self.buf self.buf = "" return data - data = self.base.read(n) + data = self.do_read(n) # The following whole ugly mess is because we need to keep track of # exactly which line separators we have seen for self.newlines, @@ -787,7 +613,7 @@ data = data[1:] self.CRLF = True if not data: - data = self.base.read(n) + data = self.do_read(n) else: self.CR = True self.atcr = False @@ -827,13 +653,34 @@ # Must read the next byte to see if it's \n, # because then we must report the next position. assert not self.buf - self.buf = self.base.read(1) + self.buf = self.do_read(1) pos += 1 self.atcr = False if self.buf == "\n": self.buf = "" return pos - len(self.buf) + def flush_buffers(self): + if self.atcr: + assert not self.buf + self.buf = self.do_read(1) + self.atcr = False + if self.buf == "\n": + self.buf = "" + if self.buf: + try: + self.do_seek(-len(self.buf), 1) + except NotImplementedError: + pass + else: + self.buf = "" + + write = PassThrough("write", flush_buffers=True) + truncate = PassThrough("truncate", flush_buffers=True) + flush = PassThrough("flush", flush_buffers=True) + close = PassThrough("close", flush_buffers=False) + + class TextOutputFilter(Stream): """Filtering output stream for universal newline translation.""" @@ -842,18 +689,20 @@ assert linesep in ["\n", "\r\n", "\r"] self.base = base # must implement write, may implement seek, tell self.linesep = linesep - self.close = base.close def write(self, data): - if self.linesep is not "\n" and "\n" in data: - data = data.replace("\n", self.linesep) + data = data.replace("\n", self.linesep) self.base.write(data) - def seek(self, offset, whence=0): - self.base.seek(offset, whence) + tell = PassThrough("tell", flush_buffers=False) + seek = PassThrough("seek", flush_buffers=False) + read = PassThrough("read", flush_buffers=False) + readall = PassThrough("readall", flush_buffers=False) + readline = PassThrough("readline", flush_buffers=False) + truncate = PassThrough("truncate", flush_buffers=False) + flush = PassThrough("flush", flush_buffers=False) + close = PassThrough("close", flush_buffers=False) - def tell(self): - return self.base.tell() class DecodingInputFilter(Stream): @@ -861,11 +710,9 @@ def __init__(self, base, encoding="utf8", errors="strict"): self.base = base + self.do_read = base.read self.encoding = encoding self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close def read(self, n): """Read *approximately* n bytes, then decode them. @@ -878,14 +725,14 @@ This does *not* translate newlines; you can stack TextInputFilter. """ - data = self.base.read(n) + data = self.do_read(n) try: return data.decode(self.encoding, self.errors) except ValueError: # XXX Sigh. decode() doesn't handle incomplete strings well. # Use the retry strategy from codecs.StreamReader. for i in range(9): - more = self.base.read(1) + more = self.do_read(1) if not more: raise data += more @@ -895,19 +742,32 @@ pass raise + write = PassThrough("write", flush_buffers=False) + truncate = PassThrough("truncate", flush_buffers=False) + flush = PassThrough("flush", flush_buffers=False) + close = PassThrough("close", flush_buffers=False) + + class EncodingOutputFilter(Stream): """Filtering output stream that writes to an encoded file.""" def __init__(self, base, encoding="utf8", errors="strict"): self.base = base + self.do_write = base.write self.encoding = encoding self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close def write(self, chars): if isinstance(chars, str): chars = unicode(chars) # Fail if it's not ASCII - self.base.write(chars.encode(self.encoding, self.errors)) + self.do_write(chars.encode(self.encoding, self.errors)) + + tell = PassThrough("tell", flush_buffers=False) + seek = PassThrough("seek", flush_buffers=False) + read = PassThrough("read", flush_buffers=False) + readall = PassThrough("readall", flush_buffers=False) + readline = PassThrough("readline", flush_buffers=False) + truncate = PassThrough("truncate", flush_buffers=False) + flush = PassThrough("flush", flush_buffers=False) + close = PassThrough("close", flush_buffers=False) Deleted: /pypy/dist/pypy/lib/sio.py ============================================================================== --- /pypy/dist/pypy/lib/sio.py Sat Jan 29 12:14:16 2005 +++ (empty file) @@ -1,913 +0,0 @@ -"""New standard I/O library. - -This code is still very young and experimental! - -There are fairly complete unit tests in test_sio.py. - -The design is simple: - -- A raw stream supports read(n), write(s), seek(offset, whence=0) and - tell(). This is generally unbuffered. Raw streams may support - Unicode. - -- A basis stream provides the raw stream API and builds on a much more - low-level API, e.g. the os, mmap or socket modules. - -- A filtering stream is raw stream built on top of another raw stream. - There are filtering streams for universal newline translation and - for unicode translation. - -- A buffering stream supports the full classic Python I/O API: - read(n=-1), readline(), readlines(sizehint=0), tell(), seek(offset, - whence=0), write(s), writelines(lst), as well as __iter__() and - next(). (There's also readall() but that's a synonym for read() - without arguments.) This is a superset of the raw stream API. I - haven't thought about fileno() and isatty() yet, nor about - truncate() or the various attributes like name and mode. Also, - close() is not implemented right. We really need only one buffering - stream implementation, which is a filtering stream. - -You typically take a basis stream, place zero or more filtering -streams on top of it, and then top it off with a buffering stream. - -""" - -import os - -class Stream(object): - "All streams except the base ones need to inherit from this class." - base = None - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - return getattr(self.base, name) - -class BufferingInputStream(Stream): - - """Standard buffering input stream. - - This is typically the top of the stack. - """ - - bigsize = 2**19 # Half a Meg - bufsize = 2**13 # 8 K - - def __init__(self, base, bufsize=None): - self.base = base - self.do_read = getattr(base, "read", None) - # function to fill buffer some more - self.do_tell = getattr(base, "tell", None) - # None, or return a byte offset - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.close = base.close - - if bufsize is None: # Get default from the class - bufsize = self.bufsize - self.bufsize = bufsize # buffer size (hint only) - self.lines = [] # ready-made lines (sans "\n") - self.buf = "" # raw data (may contain "\n") - # Invariant: readahead == "\n".join(self.lines + [self.buf]) - # self.lines contains no "\n" - # self.buf may contain "\n" - - def tell(self): - bytes = self.do_tell() # This may fail - offset = len(self.buf) - for line in self.lines: - offset += len(line) + 1 - assert bytes >= offset, (locals(), self.__dict__) - return bytes - offset - - def seek(self, offset, whence=0): - # This may fail on the do_seek() or do_tell() call. - # But it won't call either on a relative forward seek. - # Nor on a seek to the very end. - if whence == 0 or (whence == 2 and self.do_seek is not None): - self.do_seek(offset, whence) - self.lines = [] - self.buf = "" - return - if whence == 2: - # Skip relative to EOF by reading and saving only just as - # much as needed - assert self.do_seek is None - data = "\n".join(self.lines + [self.buf]) - total = len(data) - buffers = [data] - self.lines = [] - self.buf = "" - while 1: - data = self.do_read(self.bufsize) - if not data: - break - buffers.append(data) - total += len(data) - while buffers and total >= len(buffers[0]) - offset: - total -= len(buffers[0]) - del buffers[0] - cutoff = total + offset - if cutoff < 0: - raise TypeError, "cannot seek back" - if buffers: - buffers[0] = buffers[0][cutoff:] - self.buf = "".join(buffers) - self.lines = [] - return - if whence == 1: - if offset < 0: - self.do_seek(self.tell() + offset, 0) - self.lines = [] - self.buf = "" - return - while self.lines: - line = self.lines[0] - if offset <= len(line): - self.lines[0] = line[offset:] - return - offset -= len(self.lines[0]) - 1 - del self.lines[0] - assert not self.lines - if offset <= len(self.buf): - self.buf = self.buf[offset:] - return - offset -= len(self.buf) - self.buf = "" - if self.do_seek is None: - self.read(offset) - else: - self.do_seek(offset, 1) - return - raise ValueError, "whence should be 0, 1 or 2" - - def readall(self): - self.lines.append(self.buf) - more = ["\n".join(self.lines)] - self.lines = [] - self.buf = "" - bufsize = self.bufsize - while 1: - data = self.do_read(bufsize) - if not data: - break - more.append(data) - bufsize = max(bufsize*2, self.bigsize) - return "".join(more) - - def read(self, n=-1): - if n < 0: - return self.readall() - - if self.lines: - # See if this can be satisfied from self.lines[0] - line = self.lines[0] - if len(line) >= n: - self.lines[0] = line[n:] - return line[:n] - - # See if this can be satisfied *without exhausting* self.lines - k = 0 - i = 0 - for line in self.lines: - k += len(line) - if k >= n: - lines = self.lines[:i] - data = self.lines[i] - cutoff = len(data) - (k-n) - lines.append(data[:cutoff]) - self.lines[:i+1] = [data[cutoff:]] - return "\n".join(lines) - k += 1 - i += 1 - - # See if this can be satisfied from self.lines plus self.buf - if k + len(self.buf) >= n: - lines = self.lines - self.lines = [] - cutoff = n - k - lines.append(self.buf[:cutoff]) - self.buf = self.buf[cutoff:] - return "\n".join(lines) - - else: - # See if this can be satisfied from self.buf - data = self.buf - k = len(data) - if k >= n: - cutoff = len(data) - (k-n) - self.buf = data[cutoff:] - return data[:cutoff] - - lines = self.lines - self.lines = [] - lines.append(self.buf) - self.buf = "" - data = "\n".join(lines) - more = [data] - k = len(data) - while k < n: - data = self.do_read(max(self.bufsize, n-k)) - k += len(data) - more.append(data) - if not data: - break - cutoff = len(data) - (k-n) - self.buf = data[cutoff:] - more[-1] = data[:cutoff] - return "".join(more) - - def __iter__(self): - return self - - def next(self): - if self.lines: - return self.lines.pop(0) + "\n" - - # This block is needed because read() can leave self.buf - # containing newlines - self.lines = self.buf.split("\n") - self.buf = self.lines.pop() - if self.lines: - return self.lines.pop(0) + "\n" - - buf = self.buf and [self.buf] or [] - while 1: - self.buf = self.do_read(self.bufsize) - self.lines = self.buf.split("\n") - self.buf = self.lines.pop() - if self.lines: - buf.append(self.lines.pop(0)) - buf.append("\n") - break - if not self.buf: - break - buf.append(self.buf) - - line = "".join(buf) - if not line: - raise StopIteration - return line - - def readline(self): - try: - return self.next() - except StopIteration: - return "" - - def readlines(self, sizehint=0): - return list(self) - -class BufferingOutputStream(Stream): - - """Standard buffering output stream. - - This is typically the top of the stack. - """ - - bigsize = 2**19 # Half a Meg - bufsize = 2**13 # 8 K - - def __init__(self, base, bufsize=None): - self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - - if bufsize is None: # Get default from the class - bufsize = self.bufsize - self.bufsize = bufsize # buffer size (hint only) - self.buf = "" - self.tell() - - def tell(self): - assert self.do_tell is not None - if not hasattr(self, 'pos'): - self.pos = self.do_tell() - - return self.pos - - def seek(self, offset, whence=0): - self.flush() - self.do_seek(offset, whence) - self.pos = self.do_tell() - - def flush(self): - self.do_write(self.buf) - self.buf = '' - self.base.flush() - - def write(self, data): - buflen = len(self.buf) - datalen = len(data) - if datalen + buflen < self.bufsize: - self.buf += data - self.pos += datalen - else: - self.buf += data[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(data[self.bufsize-buflen:]) - - def writelines(self, sequence): - for s in sequence: - self.write(s) - - def close(self): - if (self.buf): - self.do_write(self.buf) - self.buf = '' - self.do_close() - - def truncate(self, size=None): - self.flush() - self.do_truncate(size) - -class LineBufferingOutputStream(BufferingOutputStream): - - """Line buffering output stream. - - This is typically the top of the stack. - """ - - def __init__(self, base, bufsize=None): - self.base = base - self.do_write = base.write # Flush buffer - self.do_tell = base.tell - # Return a byte offset; has to exist or this __init__() will fail - self.do_seek = getattr(base, "seek", None) - # None, or seek to a byte offset - self.do_close = base.close # Close file - self.do_truncate = base.truncate # Truncate file - - self.linesep = os.linesep - self.buf = "" # raw data (may contain "\n") - self.tell() - - def write(self, data): - all_lines = data.split(self.linesep) - full_lines = all_lines[:-1] - for line in full_lines: - line += self.linesep - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - self.do_write(self.buf) - self.buf = '' - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - # The last part of the split data never has a terminating linesep. - # If the data has a terminating linesep, the last element is an - # empty string. - - line = all_lines[-1] - buflen = len(self.buf) - linelen = len(line) - if linelen + buflen < self.bufsize: - self.buf += line - self.pos += linelen - else: - self.buf += line[:self.bufsize-buflen] - self.pos += self.bufsize-buflen - self.do_write(self.buf) - self.buf = '' - self.write(line[self.bufsize-buflen:]) - - def flush(self): - if self.buf: - self.do_write(self.buf) - self.buf = '' - self.base.flush() - - -class BufferingInputOutputStream(Stream): - """To handle buffered input and output at the same time, we are - switching back and forth between using BuffereingInputStream - and BufferingOutputStream as reads and writes are done. - A more optimal solution would be to read and write on the same - buffer, but it would take a fair bit of time to implement. - """ - - def __init__(self, base, bufsize=None): - self.base = base - self.bufsize = bufsize - self.reader = None - self.writer = None - - def read(self, n=-1): - if not self.reader: - if self.writer: - self.writer.flush() - self.writer = None - self.reader = BufferingInputStream(self.base, self.bufsize) - return self.reader.read(n) - - def write(self, data): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.write(data) - - def truncate(self, size=None): - if not self.writer: - if self.reader: - # Make sure the underlying file has the correct current - # position - self.reader.seek(self.reader.tell()) - self.reader = None - self.writer = BufferingOutputStream(self.base, self.bufsize) - return self.writer.truncate(size) - - def __getattr__(self, name): - """ - Delegate all other methods to the underlying file object. - """ - if not self.reader and not self.writer: - self.reader = BufferingInputStream(self.base, self.bufsize) - - if self.reader: - return getattr(self.reader, name) - - return getattr(self.writer, name) - -class CRLFFilter(Stream): - - """Filtering stream for universal newlines. - - TextInputFilter is more general, but this is faster when you don't - need tell/seek. - """ - - def __init__(self, base): - self.base = base - self.do_read = base.read - self.atcr = False - self.close = base.close - - def read(self, n=-1): - data = self.do_read(n) - if self.atcr: - if data.startswith("\n"): - data = data[1:] # Very rare case: in the middle of "\r\n" - self.atcr = False - if "\r" in data: - self.atcr = data.endswith("\r") # Test this before removing \r - data = data.replace("\r\n", "\n") # Catch \r\n this first - data = data.replace("\r", "\n") # Remaining \r are standalone - return data - -class MMapFile(object): - - """Standard I/O basis stream using mmap.""" - - def __init__(self, filename, mode="r"): - import mmap - self.filename = filename - self.mode = mode - if mode == "r": - flag = os.O_RDONLY - self.access = mmap.ACCESS_READ - else: - if mode == "w": - flag = os.O_RDWR | os.O_CREAT - elif mode == "a": - flag = os.O_RDWR - else: - raise ValueError, "mode should be 'r', 'w' or 'a'" - self.access = mmap.ACCESS_WRITE - if hasattr(os, "O_BINARY"): - flag |= os.O_BINARY - self.fd = os.open(filename, flag) - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - self.pos = 0 - - def __del__(self): - self.close() - - mm = fd = None - - def close(self): - if self.mm is not None: - self.mm.close() - self.mm = None - if self.fd is not None: - os.close(self.fd) - self.fd = None - - def tell(self): - return self.pos - - def seek(self, offset, whence=0): - if whence == 0: - self.pos = max(0, offset) - elif whence == 1: - self.pos = max(0, self.pos + offset) - elif whence == 2: - self.pos = max(0, self.mm.size() + offset) - else: - raise ValueError, "seek(): whence must be 0, 1 or 2" - - def readall(self): - return self.read() - - def read(self, n=-1): - import mmap - if n >= 0: - aim = self.pos + n - else: - aim = self.mm.size() # Actual file size, may be more than mapped - n = aim - self.pos - data = self.mm[self.pos:aim] - if len(data) < n: - del data - # File grew since opened; remap to get the new data - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - data = self.mm[self.pos:aim] - self.pos += len(data) - return data - - def __iter__(self): - return self - - def readline(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - self.pos += len(data) - return data - - def next(self): - import mmap - hit = self.mm.find("\n", self.pos) + 1 - if hit: - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Remap the file just in case - size = os.fstat(self.fd).st_size - self.mm = mmap.mmap(self.fd, size, access=self.access) - hit = self.mm.find("\n", self.pos) + 1 - if hit: - # Got a whole line after remapping - data = self.mm[self.pos:hit] - self.pos = hit - return data - # Read whatever we've got -- may be empty - data = self.mm[self.pos:self.mm.size()] - if not data: - raise StopIteration - self.pos += len(data) - return data - - def readlines(self, sizehint=0): - return list(iter(self.readline, "")) - - def write(self, data): - end = self.pos + len(data) - try: - self.mm[self.pos:end] = data - # This can raise IndexError on Windows, ValueError on Unix - except (IndexError, ValueError): - # XXX On Unix, this resize() call doesn't work - self.mm.resize(end) - self.mm[self.pos:end] = data - self.pos = end - - def writelines(self, lines): - filter(self.write, lines) - - def flush(self): - if self.mm is None: - raise ValueError('I/O operation on closed file') - self.mm.flush() - -class DiskFile(object): - - """Standard I/O basis stream using os.open/close/read/write/lseek""" - - # This is not quite correct, since more letters are allowed after - # these. However, the following are the only starting strings allowed - # in the mode parameter. - modes = { - 'r' : os.O_RDONLY, - 'rb' : os.O_RDONLY, - 'rU' : os.O_RDONLY, - 'U' : os.O_RDONLY, - 'w' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'wb' : os.O_WRONLY | os.O_CREAT | os.O_TRUNC, - 'a' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'ab' : os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 'r+' : os.O_RDWR, - 'rb+': os.O_RDWR, - 'r+b': os.O_RDWR, - 'w+' : os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'wb+': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'w+b': os.O_RDWR | os.O_CREAT | os.O_TRUNC, - 'a+' : os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'ab+': os.O_RDWR | os.O_CREAT | os.O_EXCL, - 'a+b': os.O_RDWR | os.O_CREAT | os.O_EXCL, - } - def __init__(self, filename, mode="r"): - self.filename = filename - self.mode = mode - try: - flag = DiskFile.modes[mode] - except KeyError: - raise ValueError, "mode should be 'r', 'r+', 'w', 'w+' or 'a+'" - - O_BINARY = getattr(os, "O_BINARY", 0) - flag |= O_BINARY - try: - self.fd = os.open(filename, flag) - except OSError: - # Opening in mode 'a' or 'a+' and file already exists - flag = flag & (os.O_RDWR | O_BINARY) - self.fd = os.open(filename, flag) - if mode[0] == 'a': - os.lseek(self.fd, 0, 2) # Move to end of file - - def seek(self, offset, whence=0): - if self.fd is None: - raise ValueError('I/O operation on closed file') - os.lseek(self.fd, offset, whence) - - def tell(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return os.lseek(self.fd, 0, 1) - - def read(self, n=-1): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if n >= 0: - return os.read(self.fd, n) - data = [] - while 1: - moreData = os.read(self.fd, 2**20) - if len(moreData) == 0: - return ''.join(data) - data.append(moreData) - - def write(self, data): - if self.fd is None: - raise ValueError('I/O operation on closed file') - while data: - n = os.write(self.fd, data) - data = data[n:] - - def close(self): - fd = self.fd - if fd is not None: - self.fd = None - os.close(fd) - - def truncate(self, size=None): - if self.fd is None: - raise ValueError('I/O operation on closed file') - if size is None: - size = self.tell() - try: - os.ftruncate(self.fd, size) - except AttributeError: - raise NotImplementedError - - def isatty(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - try: - return os.isatty(self.fd) - except AttributeError: - raise NotImplementedError - - def fileno(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - return self.fd - - def flush(self): - if self.fd is None: - raise ValueError('I/O operation on closed file') - - def __del__(self): - try: - self.close() - except: - pass - -class TextInputFilter(Stream): - - """Filtering input stream for universal newline translation.""" - - def __init__(self, base): - self.base = base # must implement read, may implement tell, seek - self.atcr = False # Set when last char read was \r - self.buf = "" # Optional one-character read-ahead buffer - self.close = base.close - self.CR = False - self.NL = False - self.CRLF = False - - def __getattr__(self, name): - if name == 'newlines': - foundchars = self.CR * 1 + self.NL * 2 + self.CRLF * 4 - if not foundchars: - return None - if foundchars in [1, 2, 4]: - if self.CR: - return '\r' - elif self.NL: - return '\n' - else: - return '\r\n' - else: - result = [] - if self.CR: - result.append('\r') - if self.NL: - result.append('\n') - if self.CRLF: - result.append('\r\n') - return tuple(result) - - def read(self, n): - """Read up to n bytes.""" - if n <= 0: - return "" - if self.buf: - assert not self.atcr - data = self.buf - self.buf = "" - return data - data = self.base.read(n) - - # The following whole ugly mess is because we need to keep track of - # exactly which line separators we have seen for self.newlines, - # grumble, grumble. This has an interesting corner-case. - # - # Consider a file consisting of exactly one line ending with '\r'. - # The first time you read(), you will not know whether it is a - # CR separator or half of a CRLF separator. Neither will be marked - # as seen, since you are waiting for your next read to determine - # what you have seen. But there's no more to read ... - - if self.atcr: - if data.startswith("\n"): - data = data[1:] - self.CRLF = True - if not data: - data = self.base.read(n) - else: - self.CR = True - self.atcr = False - - for i in range(len(data)): - if data[i] == '\n': - if i > 0 and data[i-1] == '\r': - self.CRLF = True - else: - self.NL = True - elif data[i] == '\r': - if i < len(data)-1 and data[i+1] != '\n': - self.CR = True - - if "\r" in data: - self.atcr = data.endswith("\r") - data = data.replace("\r\n", "\n").replace("\r", "\n") - - return data - - def seek(self, offset, whence=0): - """Seeks based on knowledge that does not come from a tell() - may go to the wrong place, since the number of - characters seen may not match the number of characters - that are actually in the file (where \r\n is the - line separator). Arithmetics on the result - of a tell() that moves beyond a newline character may in the - same way give the wrong result. - """ - self.base.seek(offset, whence) - self.atcr = False - self.buf = "" - - def tell(self): - pos = self.base.tell() - if self.atcr: - # Must read the next byte to see if it's \n, - # because then we must report the next position. - assert not self.buf - self.buf = self.base.read(1) - pos += 1 - self.atcr = False - if self.buf == "\n": - self.buf = "" - return pos - len(self.buf) - -class TextOutputFilter(Stream): - - """Filtering output stream for universal newline translation.""" - - def __init__(self, base, linesep=os.linesep): - assert linesep in ["\n", "\r\n", "\r"] - self.base = base # must implement write, may implement seek, tell - self.linesep = linesep - self.close = base.close - - def write(self, data): - if self.linesep is not "\n" and "\n" in data: - data = data.replace("\n", self.linesep) - self.base.write(data) - - def seek(self, offset, whence=0): - self.base.seek(offset, whence) - - def tell(self): - return self.base.tell() - -class DecodingInputFilter(Stream): - - """Filtering input stream that decodes an encoded file.""" - - def __init__(self, base, encoding="utf8", errors="strict"): - self.base = base - self.encoding = encoding - self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close - - def read(self, n): - """Read *approximately* n bytes, then decode them. - - Under extreme circumstances, - the return length could be longer than n! - - Always return a unicode string. - - This does *not* translate newlines; - you can stack TextInputFilter. - """ - data = self.base.read(n) - try: - return data.decode(self.encoding, self.errors) - except ValueError: - # XXX Sigh. decode() doesn't handle incomplete strings well. - # Use the retry strategy from codecs.StreamReader. - for i in range(9): - more = self.base.read(1) - if not more: - raise - data += more - try: - return data.decode(self.encoding, self.errors) - except ValueError: - pass - raise - -class EncodingOutputFilter(Stream): - - """Filtering output stream that writes to an encoded file.""" - - def __init__(self, base, encoding="utf8", errors="strict"): - self.base = base - self.encoding = encoding - self.errors = errors - self.tell = base.tell - self.seek = base.seek - self.close = base.close - - def write(self, chars): - if isinstance(chars, str): - chars = unicode(chars) # Fail if it's not ASCII - self.base.write(chars.encode(self.encoding, self.errors)) From arigo at codespeak.net Sat Jan 29 12:33:19 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 12:33:19 +0100 (MET) Subject: [pypy-svn] r8695 - pypy/dist/pypy/lib Message-ID: <20050129113319.E6F4827B8A@code1.codespeak.net> Author: arigo Date: Sat Jan 29 12:33:19 2005 New Revision: 8695 Modified: pypy/dist/pypy/lib/_file.py pypy/dist/pypy/lib/_sio.py Log: bug fixes; now it passes CPython's test_file. Modified: pypy/dist/pypy/lib/_file.py ============================================================================== --- pypy/dist/pypy/lib/_file.py (original) +++ pypy/dist/pypy/lib/_file.py Sat Jan 29 12:33:19 2005 @@ -79,9 +79,9 @@ """ def __init__(self, name, mode='r', bufsize=None): - self.mode = mode - self.name = name - self.closed = False + self._mode = mode + self._name = name + self._closed = True # Until the file is successfully opened self.softspace = 0 # Required according to file object docs self.encoding = None # This is not used internally by file objects @@ -110,14 +110,15 @@ if binary or universal: flag |= O_BINARY - fd = os.open(name, flag) + self.fd = os.open(name, flag) if basemode == 'a': try: - os.lseek(fd, 0, 2) + os.lseek(self.fd, 0, 2) except OSError: pass - self.stream = _sio.DiskFile(fd) + self.stream = _sio.DiskFile(self.fd) + self._closed = False reading = basemode == 'r' or plus writing = basemode != 'r' or plus @@ -144,9 +145,13 @@ if reading: self.stream = _sio.BufferingInputStream(self.stream, bufsize) + mode = property(lambda self: self._mode) + name = property(lambda self: self._name) + closed = property(lambda self: self._closed) + def read(self, n=-1): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') if n < 0: return self.stream.readall() @@ -158,52 +163,57 @@ break n -= len(data) result.append(data) - return ''.join(data) + return ''.join(result) def readall(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') return self.stream.readall() def readline(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') return self.stream.readline() def readlines(self, sizehint=0): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') return list(iter(self.stream.readline, "")) def write(self, data): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') + if not isinstance(data, str): + raise TypeError('write() argument must be a string (for now)') return self.stream.write(data) def writelines(self, lines): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') for line in lines: + if not isinstance(line, str): + raise TypeError('writelines() argument must be a list ' + 'of strings') self.stream.write(line) def tell(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') return self.stream.tell() def seek(self, offset, whence=0): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') self.stream.seek(offset, whence) def __iter__(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') return self xreadlines = __iter__ def next(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') line = self.stream.readline() if line == '': @@ -211,24 +221,28 @@ return line def truncate(self, size=None): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') if size is None: size = self.stream.tell() self.stream.truncate(size) def flush(self): - if self.closed: + if self._closed: raise ValueError('I/O operation on closed file') self.stream.flush() def close(self): - if not self.closed: - self.closed = True + if not self._closed: + self._closed = True self.stream.close() - def readinto(self, a=None): + __del__ = close + + def readinto(self, a): 'Obsolete method, do not use it.' + if self._closed: + raise ValueError('I/O operation on closed file') from array import array if not isinstance(a, array): raise TypeError('Can only read into array objects') @@ -237,3 +251,13 @@ del a[:] a.fromstring(data + '\x00' * (length-len(data))) return len(data) + + def fileno(self): + if self._closed: + raise ValueError('I/O operation on closed file') + return self.fd + + def isatty(self): + if self._closed: + raise ValueError('I/O operation on closed file') + return os.isatty(self.fd) Modified: pypy/dist/pypy/lib/_sio.py ============================================================================== --- pypy/dist/pypy/lib/_sio.py (original) +++ pypy/dist/pypy/lib/_sio.py Sat Jan 29 12:33:19 2005 @@ -470,6 +470,9 @@ the stack of streams. """ + bigsize = 2**19 # Half a Meg + bufsize = 2**13 # 8 K + def __init__(self, base, bufsize=None): self.base = base self.do_write = base.write # write more data From arigo at codespeak.net Sat Jan 29 13:05:06 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 13:05:06 +0100 (MET) Subject: [pypy-svn] r8699 - pypy/dist/pypy/lib Message-ID: <20050129120506.25F0627B6E@code1.codespeak.net> Author: arigo Date: Sat Jan 29 13:05:05 2005 New Revision: 8699 Modified: pypy/dist/pypy/lib/_file.py Log: added the 'newlines' attribute. Modified: pypy/dist/pypy/lib/_file.py ============================================================================== --- pypy/dist/pypy/lib/_file.py (original) +++ pypy/dist/pypy/lib/_file.py Sat Jan 29 13:05:05 2005 @@ -124,10 +124,11 @@ writing = basemode != 'r' or plus if universal: # Wants universal newlines - if writing: + if writing and os.linesep != '\n': self.stream = _sio.TextOutputFilter(self.stream) if reading: self.stream = _sio.TextInputFilter(self.stream) + self.getnewlines = self.stream.getnewlines if bufsize == 0: # no buffering pass @@ -145,10 +146,13 @@ if reading: self.stream = _sio.BufferingInputStream(self.stream, bufsize) - mode = property(lambda self: self._mode) - name = property(lambda self: self._name) - closed = property(lambda self: self._closed) + def getnewlines(self): + return None # can be overridden in the instance + mode = property(lambda self: self._mode) + name = property(lambda self: self._name) + closed = property(lambda self: self._closed) + newlines = property(lambda self: self.getnewlines()) def read(self, n=-1): if self._closed: From tismer at codespeak.net Sat Jan 29 13:16:08 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 13:16:08 +0100 (MET) Subject: [pypy-svn] r8700 - pypy/dist/pypy/tool Message-ID: <20050129121608.59B8927B95@code1.codespeak.net> Author: tismer Date: Sat Jan 29 13:16:08 2005 New Revision: 8700 Modified: pypy/dist/pypy/tool/sourcetools.py (contents, props changed) Log: fixeol for sourcetools.py Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Sat Jan 29 13:16:08 2005 @@ -1,21 +1,21 @@ -# a couple of support functions which -# help with generating Python source. - -def render_docstr(func, indent_str='', closing_str='', q='"""', redo=True): - """ Render a docstring as a sequence of lines. - The argument is either a docstring or an object""" - if type(func) is not str: - doc = func.__doc__ - else: - doc = func - if doc is None: - return [] - doc = indent_str + q + doc.replace(q, "\\"+q) + q + closing_str - doc2 = doc - if q in doc and redo: - doc2 = render_docstr(func, indent_str, closing_str, "'''", False) - if not redo: - return doc # recursion case - doc = (doc, doc2)[len(doc2) < len(doc)] - return [line for line in doc.split('\n')] - +# a couple of support functions which +# help with generating Python source. + +def render_docstr(func, indent_str='', closing_str='', q='"""', redo=True): + """ Render a docstring as a sequence of lines. + The argument is either a docstring or an object""" + if type(func) is not str: + doc = func.__doc__ + else: + doc = func + if doc is None: + return [] + doc = indent_str + q + doc.replace(q, "\\"+q) + q + closing_str + doc2 = doc + if q in doc and redo: + doc2 = render_docstr(func, indent_str, closing_str, "'''", False) + if not redo: + return doc # recursion case + doc = (doc, doc2)[len(doc2) < len(doc)] + return [line for line in doc.split('\n')] + From arigo at codespeak.net Sat Jan 29 13:22:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 13:22:13 +0100 (MET) Subject: [pypy-svn] r8701 - pypy/dist/pypy/module Message-ID: <20050129122213.47F5127B95@code1.codespeak.net> Author: arigo Date: Sat Jan 29 13:22:13 2005 New Revision: 8701 Modified: pypy/dist/pypy/module/__builtin__module.py Log: - class file_ renamed to class file. - disabled this, because it's still experimental and takes AGES to import. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Sat Jan 29 13:22:13 2005 @@ -947,5 +947,5 @@ yield local_iterable[index] return reversed_gen(seq) -from _file import file_ as file -open = file +#from _file import file +#open = file From hpk at codespeak.net Sat Jan 29 13:30:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 13:30:52 +0100 (MET) Subject: [pypy-svn] r8692 - pypy/funding Message-ID: <20050129123052.2327327B95@code1.codespeak.net> Author: hpk Date: Sat Jan 29 11:37:30 2005 New Revision: 8692 Added: pypy/funding/physical-person-model.txt (contents, props changed) Log: a first draft of the Physical Persons model as we discussed it at previous meetings. Added: pypy/funding/physical-person-model.txt ============================================================================== --- (empty file) +++ pypy/funding/physical-person-model.txt Sat Jan 29 11:37:30 2005 @@ -0,0 +1,162 @@ + +"Physical Persons" in the PyPy EU project +========================================= + +Introduction +------------ + +The PyPy partners strongly emphasized in their proposal +(as accepted by the EU commission) that they want +to openly involve external experts and open source developers +into our agile development process. This particular view of +Open Source development was summarized in the proposal +as follows:: + + B4.6 Resources to be mobilized + (...) + And the third, and most important resource to be mobilised, is + people. This is where this Consortium really shines. Not only + have we already attracted some of the top people in the Python + community in this project, we also have a plan to continue to + attract the interest, support, and constructive criticism of + the very best. The Open Source movement is all about + community. This fact is often overlooked by people who are + discovering Open Source for the first time, who mistakenly + believe that it is all about licensing . Successful Open + Source projects are based on sharing and trust, process rather + than product, and key people. The same is true of Agile + development methods, as defined by the Agile Alliance. + +We also explained up-front that we want to amend the contract +to allow researchers, experts and open source developers to +get a full refund for their travel and accomodation costs in +exchange for receiving their participation, work time and +contributions. We promised this to the various communities and +people we are attached to and we are set to follow up on this. + +Quote from our accepted proposal:: + + B.4.2 Foreseen amendments + + It is intended that some of the experts who participate in + the sprint workshops access the consortium with the status of + physical persons. The exact list of such persons is not and + cannot be known before hand. As they become known, they will + be added to the project consortium trough an amendment to the + contract. In the original contract preparation forms, the + budget for these physical persons was assigned to the + University of Southampton. + +The central role of "sprint workshops" is also obvious from +the start of our "B.5 project management" chapter:: + + Both the project and the development process are based + around critical workshops, so called "sprints" that will take + place on a six week cycle throughout the project (24 months). + Around these sprints input and output to stakeholders will be + structured. + + (...) + + The sprints will be the forum in which knowledge will be + shared and the transparency within the project organisation + will be measured. We will during the project focus on + evaluating and documenting our project method and share + knowledge and experience in that area as well. It is our goal + that the overall deliverables from this project will be a + functioning PyPy as well as an effective project method for + agile development/Open Source projects. Our goal is also to + disseminate this knowledge to the developer communities inside + and outside the Open Source movement as well as to commercial + and academic organisations. + + +It is thus a primary issue for the PyPy partners to implement +the models and measures neccessary to interact and invite +the wide community of experts and interested developers. + +The model of getting physical persons into the consortium +--------------------------------------------------------- + +We want to have a lightweight process ("swinging door principle") +for integrating physical persons into the EU project. The technical +board is to actively invite people and partners to join our +sprints and other developments. The board will select people +according to criterias like usefulness for the project, +past contributions and specific fields of knowledge. + +However, on the formal side there are still some details to +resolve and we ask everyone, including our EU project officer +and the national EU offices we have contacts to, to help us in +setting up a model that can then be reused by other open +and transparent projects as well. + +Here are some of the issues and our proposed solutions: + +- physical persons enter the EU contract by means of + an Accession form. They are to get reimbursement for their + travel and accomodation costs but not for their work + costs. (See 2.4.7 of the Financial Guidelines from 04/2004). + We do not think that we will have phyiscal persons with + full accounting systems and thus expect them to use + the AC model (in a very simple way). + +- Regarding cost reimbursement we would like to reimburse + costs to the acceeded physical persons attending sprints + while they are on the sprint venue. They should usually + receive the money after we received copies of their + receipts for travel/accomodation costs. The EU commission + only prepays 80% of the full funding amount, yet we may + like to reimburse 100% of their costs directly to minimize + later distribution work. + +- physical persons also sign an amendment to our Consortium + contract. Here we need to specialize their membership + internally in order to allow the consortium to continue + to act efficiently. In other words, we cannot make the + physical persons full members of the consortium because + it would make meetings and decisions ever more difficult. + + Therefore, physical persons are to enter as "associated + partners" which waive their voting rights and are not + required to attend consortium meetings. we consider this + mostly an internal details of the consortium than something + the EU commission has to care about. + +- We want physical persons to _not_ participate in the + general common liability of the full consortium partners + towards the EU commission. We feel that it is unwarranted + to receive work and contribution "for free" from sprint + participants and then make them liable if the consortium + cannot deliver as promised to the EU. + +- sprint participants/physical persons should at best + also not be required to deliver audit certificates. + If this is not feasible then we need to find an auditor who + is willing to audit the cost statements of the physical + persons in a way that does not affect the management budget. + (The costs for audit certificates are accounted to the + management budget). If audit certificates even for one or + two-time attenders of sprints then we kindly ask the EU + commission for special allowance to not count the according + costs to the "7% management Cap" rule. + + +Time frame +---------- + +We would like to setup the full model and process for +getting physical persons into the EU project by mid +February 2005. We have a number of people already interested +and many of them are already explicitely mentioned in +the proposal (B.4.2.1.4 and B.4.2.2.1). + +Feedback +-------- + +Please direct any feedback to pypy-funding at codespeak.net or to +Laura Creighton and Holger Krekel + who have been tasked by the partners +to find a workable and efficient model for sprint participants +to enter the project as physical persons. + From hpk at codespeak.net Sat Jan 29 13:31:11 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 13:31:11 +0100 (MET) Subject: [pypy-svn] r8693 - pypy/funding Message-ID: <20050129123111.6D23427B95@code1.codespeak.net> Author: hpk Date: Sat Jan 29 12:01:33 2005 New Revision: 8693 Modified: pypy/funding/physical-person-model.txt Log: some fixes and better phrasing. Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Sat Jan 29 12:01:33 2005 @@ -1,4 +1,3 @@ - "Physical Persons" in the PyPy EU project ========================================= @@ -70,10 +69,10 @@ and outside the Open Source movement as well as to commercial and academic organisations. - It is thus a primary issue for the PyPy partners to implement -the models and measures neccessary to interact and invite -the wide community of experts and interested developers. +models and measures neccessary to interact and invite +the wide community of interested researchers, experts and +interested developers. The model of getting physical persons into the consortium --------------------------------------------------------- @@ -101,46 +100,52 @@ full accounting systems and thus expect them to use the AC model (in a very simple way). -- Regarding cost reimbursement we would like to reimburse - costs to the acceeded physical persons attending sprints - while they are on the sprint venue. They should usually +- We would like to reimburse costs to the external + sprint participants (as physical persons) while they + are on the sprint venue. They should usually receive the money after we received copies of their - receipts for travel/accomodation costs. The EU commission - only prepays 80% of the full funding amount, yet we may - like to reimburse 100% of their costs directly to minimize - later distribution work. + receipts for travel/accomodation costs. Although the + EU commission prepays only 80% of the full funding amount, + we may want to reimburse 100% of their costs at once to + distribution work. -- physical persons also sign an amendment to our Consortium +- Physical persons are to sign an amendment to our Consortium contract. Here we need to specialize their membership - internally in order to allow the consortium to continue - to act efficiently. In other words, we cannot make the - physical persons full members of the consortium because - it would make meetings and decisions ever more difficult. + internally in order to allow the consortium of full parnters + to continue to act efficiently. We cannot make sprint + participants (physical persons) full members of the consortium + because it would make meetings and decisions ever more difficult. Therefore, physical persons are to enter as "associated partners" which waive their voting rights and are not - required to attend consortium meetings. we consider this - mostly an internal details of the consortium than something - the EU commission has to care about. - -- We want physical persons to _not_ participate in the + required to attend consortium meetings. We consider this + mostly an internal detail of the consortium than something + the EU commission has to care about. + + Also we want physical persons to _not_ participate in the general common liability of the full consortium partners towards the EU commission. We feel that it is unwarranted to receive work and contribution "for free" from sprint - participants and then make them liable if the consortium - cannot deliver as promised to the EU. + participants and then make them liable if the full partners + cannot deliver as promised to the EU. -- sprint participants/physical persons should at best - also not be required to deliver audit certificates. +- sprint participants (formally physical persons) should + not be required to deliver audit certificates. If this is not feasible then we need to find an auditor who - is willing to audit the cost statements of the physical + is willing to audit the very simple cost statements of the physical persons in a way that does not affect the management budget. (The costs for audit certificates are accounted to the - management budget). If audit certificates even for one or - two-time attenders of sprints then we kindly ask the EU - commission for special allowance to not count the according - costs to the "7% management Cap" rule. - + management budget as far as we know). If audit certificates + are neccessary even for one or two-time attenders of sprints + then we kindly ask the EU commission for special allowance to + not count the according costs to the "7% management Cap" rule. + +Please note that the costs for sprint participants (physical +persons) will only affect a very small portion of the overall +budget. Also we are - as explicitely stated in the proposal - +pioneering agile development/sprinting methods within +an EU project we hope that the commission will help us +to design the process in the proposed lightweight manner. Time frame ---------- @@ -149,7 +154,8 @@ getting physical persons into the EU project by mid February 2005. We have a number of people already interested and many of them are already explicitely mentioned in -the proposal (B.4.2.1.4 and B.4.2.2.1). +the proposal (B.4.2.1.4 and B.4.2.2.1 in the last amended +version of December 2004). Feedback -------- From bea at codespeak.net Sat Jan 29 13:31:20 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 13:31:20 +0100 (MET) Subject: [pypy-svn] r8696 - pypy/funding Message-ID: <20050129123120.38AE527B95@code1.codespeak.net> Author: bea Date: Sat Jan 29 12:39:33 2005 New Revision: 8696 Modified: pypy/funding/physical-person-model.txt Log: corrected some spelling stuff (bea) Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Sat Jan 29 12:39:33 2005 @@ -96,7 +96,7 @@ an Accession form. They are to get reimbursement for their travel and accomodation costs but not for their work costs. (See 2.4.7 of the Financial Guidelines from 04/2004). - We do not think that we will have phyiscal persons with + We do not think that we will have physical persons with full accounting systems and thus expect them to use the AC model (in a very simple way). @@ -111,7 +111,7 @@ - Physical persons are to sign an amendment to our Consortium contract. Here we need to specialize their membership - internally in order to allow the consortium of full parnters + internally in order to allow the consortium of full partners to continue to act efficiently. We cannot make sprint participants (physical persons) full members of the consortium because it would make meetings and decisions ever more difficult. From lac at codespeak.net Sat Jan 29 13:31:28 2005 From: lac at codespeak.net (lac at codespeak.net) Date: Sat, 29 Jan 2005 13:31:28 +0100 (MET) Subject: [pypy-svn] r8697 - pypy/funding Message-ID: <20050129123128.2E8F127B96@code1.codespeak.net> Author: lac Date: Sat Jan 29 12:43:23 2005 New Revision: 8697 Modified: pypy/funding/physical-person-model.txt Log: fix tiny error in sentence structure Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Sat Jan 29 12:43:23 2005 @@ -107,7 +107,7 @@ receipts for travel/accomodation costs. Although the EU commission prepays only 80% of the full funding amount, we may want to reimburse 100% of their costs at once to - distribution work. + simplify administration. - Physical persons are to sign an amendment to our Consortium contract. Here we need to specialize their membership From bea at codespeak.net Sat Jan 29 13:39:31 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 13:39:31 +0100 (MET) Subject: [pypy-svn] r8702 - pypy/funding Message-ID: <20050129123931.0CE3C27B7D@code1.codespeak.net> Author: bea Date: Sat Jan 29 13:39:30 2005 New Revision: 8702 Added: pypy/funding/justificationpycon_pypyproject_050128.sxw (contents, props changed) Log: utkast f?r dfki check med PO m?ndag 31/1 2005, inv?nta logilab feedback Added: pypy/funding/justificationpycon_pypyproject_050128.sxw ============================================================================== Binary file. No diff available. From bea at codespeak.net Sat Jan 29 13:41:12 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 13:41:12 +0100 (MET) Subject: [pypy-svn] r8703 - pypy/funding Message-ID: <20050129124112.CD82227B7D@code1.codespeak.net> Author: bea Date: Sat Jan 29 13:41:12 2005 New Revision: 8703 Modified: pypy/funding/justificationpycon_pypyproject_050128.sxw Log: ?ndring dfki + summa Modified: pypy/funding/justificationpycon_pypyproject_050128.sxw ============================================================================== Binary files. No diff available. From bea at codespeak.net Sat Jan 29 13:44:56 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 13:44:56 +0100 (MET) Subject: [pypy-svn] r8704 - pypy/funding Message-ID: <20050129124456.96A1327B7D@code1.codespeak.net> Author: bea Date: Sat Jan 29 13:44:56 2005 New Revision: 8704 Added: pypy/funding/justificationpycon_pypyproject_050128.txt Log: created txt version of the justification file Added: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- (empty file) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 13:44:56 2005 @@ -0,0 +1,33 @@ +Cost estimation and justification for sprint work at Pycon, Washington D.C, PyPy project + +Background: +In the proposal we explicitly mention Pycon as one of the key conferences to participate in for the PyPy project. The conference is being held at the George Washington University in Washington D.C 23-25 March 2005. Before the conference, between 19 and 22 March 2005 there is as community sprint planned. Last year there where 5 different projects sprinting. This year there will be 9 different sprints before the conference, PyPy is one of them. + +It is the intention of the PyPy team to participate and host a sprint focused on the PyPy work. Main goals are to disseminate knowledge about the technical content of PyPy as well as get active contribution from developers in the community on PyPy work that is the focus for phase 1 of the project. There will also be talks (by Holger Krekel and Armin Rigo, PyPy team) during the actual conference. + +For these reasons we need a full team presence to able to handle what we expect will be a large follow up of interested and contributing developers from the Python community. + +Justifications: +Pycon is the yearly Python conference, our presence there as a project is expected +The planned work of phase 1 will allow us to, during the sprint, to run PyPy Cpython tests, these kind of tasks are fairly easy to involve other than core developers on +The focus of testing and using testing tasks as a way of getting contribution is also a very important way of validating the work of the PyPy team as well as disseminating the work +There will be focus on the Microsoft goal of ?Python on the .NET platform? during the conference. This proprietary aspiration and interest of Python need a nonproprietary counterpart and PyPy is expected to be the next generation of Python in the community. + +Participants: +The following partners and individuals will attend the Pycon sprint and the conference: + + Sprint 4 days + conference 3 days + +Logilab 2? +DFKI Developer X +Strakt Jacob Hall?n + Samuele Pedroni + Anders Chrigstr?m +Change Maker Beatrice D?ring +Heinrich Heine University D?sseldorf Armin Rigo +Merlinux Holger Krekel +Tismerysoft Christian Tismer + +Cost estimation: +Estimated sprintcost (flight, accomodation, cost of conference): +1300 euro x 10 people= 13 000 euro \ No newline at end of file From arigo at codespeak.net Sat Jan 29 13:48:18 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 13:48:18 +0100 (MET) Subject: [pypy-svn] r8705 - pypy/dist/pypy/lib Message-ID: <20050129124818.B192E27B7D@code1.codespeak.net> Author: arigo Date: Sat Jan 29 13:48:18 2005 New Revision: 8705 Modified: pypy/dist/pypy/lib/_sio.py Log: bug fix. Modified: pypy/dist/pypy/lib/_sio.py ============================================================================== --- pypy/dist/pypy/lib/_sio.py (original) +++ pypy/dist/pypy/lib/_sio.py Sat Jan 29 13:48:18 2005 @@ -198,12 +198,11 @@ hit = self.mm.find("\n", self.pos) + 1 if not hit: # is there more data to read? - filesize = self.mm.size() # Actual file size, may be more than mapped - if filesize <= len(self.mm): - return "" - # File grew since opened; remap to get the new data - self.remapfile() - hit = self.mm.find("\n", self.pos) + 1 + filesize = self.mm.size() #Actual file size, may be more than mapped + if filesize > len(self.mm): + # File grew since opened; remap to get the new data + self.remapfile() + hit = self.mm.find("\n", self.pos) + 1 if hit: # Got a whole line data = self.mm[self.pos:hit] From bea at codespeak.net Sat Jan 29 14:06:59 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 14:06:59 +0100 (MET) Subject: [pypy-svn] r8706 - pypy/funding Message-ID: <20050129130659.2DD3727B84@code1.codespeak.net> Author: bea Date: Sat Jan 29 14:06:59 2005 New Revision: 8706 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: extracts from proposal put in..... Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 14:06:59 2005 @@ -1,7 +1,27 @@ Cost estimation and justification for sprint work at Pycon, Washington D.C, PyPy project Background: -In the proposal we explicitly mention Pycon as one of the key conferences to participate in for the PyPy project. The conference is being held at the George Washington University in Washington D.C 23-25 March 2005. Before the conference, between 19 and 22 March 2005 there is as community sprint planned. Last year there where 5 different projects sprinting. This year there will be 9 different sprints before the conference, PyPy is one of them. +In the proposal we explicitly mention Pycon as one of the key conferences to participate +in for the PyPy project. The conference is being held at the George Washington University +in Washington D.C 23-25 March 2005. Before the conference, between 19 and 22 March 2005 +there is as community sprint planned. Last year there where 5 different projects sprinting. +This year there will be 9 different sprints before the conference, PyPy is one of them. + +Extract from the proposal, B.3.4 Dissemination: +"We will also partake in the following official events, forum, conferences to spread +information about the ongoing project, its unique process and technological impact and +thus reaching out to software developers within the Python community as well as practitioners +of other software languages: +EuroPython/EuroZope (European Python Conference), ACM/IFIP/USENIX International Middleware Conference, +OSCON (Open Source Convention), OOPSLA (Object-Oriented programming, systems, languages and applications) +PyCon (Python Developers conference), FOSDEM (Free and Open Source Developer European Meeting), ECOOP (European Conference for Object Oriented Programming) +More conferences will be added once the project gets started." + +Also - see proposal B.5.5 Communication and reporting: +"We will present multiple reports and scientific papers on major conferences such as EuroPython +(Python's European community conference), FOSDEM (Free and Open Source Developer European Meeting), +OSCON (Open Source Convention), PyCon (Python developer conference) and to +domain specific audiences such as embedded device developers." It is the intention of the PyPy team to participate and host a sprint focused on the PyPy work. Main goals are to disseminate knowledge about the technical content of PyPy as well as get active contribution from developers in the community on PyPy work that is the focus for phase 1 of the project. There will also be talks (by Holger Krekel and Armin Rigo, PyPy team) during the actual conference. @@ -28,6 +48,3 @@ Merlinux Holger Krekel Tismerysoft Christian Tismer -Cost estimation: -Estimated sprintcost (flight, accomodation, cost of conference): -1300 euro x 10 people= 13 000 euro \ No newline at end of file From ac at codespeak.net Sat Jan 29 14:12:42 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 14:12:42 +0100 (MET) Subject: [pypy-svn] r8707 - in pypy/dist/pypy: interpreter module Message-ID: <20050129131242.E34CC27B62@code1.codespeak.net> Author: ac Date: Sat Jan 29 14:12:42 2005 New Revision: 8707 Modified: pypy/dist/pypy/interpreter/pyframe.py pypy/dist/pypy/interpreter/pyopcode.py pypy/dist/pypy/module/__builtin__interp.py Log: Properly inherit effects of future statements into eval(), exec and compile(). Modified: pypy/dist/pypy/interpreter/pyframe.py ============================================================================== --- pypy/dist/pypy/interpreter/pyframe.py (original) +++ pypy/dist/pypy/interpreter/pyframe.py Sat Jan 29 14:12:42 2005 @@ -6,6 +6,11 @@ from pypy.interpreter.error import OperationError from pypy.interpreter import pytraceback +import __future__ +compiler_flags = 0 +for fname in __future__.all_feature_names: + compiler_flags |= getattr(__future__, fname).compiler_flag + class PyFrame(eval.Frame): """Represents a frame for a regular Python function @@ -50,6 +55,9 @@ def getclosure(self): return None + def get_compile_flags(self): + return self.code.co_flags & compiler_flags + def eval(self, executioncontext): "Interpreter main loop!" try: Modified: pypy/dist/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/dist/pypy/interpreter/pyopcode.py (original) +++ pypy/dist/pypy/interpreter/pyopcode.py Sat Jan 29 14:12:42 2005 @@ -344,7 +344,9 @@ w_locals = f.valuestack.pop() w_globals = f.valuestack.pop() w_prog = f.valuestack.pop() - w_resulttuple = f.prepare_exec(w_prog, w_globals, w_locals) + w_compile_flags = f.space.wrap(f.get_compile_flags()) + w_resulttuple = f.prepare_exec(w_prog, w_globals, w_locals, + w_compile_flags) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) @@ -355,7 +357,7 @@ if plain: f.setdictscope(w_locals) - def app_prepare_exec(f, prog, globals, locals): + def app_prepare_exec(f, prog, globals, locals, compile_flags): """Manipulate parameters to exec statement to (codeobject, dict, dict). """ # XXX INCOMPLETE @@ -387,14 +389,10 @@ ## isinstance(prog, types.FileType)): raise TypeError("exec: arg 1 must be a string, file, or code object") ## if isinstance(prog, types.FileType): - ## flags = 0 - ## ## XXX add in parent flag merging - ## co = compile(prog.read(),prog.name,'exec',flags,1) + ## co = compile(prog.read(),prog.name,'exec',comple_flags,1) ## return (co,globals,locals) else: # prog is a string - flags = 0 - ## XXX add in parent flag merging - co = compile(prog,'','exec',flags,1) + co = compile(prog,'','exec', compile_flags, 1) return (co, globals, locals) def POP_BLOCK(f): Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Sat Jan 29 14:12:42 2005 @@ -196,14 +196,21 @@ w_exc = space.call_function(space.w_ImportError, w_failing) raise OperationError(space.w_ImportError, w_exc) - def compile(str_, filename, startstr, supplied_flags=0, dont_inherit=0): #print (str_, filename, startstr, supplied_flags, dont_inherit) # XXX we additionally allow GENERATORS because compiling some builtins # requires it. doesn't feel quite right to do that here. + supplied_flags |= 4096 + if not dont_inherit: + try: + frame = _actframe() + except IndexError: + pass + else: + supplied_flags |= frame.get_compile_flags() try: - c = cpy_builtin.compile(str_, filename, startstr, supplied_flags|4096, dont_inherit) + c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1) # It would be nice to propagate all exceptions to app level, # but here we only propagate the 'usual' ones, until we figure # out how to do it generically. From pedronis at codespeak.net Sat Jan 29 14:17:30 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 29 Jan 2005 14:17:30 +0100 (MET) Subject: [pypy-svn] r8708 - pypy/dist/pypy/lib Message-ID: <20050129131730.E617C27B62@code1.codespeak.net> Author: pedronis Date: Sat Jan 29 14:17:30 2005 New Revision: 8708 Added: pypy/dist/pypy/lib/_classobj.py Log: start of impl of old-style classes at app level, not tested nor integrated Added: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/_classobj.py Sat Jan 29 14:17:30 2005 @@ -0,0 +1,170 @@ +import sys + +obj_setattr = object.__setattr__ +obj_getattribute = object.__getattribute__ + +MASK = sys.maxint * 2 + 2 + +def uid(o): + return (MASK + id(o)) & (MASK-1) + +def type_err(arg, expected, v): + raise TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__)) + +def set_name(cls, name): + if not isinstance(name, str): + raise TypeError, "__name__ must be a string object" + obj_setattr(cls, '__name__', name) + +def set_bases(cls, bases): + if not isinstance(bases, tuple): + raise TypeError, "__bases__ must be a tuple object" + for b in bases: + if not isinstance(b, classobj): + raise TypeError, "__bases__ items must be classes" + obj_setattr(cls, '__bases__', bases) + +def set_dict(cls, dic): + if not isinstance(dic, dict): + raise TypeError, "__dict__ must be a dictionary object" + # preserved __name__ and __bases__ + dic['__name__'] = cls.__name__ + dic['__bases__'] = cls.__bases__ + obj_setattr(cls, '__dict__', dic) + +def retrieve(cls, attr): + dic = obj_getattribute(cls, '__dict__') + try: + return dic[attr] + except KeyError: + raise AttributeError, attr + +def lookup(cls, attr): + # returns (value, class it was found in) + try: + v = retrieve(cls, attr) + return v, cls + except AttributError: + for b in obj_getattribute(cls, '__bases__'): + v, found = lookup(b, attr) + if found: + return v, found + return None, None + +def mro_lookup(v, name): + try: + mro = type(v).__mro__ + except AttributeError: + return None + for x in mro: + if name in x.__dict__: + return x.__dict__[name] + return None + + +class classobj(object): + + def __new__(subtype, name, bases, dic): + if not isinstance(name, str): + type_err('name', 'string', name) + if not isinstance(dic, dict): + type_err('dict', 'dict', dic) + + try: + dic['__doc__'] + except KeyError: + dic['__doc__'] = None + + try: + dic['__module__'] + except: + try: + g = sys._getframe(1).f_globals + except ValueError: + pass + else: + modname = g.get('__name__', None) + if modname is not None: + dic['__module__'] = modname + + if not isinstance(bases, tuple): + type_err('bases', 'tuple', bases) + + if bases is None: + bases = () + + for b in bases: + if not isinstance(b, classobj): + if callable(type(b)): + return type(b)(name, bases, dic) + raise TypeError,"base must be class" + + + new_class = object.__new__(classobj) + + obj_setattr(new_class, '__dict__', dic) + obj_setattr(new_class, '__name__', name) + obj_setattr(new_class, '__bases__', bases) + + return new_class + + def __setattr__(self, attr, value): + if attr == '__name__': + set_name(self, value) + elif attr == '__bases__': + set_bases(self, value) + elif attr == '__dict__': + set_dict(self, value) + else: + obj_setattr(self, attr, value) + + def __delattr__(self, attr): + if attr in ('__name__', '__bases__', '__dict__'): + classobj.__setattr__(self, attr, None) + else: + object.__delattr__(self, attr) + + + def __getattribute__(self, attr): + if attr == '__dict__': + return obj_getattribute(self, '__dict__') + v, found = lookup(self, attr) + if not found: + raise AttributeError, "class %s has no attribute %s" % (self.__name__, attr) + if attr in ('__name__', '__bases__', '__dict__'): + return v + + descr_get = mro_lookup(v, '__get__') + if descr_get is None: + return v + return descr_get(v, None, self) + + def __repr__(self): + try: + mod = retrieve(self, '__module__') + if not isinstance(mod, str): + mod = None + except AttributeError: + mod = None + if mod is None: + return "" % (self.__name__, uid(self)) + else: + return "" % (mod, self.__name__, uid(self)) + + def __str__(self): + try: + mod = retrieve(self, '__module__') + if not isinstance(mod, str): + mod = None + except AttributeError: + mod = None + if mod is None: + return self.__name__ + else: + return "%s.%s" % (mod, self.__name__) + + +class instance(object): + pass + + From arigo at codespeak.net Sat Jan 29 14:19:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 14:19:09 +0100 (MET) Subject: [pypy-svn] r8709 - pypy/dist/pypy/lib Message-ID: <20050129131909.88FEE27B62@code1.codespeak.net> Author: arigo Date: Sat Jan 29 14:19:09 2005 New Revision: 8709 Modified: pypy/dist/pypy/lib/_sio.py Log: bug fix. Modified: pypy/dist/pypy/lib/_sio.py ============================================================================== --- pypy/dist/pypy/lib/_sio.py (original) +++ pypy/dist/pypy/lib/_sio.py Sat Jan 29 14:19:09 2005 @@ -597,8 +597,8 @@ assert not self.atcr data = self.buf self.buf = "" - return data - data = self.do_read(n) + else: + data = self.do_read(n) # The following whole ugly mess is because we need to keep track of # exactly which line separators we have seen for self.newlines, From hpk at codespeak.net Sat Jan 29 14:21:00 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 14:21:00 +0100 (MET) Subject: [pypy-svn] r8710 - pypy/funding Message-ID: <20050129132100.A790D27B62@code1.codespeak.net> Author: hpk Date: Sat Jan 29 14:21:00 2005 New Revision: 8710 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt (contents, props changed) Log: improvements to the document (introduction) and formatting changes. Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 14:21:00 2005 @@ -1,50 +1,104 @@ -Cost estimation and justification for sprint work at Pycon, Washington D.C, PyPy project - -Background: -In the proposal we explicitly mention Pycon as one of the key conferences to participate -in for the PyPy project. The conference is being held at the George Washington University -in Washington D.C 23-25 March 2005. Before the conference, between 19 and 22 March 2005 -there is as community sprint planned. Last year there where 5 different projects sprinting. -This year there will be 9 different sprints before the conference, PyPy is one of them. - -Extract from the proposal, B.3.4 Dissemination: -"We will also partake in the following official events, forum, conferences to spread -information about the ongoing project, its unique process and technological impact and -thus reaching out to software developers within the Python community as well as practitioners -of other software languages: -EuroPython/EuroZope (European Python Conference), ACM/IFIP/USENIX International Middleware Conference, -OSCON (Open Source Convention), OOPSLA (Object-Oriented programming, systems, languages and applications) -PyCon (Python Developers conference), FOSDEM (Free and Open Source Developer European Meeting), ECOOP (European Conference for Object Oriented Programming) -More conferences will be added once the project gets started." - -Also - see proposal B.5.5 Communication and reporting: -"We will present multiple reports and scientific papers on major conferences such as EuroPython -(Python's European community conference), FOSDEM (Free and Open Source Developer European Meeting), -OSCON (Open Source Convention), PyCon (Python developer conference) and to -domain specific audiences such as embedded device developers." - -It is the intention of the PyPy team to participate and host a sprint focused on the PyPy work. Main goals are to disseminate knowledge about the technical content of PyPy as well as get active contribution from developers in the community on PyPy work that is the focus for phase 1 of the project. There will also be talks (by Holger Krekel and Armin Rigo, PyPy team) during the actual conference. - -For these reasons we need a full team presence to able to handle what we expect will be a large follow up of interested and contributing developers from the Python community. - -Justifications: -Pycon is the yearly Python conference, our presence there as a project is expected -The planned work of phase 1 will allow us to, during the sprint, to run PyPy Cpython tests, these kind of tasks are fairly easy to involve other than core developers on -The focus of testing and using testing tasks as a way of getting contribution is also a very important way of validating the work of the PyPy team as well as disseminating the work -There will be focus on the Microsoft goal of ?Python on the .NET platform? during the conference. This proprietary aspiration and interest of Python need a nonproprietary counterpart and PyPy is expected to be the next generation of Python in the community. - -Participants: -The following partners and individuals will attend the Pycon sprint and the conference: - - Sprint 4 days + conference 3 days - -Logilab 2? -DFKI Developer X -Strakt Jacob Hall?n - Samuele Pedroni - Anders Chrigstr?m -Change Maker Beatrice D?ring -Heinrich Heine University D?sseldorf Armin Rigo -Merlinux Holger Krekel -Tismerysoft Christian Tismer - +Sprinting at the Pycon conference +================================= + +Justification for sprint work at Pycon, Washington D.C, PyPy project + +Background +---------- + +In the proposal we explicitly mention Pycon as one of the key +conferences to participate in for the PyPy project. We have +a need to clarify with the EU commission if we have to be aware +of problems regarding reimbursment of costs for travelling and +working in countries other than in the EU. Specifically, we +would like to check if our next planned sprint at Pycon, Washington, +imposes any problems with reimbursement. + +The Pycon conference is being held at the George Washington University +in Washington D.C 23-25 March 2005. Before the conference, +between 19 and 22 March 2005 there are community sprints +planned. Last year there where 5 different projects sprinting. +This year there will be 9 different sprints before the +conference, PyPy is to be one of them. + +Sprinting is a key work and dissemination method of the PyPy project, +as noted in the proposal at B.3.4 Dissemniation:: + + We will also partake in the following official events, forum, + conferences to spread information about the ongoing project, + its unique process and technological impact and thus reaching + out to software developers within the Python community as well + as practitioners of other software languages: + EuroPython/EuroZope (European Python Conference), + ACM/IFIP/USENIX International Middleware Conference, OSCON + (Open Source Convention), OOPSLA (Object-Oriented programming, + systems, languages and applications) PyCon (Python Developers + conference), FOSDEM (Free and Open Source Developer European + Meeting), ECOOP (European Conference for Object Oriented + Programming) More conferences will be added once the project + gets started. + +Also - please see the proposal B.5.5 Communication and reporting:: + + We will present multiple reports and scientific papers on + major conferences such as EuroPython (Python's European + community conference), FOSDEM (Free and Open Source Developer + European Meeting), OSCON (Open Source Convention), PyCon + (Python developer conference) and to domain specific audiences + such as embedded device developers. + +It is the intention of the PyPy team to participate and host a +sprint focused on the PyPy work. Main goals are to disseminate +knowledge about the technical content of PyPy as well as get +active contribution from developers in the community on PyPy +work that is the focus for phase 1 of the project. There will +also be talks (by Holger Krekel and Armin Rigo, PyPy team) +during the actual conference. + +We want to have our full team presence to able to handle what +we expect will be a large follow up of interested and +contributing developers and researchers from the Python community. + +Justification +------------- + +Pycon is the yearly Python conference, our presence there as a +project is expected The planned work of phase 1 will allow us +to, during the sprint, to run PyPy Cpython tests, these kind +of tasks are fairly easy to involve other than core developers +on The focus of testing and using testing tasks as a way of +getting contribution is also a very important way of +validating the work of the PyPy team as well as disseminating +the work + +Please note that there will be a focus on the Microsoft goal of +"Python on the .NET platform" during the conference. This +proprietary aspiration and interest of Python need a +nonproprietary counterpart and PyPy is expected to be the next +generation of Python in the community. We should be present +there as much as possible. + +Participants +------------ + +The following partners and individuals are scheduled to attend +the Pycon sprint and the conference: + +Sprint 4 days + conference 3 days + +Logilab 2 (unconfirmed) +DFKI Developer X +Strakt Jacob Hallen, Samuele Pedroni, Anders Chrigstroem +Change Maker Beatrice D?ring +HHU Duesseldorf Armin Rigo +merlinux Holger Krekel +Tismerysoft Christian Tismer + + +Time frame +---------- + +We would like to get feedback on these plans from the commission +as quick as possible as the conference is going to take place +in Mid-March already and we need to book flights and accomodation +accordingly. From ac at codespeak.net Sat Jan 29 14:32:39 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 14:32:39 +0100 (MET) Subject: [pypy-svn] r8712 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129133239.852A627B5B@code1.codespeak.net> Author: ac Date: Sat Jan 29 14:32:39 2005 New Revision: 8712 Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Log: Make our TestCase look more like unittest.TestCase Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/pypy_unittest.py (original) +++ pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Sat Jan 29 14:32:39 2005 @@ -11,17 +11,54 @@ assert x == y, msg else: assert x == y + def assertNotEqual(self, x, y, msg=None): if msg: assert x != y, msg else: assert x != y + def failIfEqual(self, x, y, msg=None): + if msg: + assert not x == y, msg + else: + assert not x == y + + def failUnless(self, expr, msg=None): + if msg is None: + assert expr + else: + assert expr, msg + + def failIf(self, expr, msg=None): + if msg is None: + assert not expr + else: + assert not expr, msg + + def fail(self, msg): + assert False, msg + def assertRaises(self, exc, call, *args, **kwargs): raises(exc, call, *args, **kwargs) + def assertAlmostEqual(self, x, y, places07, msg=None): + if msg is None: + msg = '%r != %r within %r places' %(x, y, places) + assert round(y-x, places) == 0, msg + + def assertNotAlmostEqual(self, x, y, places07, msg=None): + if msg is None: + msg = '%r == %r within %r places' %(x, y, places) + assert round(y-x, places) != 0, msg + assertEquals = assertEqual assertNotEquals = assertNotEqual + failUnlessRaises = assertRaises + failUnlessEqual = assertEqual + failIfAlmostEqual = assertNotAlmostEqual + failUnlessAlmostEqual = assertAlmostEqual + def assert_(self, expr, msg=None): if msg: assert expr, msg From tismer at codespeak.net Sat Jan 29 14:34:08 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 14:34:08 +0100 (MET) Subject: [pypy-svn] r8713 - pypy/dist/pypy/lib Message-ID: <20050129133408.5907827B5B@code1.codespeak.net> Author: tismer Date: Sat Jan 29 14:34:08 2005 New Revision: 8713 Modified: pypy/dist/pypy/lib/_classobj.py Log: first small adjustments Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Sat Jan 29 14:34:08 2005 @@ -44,7 +44,7 @@ try: v = retrieve(cls, attr) return v, cls - except AttributError: + except AttributeError: for b in obj_getattribute(cls, '__bases__'): v, found = lookup(b, attr) if found: @@ -67,6 +67,13 @@ def __new__(subtype, name, bases, dic): if not isinstance(name, str): type_err('name', 'string', name) + + if bases is None: + bases = () + + if not isinstance(bases, tuple): + type_err('bases', 'tuple', bases) + if not isinstance(dic, dict): type_err('dict', 'dict', dic) @@ -77,7 +84,7 @@ try: dic['__module__'] - except: + except KeyError: try: g = sys._getframe(1).f_globals except ValueError: @@ -87,12 +94,6 @@ if modname is not None: dic['__module__'] = modname - if not isinstance(bases, tuple): - type_err('bases', 'tuple', bases) - - if bases is None: - bases = () - for b in bases: if not isinstance(b, classobj): if callable(type(b)): @@ -131,7 +132,7 @@ v, found = lookup(self, attr) if not found: raise AttributeError, "class %s has no attribute %s" % (self.__name__, attr) - if attr in ('__name__', '__bases__', '__dict__'): + if attr in ('__name__', '__bases__'): return v descr_get = mro_lookup(v, '__get__') From arigo at codespeak.net Sat Jan 29 14:40:24 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 14:40:24 +0100 (MET) Subject: [pypy-svn] r8714 - pypy/dist/pypy/lib Message-ID: <20050129134024.9599527B5B@code1.codespeak.net> Author: arigo Date: Sat Jan 29 14:40:24 2005 New Revision: 8714 Modified: pypy/dist/pypy/lib/_file.py pypy/dist/pypy/lib/_sio.py Log: Swapped Buffering*Streams and universal newlines' Text*Filter instances in the stack of streams, to have meaningful tell()/seek(). Added the peek() method to look in the readahead buffer. This enables TextInputFilter.readline() to be efficient. Modified: pypy/dist/pypy/lib/_file.py ============================================================================== --- pypy/dist/pypy/lib/_file.py (original) +++ pypy/dist/pypy/lib/_file.py Sat Jan 29 14:40:24 2005 @@ -123,13 +123,6 @@ reading = basemode == 'r' or plus writing = basemode != 'r' or plus - if universal: # Wants universal newlines - if writing and os.linesep != '\n': - self.stream = _sio.TextOutputFilter(self.stream) - if reading: - self.stream = _sio.TextInputFilter(self.stream) - self.getnewlines = self.stream.getnewlines - if bufsize == 0: # no buffering pass elif bufsize == 1: # line-buffering @@ -146,6 +139,13 @@ if reading: self.stream = _sio.BufferingInputStream(self.stream, bufsize) + if universal: # Wants universal newlines + if writing and os.linesep != '\n': + self.stream = _sio.TextOutputFilter(self.stream) + if reading: + self.stream = _sio.TextInputFilter(self.stream) + self.getnewlines = self.stream.getnewlines + def getnewlines(self): return None # can be overridden in the instance Modified: pypy/dist/pypy/lib/_sio.py ============================================================================== --- pypy/dist/pypy/lib/_sio.py (original) +++ pypy/dist/pypy/lib/_sio.py Sat Jan 29 14:40:24 2005 @@ -4,7 +4,7 @@ - This module contains various stream classes which provide a subset of the classic Python I/O API: read(n), write(s), tell(), seek(offset, whence=0), - readall(), readline(), truncate(size), flush(), close(). + readall(), readline(), truncate(size), flush(), close(), peek(). - This is not for general usage: * read(n) may return less than n bytes, just like os.read(). @@ -12,6 +12,7 @@ * close() should be called exactly once and no further operations performed; there is no __del__() closing the stream for you. * some methods may raise NotImplementedError. + * peek() returns some (or no) characters that have already been read ahead. - A 'basis stream' provides I/O using a low-level API, like the os, mmap or socket modules. @@ -61,14 +62,20 @@ return ''.join(result) def readline(self): - # very inefficient + # very inefficient unless there is a peek() result = [] - c = self.read(1) - while c: + while True: + # "peeks" on the underlying stream to see how many characters + # we can safely read without reading past an end-of-line + peeked = self.peek() + pn = peeked.find("\n") + if pn < 0: pn = len(peeked) + c = self.read(pn + 1) + if not c: + break result.append(c) - if c == '\n': + if c.endswith('\n'): break - c = self.read(1) return ''.join(result) def truncate(self, size): @@ -80,6 +87,9 @@ def close(self): pass + def peek(self): + return '' + class DiskFile(Stream): @@ -455,6 +465,12 @@ return "".join(buf) + def peek(self): + if self.lines: + return self.lines[0] + "\n" + else: + return self.buf + write = PassThrough("write", flush_buffers=True) truncate = PassThrough("truncate", flush_buffers=True) flush = PassThrough("flush", flush_buffers=True) @@ -636,6 +652,24 @@ return data + def readline(self): + result = [] + while True: + # "peeks" on the underlying stream to see how many characters + # we can safely read without reading past an end-of-line + peeked = self.base.peek() + pn = peeked.find("\n") + pr = peeked.find("\r") + if pn < 0: pn = len(peeked) + if pr < 0: pr = len(peeked) + c = self.read(min(pn, pr) + 1) + if not c: + break + result.append(c) + if c.endswith('\n'): + break + return ''.join(result) + def seek(self, offset, whence=0): """Seeks based on knowledge that does not come from a tell() may go to the wrong place, since the number of @@ -677,6 +711,9 @@ else: self.buf = "" + def peek(self): + return self.buf + write = PassThrough("write", flush_buffers=True) truncate = PassThrough("truncate", flush_buffers=True) flush = PassThrough("flush", flush_buffers=True) From hpk at codespeak.net Sat Jan 29 14:44:37 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 14:44:37 +0100 (MET) Subject: [pypy-svn] r8715 - pypy/funding Message-ID: <20050129134437.7516027B5B@code1.codespeak.net> Author: hpk Date: Sat Jan 29 14:44:37 2005 New Revision: 8715 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: ok, more focusing on important aspects. note that we could use the Microsoft presence to aggressively argue for our presence because we are going to present our open agile developemtn process in contrast to Microsfot closed process. Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 14:44:37 2005 @@ -1,17 +1,20 @@ -Sprinting at the Pycon conference -================================= +PyPy Sprinting in non-european countries +======================================== -Justification for sprint work at Pycon, Washington D.C, PyPy project +Request for clarification/confirmation for upcoming sprint work +at Pycon, Washington D.C, PyPy project Background ---------- -In the proposal we explicitly mention Pycon as one of the key -conferences to participate in for the PyPy project. We have -a need to clarify with the EU commission if we have to be aware -of problems regarding reimbursment of costs for travelling and -working in countries other than in the EU. Specifically, we -would like to check if our next planned sprint at Pycon, Washington, +In the proposal we explicitly state that we are going to do +sprints in different countires. Some of the sprints are planned +to take place outside Europe. Especially Pycon, an important Python +conference, is one of the key conferences to participate in for the +PyPy project. We have a need to clarify with the EU commission if +we have to be aware of problems regarding reimbursment of costs for +travelling and working in countries other than in the EU. Specifically, +we would like to check if our next planned sprint at Pycon, Washington, imposes any problems with reimbursement. The Pycon conference is being held at the George Washington University @@ -59,30 +62,28 @@ we expect will be a large follow up of interested and contributing developers and researchers from the Python community. -Justification -------------- +Pycon is a very good opportunity for the project +------------------------------------------------ Pycon is the yearly Python conference, our presence there as a -project is expected The planned work of phase 1 will allow us -to, during the sprint, to run PyPy Cpython tests, these kind -of tasks are fairly easy to involve other than core developers -on The focus of testing and using testing tasks as a way of -getting contribution is also a very important way of -validating the work of the PyPy team as well as disseminating -the work +project is expected. The planned work of phase 1 fits very well +with involving early many key python developers and other experts +so that they can follow and contribute to the project. Please note that there will be a focus on the Microsoft goal of "Python on the .NET platform" during the conference. This -proprietary aspiration and interest of Python need a -nonproprietary counterpart and PyPy is expected to be the next -generation of Python in the community. We should be present -there as much as possible. +proprietary aspiration and interest of Python calls for our +nonproprietary counterpart and PyPy is expected by some to be the +next generation of Python in the community. We should be present +there as much as possible to present our views and presenting +our open agile development process in contrast to Microsoft's +rather closed development process. Participants ------------ The following partners and individuals are scheduled to attend -the Pycon sprint and the conference: +the Pycon sprint and the conference:: Sprint 4 days + conference 3 days @@ -94,11 +95,10 @@ merlinux Holger Krekel Tismerysoft Christian Tismer - Time frame ---------- -We would like to get feedback on these plans from the commission +We would like to get feedback on the above grounds from the commission as quick as possible as the conference is going to take place -in Mid-March already and we need to book flights and accomodation +in Mid-March 2005 already and we need to book flights and accomodation accordingly. From hpk at codespeak.net Sat Jan 29 15:11:58 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 15:11:58 +0100 (MET) Subject: [pypy-svn] r8716 - pypy/funding Message-ID: <20050129141158.5B04E27B66@code1.codespeak.net> Author: hpk Date: Sat Jan 29 15:11:58 2005 New Revision: 8716 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: yet another formatting fix Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 15:11:58 2005 @@ -85,15 +85,14 @@ The following partners and individuals are scheduled to attend the Pycon sprint and the conference:: -Sprint 4 days + conference 3 days - -Logilab 2 (unconfirmed) -DFKI Developer X -Strakt Jacob Hallen, Samuele Pedroni, Anders Chrigstroem -Change Maker Beatrice D?ring -HHU Duesseldorf Armin Rigo -merlinux Holger Krekel -Tismerysoft Christian Tismer + Sprint 4 days + conference 3 days + Logilab 2 (unconfirmed) + DFKI Developer X + Strakt Jacob Hallen, Samuele Pedroni, Anders Chrigstroem + Change Maker Beatrice D?ring + HHU Duesseldorf Armin Rigo + merlinux Holger Krekel + Tismerysoft Christian Tismer Time frame ---------- From bea at codespeak.net Sat Jan 29 15:36:29 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 15:36:29 +0100 (MET) Subject: [pypy-svn] r8717 - pypy/funding Message-ID: <20050129143629.889A427B66@code1.codespeak.net> Author: bea Date: Sat Jan 29 15:36:29 2005 New Revision: 8717 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: fixed typo (countries) Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sat Jan 29 15:36:29 2005 @@ -8,7 +8,7 @@ ---------- In the proposal we explicitly state that we are going to do -sprints in different countires. Some of the sprints are planned +sprints in different countries. Some of the sprints are planned to take place outside Europe. Especially Pycon, an important Python conference, is one of the key conferences to participate in for the PyPy project. We have a need to clarify with the EU commission if From arigo at codespeak.net Sat Jan 29 15:48:15 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 15:48:15 +0100 (MET) Subject: [pypy-svn] r8718 - pypy/dist/pypy/lib Message-ID: <20050129144815.9747B27B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 15:48:15 2005 New Revision: 8718 Added: pypy/dist/pypy/lib/traceback.py - copied, changed from r8714, pypy/dist/lib-python-2.3.4/traceback.py Log: Minor fix for new-style-class exceptions. Copied: pypy/dist/pypy/lib/traceback.py (from r8714, pypy/dist/lib-python-2.3.4/traceback.py) ============================================================================== --- pypy/dist/lib-python-2.3.4/traceback.py (original) +++ pypy/dist/pypy/lib/traceback.py Sat Jan 29 15:48:15 2005 @@ -155,7 +155,7 @@ which exception occurred is the always last string in the list. """ list = [] - if type(etype) == types.ClassType: + if isinstance(etype, (type, types.ClassType)): stype = etype.__name__ else: stype = etype From hpk at codespeak.net Sat Jan 29 15:58:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 15:58:50 +0100 (MET) Subject: [pypy-svn] r8719 - pypy/dist/pypy/lib Message-ID: <20050129145850.9365B27B66@code1.codespeak.net> Author: hpk Date: Sat Jan 29 15:58:50 2005 New Revision: 8719 Removed: pypy/dist/pypy/lib/re.py pypy/dist/pypy/lib/sre_adapt.py pypy/dist/pypy/lib/sre_parse.py Log: ok, it seems we had a mix of python 2.4 and 2.3 moduels with slight changes and were borrowing _sre from CPython anyway. So lets backup out our changes in pypy/lib andd see how far we get (if nobody minds, Seo?) Deleted: /pypy/dist/pypy/lib/re.py ============================================================================== --- /pypy/dist/pypy/lib/re.py Sat Jan 29 15:58:50 2005 +++ (empty file) @@ -1,30 +0,0 @@ -from dumbre import Pattern -# from plexre import Pattern -# from sre_adapt import Pattern - - -# From CPython -def escape(pattern): - "Escape all non-alphanumeric characters in pattern." - s = list(pattern) - for i in range(len(pattern)): - c = pattern[i] - if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"): - if c == "\000": - s[i] = "\\000" - else: - s[i] = "\\" + c - return ''.join(s) - - -_cache = {} - -def compile(pattern, flags=0): - if (pattern, flags) in _cache: - return _cache[pattern, flags] - compiled = Pattern(pattern, flags) - _cache[pattern, flags] = compiled - return compiled - -def match(pattern, string, flags=0): - return compile(pattern, flags).match(string) Deleted: /pypy/dist/pypy/lib/sre_adapt.py ============================================================================== --- /pypy/dist/pypy/lib/sre_adapt.py Sat Jan 29 15:58:50 2005 +++ (empty file) @@ -1,2 +0,0 @@ -import sre_compile -Pattern = sre_compile.compile Deleted: /pypy/dist/pypy/lib/sre_parse.py ============================================================================== --- /pypy/dist/pypy/lib/sre_parse.py Sat Jan 29 15:58:50 2005 +++ (empty file) @@ -1,742 +0,0 @@ -# -# Secret Labs' Regular Expression Engine -# -# convert re-style regular expression to sre pattern -# -# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. -# -# See the sre.py file for information on usage and redistribution. -# - -"""Internal support module for sre""" - -# XXX: show string offset and offending character for all errors - -# this module works under 1.5.2 and later. don't use string methods -import string, sys - -from sre_constants import * - -SPECIAL_CHARS = ".\\[{()*+?^$|" -REPEAT_CHARS = "*+?{" - -DIGITS = tuple("0123456789") - -OCTDIGITS = tuple("01234567") -HEXDIGITS = tuple("0123456789abcdefABCDEF") - -WHITESPACE = tuple(" \t\n\r\v\f") - -ESCAPES = { - r"\a": (LITERAL, ord("\a")), - r"\b": (LITERAL, ord("\b")), - r"\f": (LITERAL, ord("\f")), - r"\n": (LITERAL, ord("\n")), - r"\r": (LITERAL, ord("\r")), - r"\t": (LITERAL, ord("\t")), - r"\v": (LITERAL, ord("\v")), - r"\\": (LITERAL, ord("\\")) -} - -CATEGORIES = { - r"\A": (AT, AT_BEGINNING_STRING), # start of string - r"\b": (AT, AT_BOUNDARY), - r"\B": (AT, AT_NON_BOUNDARY), - r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]), - r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]), - r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]), - r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]), - r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]), - r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]), - r"\Z": (AT, AT_END_STRING), # end of string -} - -FLAGS = { - # standard flags - "i": SRE_FLAG_IGNORECASE, - "L": SRE_FLAG_LOCALE, - "m": SRE_FLAG_MULTILINE, - "s": SRE_FLAG_DOTALL, - "x": SRE_FLAG_VERBOSE, - # extensions - "t": SRE_FLAG_TEMPLATE, - "u": SRE_FLAG_UNICODE, -} - -# figure out best way to convert hex/octal numbers to integers -try: - int("10", 8) - atoi = int # 2.0 and later -except TypeError: - atoi = string.atoi # 1.5.2 - -class Pattern: - # master pattern object. keeps track of global attributes - def __init__(self): - self.flags = 0 - self.open = [] - self.groups = 1 - self.groupdict = {} - def opengroup(self, name=None): - gid = self.groups - self.groups = gid + 1 - if name is not None: - ogid = self.groupdict.get(name, None) - if ogid is not None: - raise error, ("redefinition of group name %s as group %d; " - "was group %d" % (repr(name), gid, ogid)) - self.groupdict[name] = gid - self.open.append(gid) - return gid - def closegroup(self, gid): - self.open.remove(gid) - def checkgroup(self, gid): - return gid < self.groups and gid not in self.open - -class SubPattern: - # a subpattern, in intermediate form - def __init__(self, pattern, data=None): - self.pattern = pattern - if data is None: - data = [] - self.data = data - self.width = None - def dump(self, level=0): - nl = 1 - for op, av in self.data: - print level*" " + op,; nl = 0 - if op == "in": - # member sublanguage - print; nl = 1 - for op, a in av: - print (level+1)*" " + op, a - elif op == "branch": - print; nl = 1 - i = 0 - for a in av[1]: - if i > 0: - print level*" " + "or" - a.dump(level+1); nl = 1 - i = i + 1 - elif type(av) in (type(()), type([])): - for a in av: - if isinstance(a, SubPattern): - if not nl: print - a.dump(level+1); nl = 1 - else: - print a, ; nl = 0 - else: - print av, ; nl = 0 - if not nl: print - def __repr__(self): - return repr(self.data) - def __len__(self): - return len(self.data) - def __iter__(self): - return iter(self.data) - def __delitem__(self, index): - del self.data[index] - def __getitem__(self, index): - if isinstance(index, slice): - return SubPattern(self.pattern, self.data[index]) - else: - return self.data[index] - def __setitem__(self, index, code): - self.data[index] = code - def insert(self, index, code): - self.data.insert(index, code) - def append(self, code): - self.data.append(code) - def getwidth(self): - # determine the width (min, max) for this subpattern - if self.width: - return self.width - lo = hi = 0L - for op, av in self.data: - if op is BRANCH: - i = sys.maxint - j = 0 - for av in av[1]: - l, h = av.getwidth() - i = min(i, l) - j = max(j, h) - lo = lo + i - hi = hi + j - elif op is CALL: - i, j = av.getwidth() - lo = lo + i - hi = hi + j - elif op is SUBPATTERN: - i, j = av[1].getwidth() - lo = lo + i - hi = hi + j - elif op in (MIN_REPEAT, MAX_REPEAT): - i, j = av[2].getwidth() - lo = lo + long(i) * av[0] - hi = hi + long(j) * av[1] - elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY): - lo = lo + 1 - hi = hi + 1 - elif op == SUCCESS: - break - self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint)) - return self.width - -class Tokenizer: - def __init__(self, string): - self.string = string - self.index = 0 - self.__next() - def __next(self): - if self.index >= len(self.string): - self.next = None - return - char = self.string[self.index] - if char[0] == "\\": - try: - c = self.string[self.index + 1] - except IndexError: - raise error, "bogus escape (end of line)" - char = char + c - self.index = self.index + len(char) - self.next = char - def match(self, char, skip=1): - if char == self.next: - if skip: - self.__next() - return 1 - return 0 - def get(self): - this = self.next - self.__next() - return this - def tell(self): - return self.index, self.next - def seek(self, index): - self.index, self.next = index - -def isident(char): - return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_" - -def isdigit(char): - return "0" <= char <= "9" - -def isname(name): - # check that group name is a valid string - if not isident(name[0]): - return False - for char in name: - if not isident(char) and not isdigit(char): - return False - return True - -def _group(escape, groups): - # check if the escape string represents a valid group - try: - gid = atoi(escape[1:]) - if gid and gid < groups: - return gid - except ValueError: - pass - return None # not a valid group - -def _class_escape(source, escape): - # handle escape code inside character class - code = ESCAPES.get(escape) - if code: - return code - code = CATEGORIES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape (exactly two digits) - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - escape = escape[2:] - if len(escape) != 2: - raise error, "bogus escape: %s" % repr("\\" + escape) - return LITERAL, atoi(escape, 16) & 0xff - elif escape[1:2] in OCTDIGITS: - # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 5: - escape = escape + source.get() - escape = escape[1:] - return LITERAL, atoi(escape, 8) & 0xff - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _escape(source, escape, state): - # handle escape code in expression - code = CATEGORIES.get(escape) - if code: - return code - code = ESCAPES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - if len(escape) != 4: - raise ValueError - return LITERAL, atoi(escape[2:], 16) & 0xff - elif escape[1:2] == "0": - # octal escape - while source.next in OCTDIGITS and len(escape) < 4: - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - elif escape[1:2] in DIGITS: - # octal escape *or* decimal group reference (sigh) - if source.next in DIGITS: - escape = escape + source.get() - if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and - source.next in OCTDIGITS): - # got three octal digits; this is an octal escape - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - # got at least one decimal digit; this is a group reference - group = _group(escape, state.groups) - if group: - if not state.checkgroup(group): - raise error, "cannot refer to open group" - return GROUPREF, group - raise ValueError - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _parse_sub(source, state, nested=1): - # parse an alternation: a|b|c - - items = [] - while 1: - items.append(_parse(source, state)) - if source.match("|"): - continue - if not nested: - break - if not source.next or source.match(")", 0): - break - else: - raise error, "pattern not properly closed" - - if len(items) == 1: - return items[0] - - subpattern = SubPattern(state) - - # check if all items share a common prefix - while 1: - prefix = None - for item in items: - if not item: - break - if prefix is None: - prefix = item[0] - elif item[0] != prefix: - break - else: - # all subitems start with a common "prefix". - # move it out of the branch - for item in items: - del item[0] - subpattern.append(prefix) - continue # check next one - break - - # check if the branch can be replaced by a character set - for item in items: - if len(item) != 1 or item[0][0] != LITERAL: - break - else: - # we can store this as a character set instead of a - # branch (the compiler may optimize this even more) - set = [] - for item in items: - set.append(item[0]) - subpattern.append((IN, set)) - return subpattern - - subpattern.append((BRANCH, (None, items))) - return subpattern - -def _parse(source, state): - # parse a simple pattern - - subpattern = SubPattern(state) - - while 1: - - if source.next in ("|", ")"): - break # end of subpattern - this = source.get() - if this is None: - break # end of pattern - - if state.flags & SRE_FLAG_VERBOSE: - # skip whitespace and comments - if this in WHITESPACE: - continue - if this == "#": - while 1: - this = source.get() - if this in (None, "\n"): - break - continue - - if this and this[0] not in SPECIAL_CHARS: - subpattern.append((LITERAL, ord(this))) - - elif this == "[": - # character set - set = [] -## if source.match(":"): -## pass # handle character classes - if source.match("^"): - set.append((NEGATE, None)) - # check remaining characters - start = set[:] - while 1: - this = source.get() - if this == "]" and set != start: - break - elif this and this[0] == "\\": - code1 = _class_escape(source, this) - elif this: - code1 = LITERAL, ord(this) - else: - raise error, "unexpected end of regular expression" - if source.match("-"): - # potential range - this = source.get() - if this == "]": - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - set.append((LITERAL, ord("-"))) - break - elif this: - if this[0] == "\\": - code2 = _class_escape(source, this) - else: - code2 = LITERAL, ord(this) - if code1[0] != LITERAL or code2[0] != LITERAL: - raise error, "bad character range" - lo = code1[1] - hi = code2[1] - if hi < lo: - raise error, "bad character range" - set.append((RANGE, (lo, hi))) - else: - raise error, "unexpected end of regular expression" - else: - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - - # XXX: should move set optimization to compiler! - if len(set)==1 and set[0][0] is LITERAL: - subpattern.append(set[0]) # optimization - elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: - subpattern.append((NOT_LITERAL, set[1][1])) # optimization - else: - # XXX: should add charmap optimization here - subpattern.append((IN, set)) - - elif this and this[0] in REPEAT_CHARS: - # repeat previous item - if this == "?": - min, max = 0, 1 - elif this == "*": - min, max = 0, MAXREPEAT - - elif this == "+": - min, max = 1, MAXREPEAT - elif this == "{": - here = source.tell() - min, max = 0, MAXREPEAT - lo = hi = "" - while source.next in DIGITS: - lo = lo + source.get() - if source.match(","): - while source.next in DIGITS: - hi = hi + source.get() - else: - hi = lo - if not source.match("}"): - subpattern.append((LITERAL, ord(this))) - source.seek(here) - continue - if lo: - min = atoi(lo) - if hi: - max = atoi(hi) - if max < min: - raise error, "bad repeat interval" - else: - raise error, "not supported" - # figure out which item to repeat - if subpattern: - item = subpattern[-1:] - else: - item = None - if not item or (len(item) == 1 and item[0][0] == AT): - raise error, "nothing to repeat" - if item[0][0] in (MIN_REPEAT, MAX_REPEAT): - raise error, "multiple repeat" - if source.match("?"): - subpattern[-1] = (MIN_REPEAT, (min, max, item)) - else: - subpattern[-1] = (MAX_REPEAT, (min, max, item)) - - elif this == ".": - subpattern.append((ANY, None)) - - elif this == "(": - group = 1 - name = None - if source.match("?"): - group = 0 - # options - if source.match("P"): - # python extensions - if source.match("<"): - # named group: skip forward to end of name - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ">": - break - name = name + char - group = 1 - if not isname(name): - raise error, "bad character in group name" - elif source.match("="): - # named backreference - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ")": - break - name = name + char - if not isname(name): - raise error, "bad character in group name" - gid = state.groupdict.get(name) - if gid is None: - raise error, "unknown group name" - subpattern.append((GROUPREF, gid)) - continue - else: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - raise error, "unknown specifier: ?P%s" % char - elif source.match(":"): - # non-capturing group - group = 2 - elif source.match("#"): - # comment - while 1: - if source.next is None or source.next == ")": - break - source.get() - if not source.match(")"): - raise error, "unbalanced parenthesis" - continue - elif source.next in ("=", "!", "<"): - # lookahead assertions - char = source.get() - dir = 1 - if char == "<": - if source.next not in ("=", "!"): - raise error, "syntax error" - dir = -1 # lookbehind - char = source.get() - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if char == "=": - subpattern.append((ASSERT, (dir, p))) - else: - subpattern.append((ASSERT_NOT, (dir, p))) - continue - else: - # flags - if not source.next in FLAGS: - raise error, "unexpected end of pattern" - while source.next in FLAGS: - state.flags = state.flags | FLAGS[source.get()] - if group: - # parse group contents - if group == 2: - # anonymous group - group = None - else: - group = state.opengroup(name) - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if group is not None: - state.closegroup(group) - subpattern.append((SUBPATTERN, (group, p))) - else: - while 1: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - if char == ")": - break - raise error, "unknown extension" - - elif this == "^": - subpattern.append((AT, AT_BEGINNING)) - - elif this == "$": - subpattern.append((AT, AT_END)) - - elif this and this[0] == "\\": - code = _escape(source, this, state) - subpattern.append(code) - - else: - raise error, "parser error" - - return subpattern - -def parse(str, flags=0, pattern=None): - # parse 're' pattern into list of (opcode, argument) tuples - - source = Tokenizer(str) - - if pattern is None: - pattern = Pattern() - pattern.flags = flags - pattern.str = str - - p = _parse_sub(source, pattern, 0) - - tail = source.get() - if tail == ")": - raise error, "unbalanced parenthesis" - elif tail: - raise error, "bogus characters at end of regular expression" - - if flags & SRE_FLAG_DEBUG: - p.dump() - - if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: - # the VERBOSE flag was switched on inside the pattern. to be - # on the safe side, we'll parse the whole thing again... - return parse(str, p.pattern.flags) - - return p - -def parse_template(source, pattern): - # parse 're' replacement string into list of literals and - # group references - s = Tokenizer(source) - p = [] - a = p.append - def literal(literal, p=p): - if p and p[-1][0] is LITERAL: - p[-1] = LITERAL, p[-1][1] + literal - else: - p.append((LITERAL, literal)) - sep = source[:0] - if type(sep) is type(""): - makechar = chr - else: - makechar = unichr - while 1: - this = s.get() - if this is None: - break # end of replacement string - if this and this[0] == "\\": - # group - if this == "\\g": - name = "" - if s.match("<"): - while 1: - char = s.get() - if char is None: - raise error, "unterminated group name" - if char == ">": - break - name = name + char - if not name: - raise error, "bad group name" - try: - index = atoi(name) - except ValueError: - if not isname(name): - raise error, "bad character in group name" - try: - index = pattern.groupindex[name] - except KeyError: - raise IndexError, "unknown group name" - a((MARK, index)) - elif len(this) > 1 and this[1] in DIGITS: - code = None - while 1: - group = _group(this, pattern.groups+1) - if group: - if (s.next not in DIGITS or - not _group(this + s.next, pattern.groups+1)): - code = MARK, group - break - elif s.next in OCTDIGITS: - this = this + s.get() - else: - break - if not code: - this = this[1:] - code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff) - if code[0] is LITERAL: - literal(code[1]) - else: - a(code) - else: - try: - this = makechar(ESCAPES[this][1]) - except KeyError: - pass - literal(this) - else: - literal(this) - # convert template to groups and literals lists - i = 0 - groups = [] - literals = [] - for c, s in p: - if c is MARK: - groups.append((i, s)) - literals.append(None) - else: - literals.append(s) - i = i + 1 - return groups, literals - -def expand_template(template, match): - g = match.group - sep = match.string[:0] - groups, literals = template - literals = literals[:] - try: - for index, group in groups: - literals[index] = s = g(group) - if s is None: - raise IndexError - except IndexError: - raise error, "empty group" - return string.join(literals, sep) From arigo at codespeak.net Sat Jan 29 16:01:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 16:01:13 +0100 (MET) Subject: [pypy-svn] r8720 - pypy/dist/pypy/lib/test2 Message-ID: <20050129150113.D125C27B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 16:01:13 2005 New Revision: 8720 Added: pypy/dist/pypy/lib/test2/test_funcattrs.py - copied, changed from r8714, pypy/dist/lib-python-2.3.4/test/test_funcattrs.py Log: copied, modified from CPython. Copied: pypy/dist/pypy/lib/test2/test_funcattrs.py (from r8714, pypy/dist/lib-python-2.3.4/test/test_funcattrs.py) ============================================================================== --- pypy/dist/lib-python-2.3.4/test/test_funcattrs.py (original) +++ pypy/dist/pypy/lib/test2/test_funcattrs.py Sat Jan 29 16:01:13 2005 @@ -36,8 +36,8 @@ try: del b.__dict__ -except TypeError: pass -else: raise TestFailed, 'del func.__dict__ expected TypeError' +except (AttributeError, TypeError): pass +else: raise TestFailed, 'expected AttributeError or TypeError' b.publish = 1 try: @@ -175,13 +175,13 @@ try: del another.__dict__ -except TypeError: pass -else: raise TestFailed +except (TypeError, AttributeError): pass +else: raise TestFailed, 'del another.__dict__ did not fail' try: del another.func_dict -except TypeError: pass -else: raise TestFailed +except (TypeError, AttributeError): pass +else: raise TestFailed, 'del another.func_dict did not fail' try: another.func_dict = None From ac at codespeak.net Sat Jan 29 16:04:08 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 16:04:08 +0100 (MET) Subject: [pypy-svn] r8721 - pypy/dist/pypy/interpreter Message-ID: <20050129150408.C868527B66@code1.codespeak.net> Author: ac Date: Sat Jan 29 16:04:08 2005 New Revision: 8721 Modified: pypy/dist/pypy/interpreter/pycode.py pypy/dist/pypy/interpreter/typedef.py Log: Add testing for equality to code objects. Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Sat Jan 29 16:04:08 2005 @@ -158,6 +158,38 @@ self = space.interpclass_w(w_self) return space.newtuple(self.co_names_w) + def descr_code__eq__(space, w_self, w_other): + self = space.interpclass_w(w_self) + other = space.interpclass_w(w_other) + if not isinstance(other, PyCode): + return space.w_False + areEqual = (self.co_name == other.co_name and + self.co_argcount == other.co_argcount and + self.co_nlocals == other.co_nlocals and + self.co_flags == other.co_flags and + self.co_firstlineno == other.co_firstlineno and + self.co_code == other.co_code and + len(self.co_consts_w) == len(other.co_consts_w)) + if not areEqual: + return space.w_False + + for i in xrange(len(self.co_consts_w)): + if not space.eq_w(self.co_consts_w[i], other.co_consts_w[i]): + return space.w_False + + if len(self.co_names_w) != len(other.co_names_w): + return space.w_False + + for i in xrange(len(self.co_names_w)): + if not space.eq_w(self.co_names_w[i], other.co_names_w[i]): + return space.w_False + if (self.co_varnames == other.co_varnames and + self.co_freevars == other.co_freevars and + self.co_cellvars == other.co_cellvars): + return space.w_True + + return space.w_True + def descr_code__new__(space, w_subtype, w_argcount, w_nlocals, w_stacksize, w_flags, w_codestring, w_constants, w_names, @@ -184,6 +216,7 @@ code.co_cellvars = unpack_str_tuple(space, w_cellvars) return space.wrap(code) + def _really_enhanceclass(key, stuff): return type("Mixed", key, {}) Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Jan 29 16:04:08 2005 @@ -194,6 +194,7 @@ PyCode.typedef = TypeDef('code', __new__ = interp2app(PyCode.descr_code__new__.im_func), + __eq__ = interp2app(PyCode.descr_code__eq__.im_func), co_argcount = interp_attrproperty('co_argcount'), co_nlocals = interp_attrproperty('co_nlocals'), co_stacksize = interp_attrproperty('co_stacksize'), From ac at codespeak.net Sat Jan 29 16:40:27 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 16:40:27 +0100 (MET) Subject: [pypy-svn] r8722 - pypy/dist/pypy/module Message-ID: <20050129154027.BA71527B66@code1.codespeak.net> Author: ac Date: Sat Jan 29 16:40:27 2005 New Revision: 8722 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Add __builtin__.unichr(). Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Sat Jan 29 16:40:27 2005 @@ -438,7 +438,8 @@ def help(): print "You must be joking." - +def unichr(code): + return (chr((code >> 24) & 0xff) + chr((code >> 16) & 0xff)+ chr((code >> 8) &0xff) + chr(code & 0xff)).decode('ucs-4') # ______________________________________________________________________ # # Interpreter-level function definitions From arigo at codespeak.net Sat Jan 29 16:46:43 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 16:46:43 +0100 (MET) Subject: [pypy-svn] r8723 - pypy/dist/pypy/interpreter Message-ID: <20050129154643.A78E827B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 16:46:43 2005 New Revision: 8723 Modified: pypy/dist/pypy/interpreter/pyopcode.py Log: missing space.str_w(). Modified: pypy/dist/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/dist/pypy/interpreter/pyopcode.py (original) +++ pypy/dist/pypy/interpreter/pyopcode.py Sat Jan 29 16:46:43 2005 @@ -72,8 +72,8 @@ return self.code.co_consts_w[index] def getname_w(self, index): - varname = self.code.co_names_w[index] - return varname + w_varname = self.code.co_names_w[index] + return w_varname ################################################################ @@ -435,7 +435,7 @@ # catch KeyErrors and turn them into NameErrors if not e.match(f.space, f.space.w_KeyError): raise - message = "name '%s' is not defined" % varname + message = "name '%s' is not defined" % f.space.str_w(w_varname) raise OperationError(f.space.w_NameError, f.space.wrap(message)) def UNPACK_SEQUENCE(f, itemcount): From ac at codespeak.net Sat Jan 29 16:56:58 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 16:56:58 +0100 (MET) Subject: [pypy-svn] r8724 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129155658.E8E2427B66@code1.codespeak.net> Author: ac Date: Sat Jan 29 16:56:58 2005 New Revision: 8724 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: Enable more tests. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 16:56:58 2005 @@ -23,6 +23,15 @@ mydir = py.magic.autopath().dirpath() +workingTests = ( +'test_urlparse.py', +'test_base64.py', +'test_binop.py', +'test_bisect.py', +'test_call', +'test_codeop.py', +'test_compile.py', +) def make_module(space, dottedname, filepath): #print "making module", dottedname, "from", filepath @@ -41,7 +50,7 @@ for x in self.fspath.listdir('test_*.py'): if x.read().find('unittest') != -1: # we can try to run ... - if x.basename != 'test_urlparse.py': + if x.basename not in workingTests: continue yield Module(x) From arigo at codespeak.net Sat Jan 29 17:03:53 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 17:03:53 +0100 (MET) Subject: [pypy-svn] r8725 - pypy/dist/pypy/interpreter Message-ID: <20050129160353.BAAC027B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 17:03:53 2005 New Revision: 8725 Modified: pypy/dist/pypy/interpreter/pycode.py Log: PyCode.co_consts_w is really a list, not a tuple. Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Sat Jan 29 17:03:53 2005 @@ -53,8 +53,8 @@ self.co_stacksize = 0 # #entries needed for evaluation stack self.co_flags = 0 # CO_..., see above self.co_code = None # string: instruction opcodes - self.co_consts_w = () # tuple: constants used (wrapped!) - self.co_names_w = [] # list of wrapped strings: names (for attrs,...) + self.co_consts_w = [] # list of constants used (wrapped!) + self.co_names_w = [] # list of wrapped strs: names (for attrs..) self.co_varnames = () # tuple of strings: local variable names self.co_freevars = () # tuple of strings: free variable names self.co_cellvars = () # tuple of strings: cell variable names From arigo at codespeak.net Sat Jan 29 17:07:04 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 17:07:04 +0100 (MET) Subject: [pypy-svn] r8726 - in pypy/dist/pypy: interpreter objspace objspace/std Message-ID: <20050129160704.ED56227B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 17:07:04 2005 New Revision: 8726 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/typedef.py pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/listobject.py Log: Support for __del__ on user-defined classes. Waiting for a better idea, this is done with a new space operation 'userdel'. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Sat Jan 29 17:07:04 2005 @@ -317,6 +317,7 @@ ('get', 'get', 3, ['__get__']), ('set', 'set', 3, ['__set__']), ('delete', 'delete', 2, ['__delete__']), + ('userdel', 'del', 2, ['__del__']), ] ObjSpace.BuiltinModuleTable = [ Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Jan 29 17:07:04 2005 @@ -36,6 +36,9 @@ # XXX sanity checks here self.w__class__ = w_subtype + def __del__(self): + self.space.userdel(self) + if typedef.hasdict: def user_setup(self, space, w_subtype): self.space = space @@ -59,7 +62,7 @@ body = dict([(key, value) for key, value in User_InsertNameHere.__dict__.items() - if not key.startswith('_')]) + if not key.startswith('_') or key == '__del__']) subcls = type(name, (cls,), body) return subcls Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Sat Jan 29 17:07:04 2005 @@ -243,6 +243,11 @@ raise OperationError(space.w_TypeError, space.wrap("__hash__() should return an int")) + def userdel(space, w_obj): + w_del = space.lookup(w_obj, '__del__') + if w_del is not None: + space.get_and_call_function(w_del, w_obj) + # xxx round, ord Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Sat Jan 29 17:07:04 2005 @@ -382,6 +382,10 @@ items[i] = items[i+d] items[i+d] = None w_list.ob_size -= d + # set the unused items to None to make sure the objects are freed + while i < w_list.ob_size: + items[i] = None + i += 1 # note that the default value will come back wrapped!!! def list_pop__List_Int(space, w_list, w_idx=-1): From ac at codespeak.net Sat Jan 29 17:11:18 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 17:11:18 +0100 (MET) Subject: [pypy-svn] r8727 - pypy/dist/pypy/module Message-ID: <20050129161118.84CB527B66@code1.codespeak.net> Author: ac Date: Sat Jan 29 17:11:18 2005 New Revision: 8727 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Improve implementation of unichr() Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Sat Jan 29 17:11:18 2005 @@ -439,7 +439,7 @@ print "You must be joking." def unichr(code): - return (chr((code >> 24) & 0xff) + chr((code >> 16) & 0xff)+ chr((code >> 8) &0xff) + chr(code & 0xff)).decode('ucs-4') + return unicode('\\U%08x' %(code), 'unicode-escape') # ______________________________________________________________________ # # Interpreter-level function definitions From arigo at codespeak.net Sat Jan 29 17:12:40 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 17:12:40 +0100 (MET) Subject: [pypy-svn] r8728 - pypy/dist/pypy/objspace/std Message-ID: <20050129161240.3DC2827B66@code1.codespeak.net> Author: arigo Date: Sat Jan 29 17:12:40 2005 New Revision: 8728 Modified: pypy/dist/pypy/objspace/std/listobject.py Log: oups, always run the tests before you check-in. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Sat Jan 29 17:12:40 2005 @@ -383,9 +383,8 @@ items[i+d] = None w_list.ob_size -= d # set the unused items to None to make sure the objects are freed - while i < w_list.ob_size: + for i in range(w_list.ob_size, ilow+d): items[i] = None - i += 1 # note that the default value will come back wrapped!!! def list_pop__List_Int(space, w_list, w_idx=-1): From ac at codespeak.net Sat Jan 29 17:24:00 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Sat, 29 Jan 2005 17:24:00 +0100 (MET) Subject: [pypy-svn] r8729 - pypy/dist/pypy/module Message-ID: <20050129162400.C005F27B66@code1.codespeak.net> Author: ac Date: Sat Jan 29 17:24:00 2005 New Revision: 8729 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Test that arg is within bound and raise correct exception. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Sat Jan 29 17:24:00 2005 @@ -439,6 +439,9 @@ print "You must be joking." def unichr(code): + import sys + if (code < 0 or code > sys.maxunicode): + raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) return unicode('\\U%08x' %(code), 'unicode-escape') # ______________________________________________________________________ # From arigo at codespeak.net Sat Jan 29 17:53:43 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 17:53:43 +0100 (MET) Subject: [pypy-svn] r8731 - pypy/dist/pypy/objspace/std Message-ID: <20050129165343.44BF127B4D@code1.codespeak.net> Author: arigo Date: Sat Jan 29 17:53:43 2005 New Revision: 8731 Modified: pypy/dist/pypy/objspace/std/floatobject.py Log: The float's ** can raise ZeroDivisionError too. Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Sat Jan 29 17:53:43 2005 @@ -245,6 +245,8 @@ raise FailedToImplement(space.w_OverflowError, space.wrap("float power")) except ValueError, e: raise FailedToImplement(space.w_ValueError, space.wrap(str(e))) + except ZeroDivisionError, e: # (0.0 ** -1) + raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) return W_FloatObject(space, z) From arigo at codespeak.net Sat Jan 29 17:55:40 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 17:55:40 +0100 (MET) Subject: [pypy-svn] r8732 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129165540.EA3A727B5C@code1.codespeak.net> Author: arigo Date: Sat Jan 29 17:55:40 2005 New Revision: 8732 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: CPython's test_operator passes. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 17:55:40 2005 @@ -31,6 +31,7 @@ 'test_call', 'test_codeop.py', 'test_compile.py', +'test_operator.py', ) def make_module(space, dottedname, filepath): From tismer at codespeak.net Sat Jan 29 18:07:23 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 18:07:23 +0100 (MET) Subject: [pypy-svn] r8734 - pypy/dist/pypy/lib Message-ID: <20050129170723.AF2CA27B5C@code1.codespeak.net> Author: tismer Date: Sat Jan 29 18:07:23 2005 New Revision: 8734 Modified: pypy/dist/pypy/lib/_classobj.py Log: a first implementation works quite fine, already and runs some of the standard tests. (Samuele+Chris) Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Sat Jan 29 18:07:23 2005 @@ -1,4 +1,9 @@ -import sys +import sys, operator + +def coerce(left, right): + # XXX this is just a surrogate for now + # XXX the builtin coerce needs to be implemented by PyPy + return None obj_setattr = object.__setattr__ obj_getattribute = object.__getattribute__ @@ -32,8 +37,8 @@ dic['__bases__'] = cls.__bases__ obj_setattr(cls, '__dict__', dic) -def retrieve(cls, attr): - dic = obj_getattribute(cls, '__dict__') +def retrieve(obj, attr): + dic = obj_getattribute(obj, '__dict__') try: return dic[attr] except KeyError: @@ -51,6 +56,15 @@ return v, found return None, None +def get_class_module(cls): + try: + mod = retrieve(cls, "__module__") + except AttributeError: + mod = None + if not isinstance(mod, str): + return "?" + return mod + def mro_lookup(v, name): try: mro = type(v).__mro__ @@ -140,32 +154,214 @@ return v return descr_get(v, None, self) - def __repr__(self): - try: - mod = retrieve(self, '__module__') - if not isinstance(mod, str): - mod = None - except AttributeError: - mod = None - if mod is None: - return "" % (self.__name__, uid(self)) - else: - return "" % (mod, self.__name__, uid(self)) + def __repr__(self): + mod = get_class_module(self) + return "" % (mod, self.__name__, uid(self)) def __str__(self): - try: - mod = retrieve(self, '__module__') - if not isinstance(mod, str): - mod = None - except AttributeError: - mod = None - if mod is None: + mod = get_class_module(self) + if mod == "?": return self.__name__ else: return "%s.%s" % (mod, self.__name__) - + + def __call__(self, *args, **kwds): + inst = object.__new__(instance) + dic = inst.__dict__ + dic['__class__'] = self + try: + init = self.__init__ + except AttributeError: + pass + else: + ret = init(inst, *args, **kwds) + if ret is not None: + raise TypeError("__init__() should return None") + return inst + +# first we use the object's dict for the instance dict. +# with a little more effort, it should be possible +# to provide a clean extra dict with no other attributes +# in it. + +def instance_getattr1(inst, name, exc=True): + if name == "__dict__": + return obj_getattribute(inst, name) + elif name == "__class__": + # for now, it lives in the instance dict + return retrieve(inst, name) + try: + return retrieve(inst, name) + except AttributeError: + cls = retrieve(inst, "__class__") + v, found = lookup(cls, name) + if not found: + if exc: + raise AttributeError, "%s instance has no attribute %s" % (cls.__name__, name) + else: + return None + descr_get = mro_lookup(v, '__get__') + if descr_get is None: + return v + return descr_get(v, inst, cls) class instance(object): - pass - + def __getattribute__(self, name): + try: + return instance_getattr1(self, name) + except AttributeError: + getattr = instance_getattr1(self, '__getattr__', exc=False) + if getattr is not None: + return getattr(name) + raise + def __new__(typ, klass, dic=None): + # typ is not used at all + if not isinstance(klass,classobj): + raise TypeError("instance() first arg must be class") + if dic is None: + dic = {} + elif not isinstance(dic, dict): + raise TypeError("instance() second arg must be dictionary or None") + inst = object.__new__(instance) + dic['__class__'] = klass + obj_setattr(inst, '__dict__', dic) + return inst + + def __setattr__(self, name, value): + if name == '__dict__': + if not isinstance(value, dict): + raise TypeError("__dict__ must be set to a dictionary") + # for now, we need to copy things, because we are using + # the __dict__for our class as well. This will vanish! + value['__class__'] = self.__class__ + obj_setattr(inst, '__dict__', value) + elif name == '__class__': + if not isinstance(value, classobj): + raise TypeError("__class__ must be set to a class") + self.__dict__['__class__'] = value + else: + setattr = instance_getattr1(self, '__setattr__', exc=False) + if setattr is not None: + setattr(name, value) + else: + self.__dict__[name] = value + + def __delattr__(self, name): + # abuse __setattr__ to get the complaints :-) + # this is as funny as in CPython + if name in ('__dict__', '__class__'): + instance.__setattr__(self, name, None) + else: + delattr = instance_getattr1(self, '__delattr__', exc=False) + if delattr is not None: + delattr(name) + else: + try: + del self.__dict__[name] + except KeyError, ex: + raise AttributeError("%s instance has no attribute '%s'" % ( + self.__class__.__name__,name) ) + + def __repr__(self): + try: + func = instance_getattr1(self, '__repr__') + except AttributeError: + klass = self.__class__ + mod = get_class_module(klass) + return "<%s.%s instance at 0x%x>" % (mod, klass.__name__, uid(self)) + return func() + + def __str__(self): + try: + func = instance_getattr1(self, '__str__') + except AttributeError: + return instance.__repr__(self) + return func() + + def __hash__(self): + _eq = instance_getattr1(self, "__eq__", False) + _cmp = instance_getattr1(self, "__cmp__", False) + _hash = instance_getattr1(self, "__hash__", False) + if (_eq or _cmp) and not _hash: + raise TypeError("unhashable instance") + if _hash: + ret = _hash() + if not isinstance(ret, int): + raise TypeError("__hash__() should return an int") + else: + return id(self) + + def __len__(self): + ret = instance_getattr1(self,'__len__')() + if isinstance(ret, int): + if ret < 0: + raise ValueError("__len__() should return >= 0") + return ret + else: + raise TypeError("__len__() should return an int") + + def __getitem__(self, key): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__getslice__', False) + if func: + return func(key.start, key.end) + return instance_getattr1(self, '__getitem__')(key) + + def __setitem__(self, key, value): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__setslice__', False) + if func: + func(key.start, key.end, value) + instance_getattr1(self, '__setitem__')(key, value) + + def __delitem__(self, key): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__delslice__', False) + if func: + func(key.start, key.end) + instance_getattr1(self, '__delitem__')(key) + + def __contains__(self, obj): + func = instance_getattr1(self, '__contains__', False) + if func: + return bool(func(obj)) + # now do it ourselves + for x in self: + if x == obj: + return True + return False + + # unary operators + def __neg__(self): + return instance_getattr1(self, '__neg__')() + def __pos__(self): + return instance_getattr1(self, '__abs__')() + def __abs__(self): + return instance_getattr1(self, '__abs__')() + + # binary operators + for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): + exec(""" +def __%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.%(op2)s(self, other) + +def __r%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__r%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.%(op2)s(other, self) +""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')]} + del op + From hpk at codespeak.net Sat Jan 29 18:10:42 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 18:10:42 +0100 (MET) Subject: [pypy-svn] r8735 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129171042.6EA8027B5C@code1.codespeak.net> Author: hpk Date: Sat Jan 29 18:10:42 2005 New Revision: 8735 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: basically allow to run "output" tests against PyPy (output tests are the ones that have an expected output file in test/output/*) Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 18:10:42 2005 @@ -5,6 +5,7 @@ from pypy.tool import pytestsupport from pypy.conftest import gettestobjspace, options from pypy.interpreter.module import Module as PyPyModule +from pypy.interpreter.main import run_string, run_file # # PyPy's command line extra options (these are added @@ -23,7 +24,7 @@ mydir = py.magic.autopath().dirpath() -workingTests = ( +working_unittests = ( 'test_urlparse.py', 'test_base64.py', 'test_binop.py', @@ -34,6 +35,10 @@ 'test_operator.py', ) +working_outputtests = ( + # well +) + def make_module(space, dottedname, filepath): #print "making module", dottedname, "from", filepath w_dottedname = space.wrap(dottedname) @@ -49,11 +54,7 @@ class Directory(py.test.collect.Directory): def __iter__(self): for x in self.fspath.listdir('test_*.py'): - if x.read().find('unittest') != -1: - # we can try to run ... - if x.basename not in workingTests: - continue - yield Module(x) + yield Module(x) def app_list_testmethods(mod, testcaseclass): """ return [(instance.setUp, instance.tearDown, @@ -75,11 +76,38 @@ l.append((instance.setUp, instance.tearDown, methods)) return l list_testmethods = app2interp_temp(app_list_testmethods) - - -class Module(py.test.collect.Module): + +def Module(fspath): + output = fspath.dirpath('output', fspath.purebasename) + if output.check(file=1): + # ok this is an output test + if fspath.basename not in working_outputtests: + return + return OutputTestItem(fspath, output) + content = fspath.read() + if content.find('unittest') != -1: + # we can try to run ... + if fspath.basename not in working_unittests: + return + return UnittestModule(fspath) + +class OutputTestItem(py.test.Item): + def __init__(self, fspath, output): + self.fspath = fspath + self.outputpath = output + self.extpy = py.path.extpy(fspath) + + def run(self, driver): + space = gettestobjspace('std') + try: + run_file(str(self.fspath), space=space) + except OperationError, e: + raise self.Failed( + excinfo=pytestsupport.AppExceptionInfo(space, e)) + +class UnittestModule(py.test.collect.Module): def __init__(self, fspath): - super(Module, self).__init__(fspath) + super(UnittestModule, self).__init__(fspath) def _prepare(self): if hasattr(self, 'space'): From bea at codespeak.net Sat Jan 29 18:11:58 2005 From: bea at codespeak.net (bea at codespeak.net) Date: Sat, 29 Jan 2005 18:11:58 +0100 (MET) Subject: [pypy-svn] r8736 - pypy/funding Message-ID: <20050129171158.3F60D27B5C@code1.codespeak.net> Author: bea Date: Sat Jan 29 18:11:58 2005 New Revision: 8736 Added: pypy/funding/calendardeliverables_pypyproject_050125_v1.sxc (contents, props changed) Log: uppdated version of Jacobs calendar for Saarbruecken meeting, this with partners per wp Added: pypy/funding/calendardeliverables_pypyproject_050125_v1.sxc ============================================================================== Binary file. No diff available. From arigo at codespeak.net Sat Jan 29 18:12:38 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 29 Jan 2005 18:12:38 +0100 (MET) Subject: [pypy-svn] r8737 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129171238.1905527B5C@code1.codespeak.net> Author: arigo Date: Sat Jan 29 18:12:37 2005 New Revision: 8737 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: test_heapq passes (slowly). Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 18:12:37 2005 @@ -33,6 +33,7 @@ 'test_codeop.py', 'test_compile.py', 'test_operator.py', +'test_heapq.py', ) working_outputtests = ( From hpk at codespeak.net Sat Jan 29 18:13:34 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 18:13:34 +0100 (MET) Subject: [pypy-svn] r8738 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050129171334.3076827B5C@code1.codespeak.net> Author: hpk Date: Sat Jan 29 18:13:34 2005 New Revision: 8738 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: be a bit more clever about not running tests but still allowing to run tests named on the cmdline Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Jan 29 18:13:34 2005 @@ -55,6 +55,9 @@ class Directory(py.test.collect.Directory): def __iter__(self): for x in self.fspath.listdir('test_*.py'): + if fspath.basename not in working_outputtests and \ + fspath.basename not in working_unittests: + continue yield Module(x) def app_list_testmethods(mod, testcaseclass): @@ -82,14 +85,10 @@ output = fspath.dirpath('output', fspath.purebasename) if output.check(file=1): # ok this is an output test - if fspath.basename not in working_outputtests: - return return OutputTestItem(fspath, output) content = fspath.read() if content.find('unittest') != -1: # we can try to run ... - if fspath.basename not in working_unittests: - return return UnittestModule(fspath) class OutputTestItem(py.test.Item): From tismer at codespeak.net Sat Jan 29 19:17:41 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sat, 29 Jan 2005 19:17:41 +0100 (MET) Subject: [pypy-svn] r8740 - pypy/dist/pypy/lib/test2 Message-ID: <20050129181741.0831A27B57@code1.codespeak.net> Author: tismer Date: Sat Jan 29 19:17:40 2005 New Revision: 8740 Added: pypy/dist/pypy/lib/test2/test_class.py Log: added a test forclasses that is just a copy of the python lib thingy, with some hacks added to actually get the _class.py file imported. This should vanish absolutely soon. Added: pypy/dist/pypy/lib/test2/test_class.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/test2/test_class.py Sat Jan 29 19:17:40 2005 @@ -0,0 +1,334 @@ +"Test the functionality of Python classes implementing operators." + +from test.test_support import TestFailed + +# HACK BEGIN + +# After this implementation is complete and +# incorporated into the core after translation, +# this test file should really vanish! + +import pypy, os +prefix = os.path.dirname(pypy.__file__) +libdir = os.path.join(prefix, "lib") +fname = "_classobj.py" +fpath = os.path.join(libdir, fname) +execfile(fpath) + +__metaclass__ = classobj + +# HACK END + +testmeths = [ + +# Binary operations + "add", + "radd", + "sub", + "rsub", + "mul", + "rmul", + "div", + "rdiv", + "mod", + "rmod", + "divmod", + "rdivmod", + "pow", + "rpow", + "rshift", + "rrshift", + "lshift", + "rlshift", + "and", + "rand", + "or", + "ror", + "xor", + "rxor", + +# List/dict operations + "contains", + "getitem", + "getslice", + "setitem", + "setslice", + "delitem", + "delslice", + +# Unary operations + "neg", + "pos", + "abs", + "int", + "long", + "float", + "oct", + "hex", + +# generic operations + "init", + ] + +# These need to return something other than None +# "coerce", +# "hash", +# "str", +# "repr", + +# These are separate because they can influence the test of other methods. +# "getattr", +# "setattr", +# "delattr", + +class AllTests: + def __coerce__(self, *args): + print "__coerce__:", args + return (self,) + args + + def __hash__(self, *args): + print "__hash__:", args + return hash(id(self)) + + def __str__(self, *args): + print "__str__:", args + return "AllTests" + + def __repr__(self, *args): + print "__repr__:", args + return "AllTests" + + def __cmp__(self, *args): + print "__cmp__:", args + return 0 + + def __del__(self, *args): + print "__del__:", args + +# Synthesize AllTests methods from the names in testmeths. + +method_template = """\ +def __%(method)s__(self, *args): + print "__%(method)s__:", args +""" + +for method in testmeths: + exec method_template % locals() in AllTests.__dict__ + +del method, method_template + +# this also tests __init__ of course. +testme = AllTests() + +# Binary operations + +testme + 1 +1 + testme + +testme - 1 +1 - testme + +testme * 1 +1 * testme + +if 1/2 == 0: + testme / 1 + 1 / testme +else: + # True division is in effect, so "/" doesn't map to __div__ etc; but + # the canned expected-output file requires that __div__ etc get called. + testme.__coerce__(1) + testme.__div__(1) + testme.__coerce__(1) + testme.__rdiv__(1) + +testme % 1 +1 % testme + +divmod(testme,1) +divmod(1, testme) + +testme ** 1 +1 ** testme + +testme >> 1 +1 >> testme + +testme << 1 +1 << testme + +testme & 1 +1 & testme + +testme | 1 +1 | testme + +testme ^ 1 +1 ^ testme + + +# List/dict operations + +1 in testme + +testme[1] +testme[1] = 1 +del testme[1] + +testme[:42] +testme[:42] = "The Answer" +del testme[:42] + +testme[2:1024:10] +testme[2:1024:10] = "A lot" +del testme[2:1024:10] + +testme[:42, ..., :24:, 24, 100] +testme[:42, ..., :24:, 24, 100] = "Strange" +del testme[:42, ..., :24:, 24, 100] + + +# Now remove the slice hooks to see if converting normal slices to slice +# object works. + +del AllTests.__getslice__ +del AllTests.__setslice__ +del AllTests.__delslice__ + +import sys +if sys.platform[:4] != 'java': + testme[:42] + testme[:42] = "The Answer" + del testme[:42] +else: + # This works under Jython, but the actual slice values are + # different. + print "__getitem__: (slice(0, 42, None),)" + print "__setitem__: (slice(0, 42, None), 'The Answer')" + print "__delitem__: (slice(0, 42, None),)" + +# Unary operations + +-testme ++testme +abs(testme) +if sys.platform[:4] != 'java': + int(testme) + long(testme) + float(testme) + oct(testme) + hex(testme) +else: + # Jython enforced that these methods return + # a value of the expected type. + print "__int__: ()" + print "__long__: ()" + print "__float__: ()" + print "__oct__: ()" + print "__hex__: ()" + + +# And the rest... + +hash(testme) +repr(testme) +str(testme) + +testme == 1 +testme < 1 +testme > 1 +testme <> 1 +testme != 1 +1 == testme +1 < testme +1 > testme +1 <> testme +1 != testme + +# This test has to be last (duh.) + +del testme +if sys.platform[:4] == 'java': + import java + java.lang.System.gc() + +# Interfering tests + +class ExtraTests: + def __getattr__(self, *args): + print "__getattr__:", args + return "SomeVal" + + def __setattr__(self, *args): + print "__setattr__:", args + + def __delattr__(self, *args): + print "__delattr__:", args + +testme = ExtraTests() +testme.spam +testme.eggs = "spam, spam, spam and ham" +del testme.cardinal + + +# Test correct errors from hash() on objects with comparisons but no __hash__ + +class C0: + pass + +hash(C0()) # This should work; the next two should raise TypeError + +class C1: + def __cmp__(self, other): return 0 + +try: hash(C1()) +except TypeError: pass +else: raise TestFailed, "hash(C1()) should raise an exception" + +class C2: + def __eq__(self, other): return 1 + +try: hash(C2()) +except TypeError: pass +else: raise TestFailed, "hash(C2()) should raise an exception" + + +# Test for SF bug 532646 + +class A: + pass +A.__call__ = A() +a = A() +try: + a() # This should not segfault +except RuntimeError: + pass +else: + raise TestFailed, "how could this not have overflowed the stack?" + + +# Tests for exceptions raised in instance_getattr2(). + +def booh(self): + raise AttributeError, "booh" + +class A: + a = property(booh) +try: + A().a # Raised AttributeError: A instance has no attribute 'a' +except AttributeError, x: + if str(x) is not "booh": + print "attribute error for A().a got masked:", str(x) + +class E: + __eq__ = property(booh) +E() == E() # In debug mode, caused a C-level assert() to fail + +class I: + __init__ = property(booh) +try: + I() # In debug mode, printed XXX undetected error and raises AttributeError +except AttributeError, x: + pass +else: + print "attribute error for I.__init__ got masked" From hpk at codespeak.net Sat Jan 29 20:13:29 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 29 Jan 2005 20:13:29 +0100 (MET) Subject: [pypy-svn] r8741 - pypy/extradoc/sprintinfo Message-ID: <20050129191329.6CCF027B57@code1.codespeak.net> Author: hpk Date: Sat Jan 29 20:13:29 2005 New Revision: 8741 Added: pypy/extradoc/sprintinfo/post-leysin-planning.txt (contents, props changed) Log: the result of our Leysin Sprint summary discussion and the planning for the time after it ... Added: pypy/extradoc/sprintinfo/post-leysin-planning.txt ============================================================================== --- (empty file) +++ pypy/extradoc/sprintinfo/post-leysin-planning.txt Sat Jan 29 20:13:29 2005 @@ -0,0 +1,146 @@ +Summary of Leysin Sprint (and before) +===================================== + +- introduced newcomers to the project to the PyPy code base + and development process. We gave introductions to the + basic functioning and the structure of the code base. + For getting everybody into PyPy, we then mainly ran tests + and fixed various bugs and added small things. + +- we ran some of the CPython's regression tests against PyPy + and enhanced the testing tool to be able to directly + support running such tests. + +- merged the typeunwrap-branch back into the trunk + (which allows for type specific unwraps in favour + of deprecated generic unwraps). + +- We started the DFKI dialogue, documented action items + and time plan for the first two weeks of February + (mostly related to coordination and EU communication + issues). We came up with a model for physical persons + resp. sprint attendants to get 100% funding. + +- Bea interviewed almost all of the sprint participants + to find out about their expectations, dissemination + and more general ideas about the PyPy project and + where it should go in the future. Evaluation forms + have been send out to various people. + +- Planning for new and improved infrastructure, including + subversion ("newrepolayout") and issue tracker decisions. + +- We fixed some long standing translator issues and + tried to better understand which problems are remaining. + +- We started to work on old-style classes (implemented + at application level with new-style classes) + +- We have a better bootstrap and a rather complete exception + hierarchy now (generated from application level to interpreter + level). This was done with a tool (to be completed) that is + basically capable of translating applevel modules to interplevel + (which are then completly unreadable). + +- we reorganized and cleaned up our base python module + library which is now in dist/lib-python-2.3.4 whereas + our overrides and modifications are in dist/pypy/lib. + +- The applevel file class was improved but is currently + not used by default (both for slowness and lack of speed). + +- we may have an itertools implementation (Adrien?). + +- Marcus Denker gave a nice talk about Squeak and Croquet + which we discussed (including technical details of + the continuation based Seaside Framework and + possible future cooperation). + + +Tasks for after the Leysin Sprint +================================= + +- lots of management/coordination tasks are already + summarized by Bea in specific documents in svn/pypy/funding. + +other than that here is a technical brainstorming about +upcoming issues and tasks: + +- Be on #pypy IRC (on freenode) to continously discuss + the below issues and (re-)assign tasks (and help non-partners + to be able to contribute) + +- (Samuele, Christian) finish old-style classes (and their tests) + and integrate them into PyPy (so that by default bare class + statements mean old-style classes). + +- (Armin, Christian) implement slots and coerce + +- (Christian, ...) prepare a nice gentinterp-tool for generating + interp-level modules out of application level ones. Also allow + to build inline interp-level classes from application ones. + +- (Anders, ...) fix pow() and generally complete builtins, reload() etc.pp. + +- (Holger, ...) complete the lib-python2.3.4/test runner to support more + styles of testing (doctests mainly). + +- (Samuele, Christian) provide the "get-rid-of-unused-variables" algorithms + directly at the flowgraph level (without requiring the annotator) + +- (Armin, Christian) refactor and make more code reusable from the + various Gen* backends. + +- (Holger) find a way to run the tests (some of which need to be fixed) + from pypy/lib (which overrides ...) + +- (Armin, Holger) find a way to run automated tests on many platforms + +- (Armin, Christian) fix and cleanup pypy/module resp. the mixin of + interplevel/applevel code, reduce magic and only good magic ... + +- install an IRC-bot that logs stuff on #pypy (for ultimate + control of whats going on) + +- (Samuele, Laura) enumerate all missing or incomplete + builtin types, functions and modules. (preferably + as a web page :-) + +- (Bea will call for a common day, but let's not wait for Bea) + consolidate/improve and add documentation about the current state + of PyPy affairs (especially regarding its technical implementation). + And actually remove outdated documentation. + +- (Holger, pypy-dev) come up with and discuss a release scheme for PyPy + +- (Bea will dispatch) Write a good tutorial. + +- (Samuele, Christian) resolve platform problems (regarding longs + and ints and tests and 32/64 bits ...), including arithmetic + how to do bit-limited arithmetic at interpreter level? + +- (Logilab?) we need a parser/compiler, and we especially want to + cleanly provide a hook to allow custom + compilation/code objects/frame objects/bytecode implementations. + +- (Armin, Samuele) translation: finish "filling the caches", revisit + MultiMethods with respect to that and other issues. + +- make GenC() use more of the annotation (currently nada) + +- (Samuele) improve and further fix the annotator (never ending task) + +- explore the through-java path + +- (Jacob, holger, ...) generate all kinds of reports about various + aspects of developing + +- (Christian) play a bit with generating app- or interplevel + from C-sources + +- (Bea and Jacob driving) prepare and improve sprints with + respect to giving tutorials, welcoming and integrating newcomers + +- be prepared to make a list of tasks suitable + for sprint attendees (and try to find out before + about the according experience levels) From tismer at codespeak.net Sun Jan 30 01:51:05 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Sun, 30 Jan 2005 01:51:05 +0100 (MET) Subject: [pypy-svn] r8742 - in pypy/dist/pypy: module translator Message-ID: <20050130005105.014EF27B57@code1.codespeak.net> Author: tismer Date: Sun Jan 30 01:51:05 2005 New Revision: 8742 Modified: pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: using Armin's transform_dead_op_vars now to get rid of unused variables. This is really nice. Now I should stick with my promise and extract that function from transform.py . Next time, I want to produce goto-less generated code. Well, maybe atleast partially for the simple cases. Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Sun Jan 30 01:51:05 2005 @@ -173,9 +173,8 @@ def __str__(space, w_self_1): - w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=w_argc_17=None - w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=w_14=w_15=w_19=w_20=None - w_21=None + w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=v9=w_self_11=w_15=w_16=None + w_5=w_self_10=w_12=w_13=w_14=None goto = 1 # startblock while True: @@ -190,34 +189,33 @@ goto = 5 else: assert v4 == False - w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + w_self_6, w_argc_7 = w_self_1, w_argc_2 goto = 2 if goto == 2: - w_9 = space.eq(w_argc_7, gi_1) - v10 = space.is_true(w_9) - if v10 == True: - (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, - w_8, w_9, v10) + w_8 = space.eq(w_argc_7, gi_1) + v9 = space.is_true(w_8) + if v9 == True: + w_self_10 = w_self_6 goto = 3 else: - assert v10 == False - w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + assert v9 == False + w_self_11 = w_self_6 goto = 4 if goto == 3: - w_19 = space.getattr(w_self_11, gs_args) - w_20 = space.getitem(w_19, gi_0) - _tup = space.newtuple([w_20]) - w_21 = space.call(space.w_str, _tup) - w_5 = w_21 + w_12 = space.getattr(w_self_10, gs_args) + w_13 = space.getitem(w_12, gi_0) + _tup = space.newtuple([w_13]) + w_14 = space.call(space.w_str, _tup) + w_5 = w_14 goto = 5 if goto == 4: - w_22 = space.getattr(w_self_16, gs_args) - _tup = space.newtuple([w_22]) - w_23 = space.call(space.w_str, _tup) - w_5 = w_23 + w_15 = space.getattr(w_self_11, gs_args) + _tup = space.newtuple([w_15]) + w_16 = space.call(space.w_str, _tup) + w_5 = w_16 goto = 5 if goto == 5: @@ -246,8 +244,8 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None - w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=None + w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None + w_13=w_14=w_15=w_16=None goto = 1 # startblock while True: @@ -258,28 +256,27 @@ w_4 = space.eq(w_argc_0, gi_4) v5 = space.is_true(w_4) if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) + w_self_6, w_args_7 = w_self_3, w_args_1 goto = 2 else: assert v5 == False - w_12 = space.w_None + w_8 = space.w_None goto = 3 if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_object, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_start, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_end, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_reason, w_19) - w_12 = space.w_None + w_9 = space.getitem(w_args_7, gi_0) + w_10 = space.setattr(w_self_6, gs_object, w_9) + w_11 = space.getitem(w_args_7, gi_1) + w_12 = space.setattr(w_self_6, gs_start, w_11) + w_13 = space.getitem(w_args_7, gi_2) + w_14 = space.setattr(w_self_6, gs_end, w_13) + w_15 = space.getitem(w_args_7, gi_3) + w_16 = space.setattr(w_self_6, gs_reason, w_15) + w_8 = space.w_None goto = 3 if goto == 3: - return w_12 + return w_8 fastf_UnicodeTranslateError___init__ = globals().pop("__init__") ##SECTION## @@ -365,9 +362,8 @@ def __str__(space, w_self_1): - w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=w_9=v10=w_self_16=w_argc_17=None - w_18=w_22=w_23=w_5=w_self_11=w_argc_12=w_13=w_14=w_15=w_19=w_20=None - w_21=None + w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=v9=w_self_11=w_15=w_16=None + w_5=w_self_10=w_12=w_13=w_14=None goto = 1 # startblock while True: @@ -382,33 +378,32 @@ goto = 5 else: assert v4 == False - w_self_6, w_argc_7, w_8 = w_self_1, w_argc_2, w_3 + w_self_6, w_argc_7 = w_self_1, w_argc_2 goto = 2 if goto == 2: - w_9 = space.eq(w_argc_7, gi_1) - v10 = space.is_true(w_9) - if v10 == True: - (w_self_11, w_argc_12, w_13, w_14, w_15) = (w_self_6, w_argc_7, - w_8, w_9, v10) + w_8 = space.eq(w_argc_7, gi_1) + v9 = space.is_true(w_8) + if v9 == True: + w_self_10 = w_self_6 goto = 3 else: - assert v10 == False - w_self_16, w_argc_17, w_18 = w_self_6, w_argc_7, w_9 + assert v9 == False + w_self_11 = w_self_6 goto = 4 if goto == 3: - w_19 = space.getattr(w_self_11, gs_args) - w_20 = space.getitem(w_19, gi_0) - w_21 = space.repr(w_20) - w_5 = w_21 + w_12 = space.getattr(w_self_10, gs_args) + w_13 = space.getitem(w_12, gi_0) + w_14 = space.repr(w_13) + w_5 = w_14 goto = 5 if goto == 4: - w_22 = space.getattr(w_self_16, gs_args) - _tup = space.newtuple([w_22]) - w_23 = space.call(space.w_str, _tup) - w_5 = w_23 + w_15 = space.getattr(w_self_11, gs_args) + _tup = space.newtuple([w_15]) + w_16 = space.call(space.w_str, _tup) + w_5 = w_16 goto = 5 if goto == 5: @@ -432,11 +427,10 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_18=w_args_19=w_argc_20=None - w_21=v23=w_self_29=w_args_30=w_argc_31=w_36=v37=w_43=w_self_38=None - w_args_39=w_argc_40=w_41=w_42=w_44=w_45=w_46=w_47=w_48=w_49=w_self_24=None - w_args_25=w_argc_26=w_27=w_28=w_32=w_33=w_34=w_35=w_self_9=w_args_10=None - w_argc_11=w_12=w_13=w_14=w_15=w_16=w_17=w_22=None + w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_12=w_args_13=w_argc_14=None + w_15=v17=w_self_21=w_args_22=w_argc_23=w_28=v29=w_32=w_self_30=None + w_args_31=w_33=w_34=w_35=w_36=w_37=w_38=w_self_18=w_args_19=w_argc_20=None + w_24=w_25=w_26=w_27=w_self_9=w_args_10=w_argc_11=w_16=None goto = 1 # startblock while True: @@ -450,65 +444,61 @@ w_7 = space.le(gi_2, w_argc_0) v8 = space.is_true(w_7) if v8 == True: - (w_self_9, w_args_10, w_argc_11, w_12, w_13, w_14, w_15, w_16, - w_17) = (w_self_3, w_args_1, w_argc_0, w_2, w_4, w_5, w_6, w_7, - v8) + w_self_9, w_args_10, w_argc_11 = w_self_3, w_args_1, w_argc_0 goto = 2 else: assert v8 == False - (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_3, w_args_1, + (w_self_12, w_args_13, w_argc_14, w_15) = (w_self_3, w_args_1, w_argc_0, w_7) goto = 3 if goto == 2: - w_22 = space.le(w_argc_11, gi_3) - (w_self_18, w_args_19, w_argc_20, w_21) = (w_self_9, w_args_10, - w_argc_11, w_22) + w_16 = space.le(w_argc_11, gi_3) + (w_self_12, w_args_13, w_argc_14, w_15) = (w_self_9, w_args_10, + w_argc_11, w_16) goto = 3 if goto == 3: - v23 = space.is_true(w_21) - if v23 == True: - (w_self_24, w_args_25, w_argc_26, w_27, w_28) = (w_self_18, - w_args_19, w_argc_20, w_21, v23) + v17 = space.is_true(w_15) + if v17 == True: + w_self_18, w_args_19, w_argc_20 = w_self_12, w_args_13, w_argc_14 goto = 4 else: - assert v23 == False - w_self_29, w_args_30, w_argc_31 = w_self_18, w_args_19, w_argc_20 + assert v17 == False + w_self_21, w_args_22, w_argc_23 = w_self_12, w_args_13, w_argc_14 goto = 5 if goto == 4: - w_32 = space.getitem(w_args_25, gi_0) - w_33 = space.setattr(w_self_24, gs_errno, w_32) - w_34 = space.getitem(w_args_25, gi_1) - w_35 = space.setattr(w_self_24, gs_strerror, w_34) - w_self_29, w_args_30, w_argc_31 = w_self_24, w_args_25, w_argc_26 + w_24 = space.getitem(w_args_19, gi_0) + w_25 = space.setattr(w_self_18, gs_errno, w_24) + w_26 = space.getitem(w_args_19, gi_1) + w_27 = space.setattr(w_self_18, gs_strerror, w_26) + w_self_21, w_args_22, w_argc_23 = w_self_18, w_args_19, w_argc_20 goto = 5 if goto == 5: - w_36 = space.eq(w_argc_31, gi_3) - v37 = space.is_true(w_36) - if v37 == True: - (w_self_38, w_args_39, w_argc_40, w_41, w_42) = (w_self_29, - w_args_30, w_argc_31, w_36, v37) + w_28 = space.eq(w_argc_23, gi_3) + v29 = space.is_true(w_28) + if v29 == True: + w_self_30, w_args_31 = w_self_21, w_args_22 goto = 6 else: - assert v37 == False - w_43 = space.w_None + assert v29 == False + w_32 = space.w_None goto = 7 if goto == 6: - w_44 = space.getitem(w_args_39, gi_2) - w_45 = space.setattr(w_self_38, gs_filename, w_44) - w_46 = space.getitem(w_args_39, gi_0) - w_47 = space.getitem(w_args_39, gi_1) - w_48 = space.newtuple([w_46, w_47]) - w_49 = space.setattr(w_self_38, gs_args, w_48) - w_43 = space.w_None + w_33 = space.getitem(w_args_31, gi_2) + w_34 = space.setattr(w_self_30, gs_filename, w_33) + w_35 = space.getitem(w_args_31, gi_0) + w_36 = space.getitem(w_args_31, gi_1) + w_37 = space.newtuple([w_35, w_36]) + w_38 = space.setattr(w_self_30, gs_args, w_37) + w_32 = space.w_None goto = 7 if goto == 7: - return w_43 + return w_32 fastf_EnvironmentError___init__ = globals().pop("__init__") ##SECTION## @@ -587,8 +577,8 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None - w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=w_22=None + w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None + w_13=w_14=w_15=w_16=w_17=w_18=None goto = 1 # startblock while True: @@ -599,30 +589,29 @@ w_4 = space.eq(w_argc_0, gi_5) v5 = space.is_true(w_4) if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) + w_self_6, w_args_7 = w_self_3, w_args_1 goto = 2 else: assert v5 == False - w_12 = space.w_None + w_8 = space.w_None goto = 3 if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_encoding, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_object, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_start, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_end, w_19) - w_21 = space.getitem(w_args_7, gi_4) - w_22 = space.setattr(w_self_6, gs_reason, w_21) - w_12 = space.w_None + w_9 = space.getitem(w_args_7, gi_0) + w_10 = space.setattr(w_self_6, gs_encoding, w_9) + w_11 = space.getitem(w_args_7, gi_1) + w_12 = space.setattr(w_self_6, gs_object, w_11) + w_13 = space.getitem(w_args_7, gi_2) + w_14 = space.setattr(w_self_6, gs_start, w_13) + w_15 = space.getitem(w_args_7, gi_3) + w_16 = space.setattr(w_self_6, gs_end, w_15) + w_17 = space.getitem(w_args_7, gi_4) + w_18 = space.setattr(w_self_6, gs_reason, w_17) + w_8 = space.w_None goto = 3 if goto == 3: - return w_12 + return w_8 fastf_UnicodeEncodeError___init__ = globals().pop("__init__") ##SECTION## @@ -703,10 +692,9 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_2=w_4=v5=w_self_12=w_args_13=w_argc_14=w_17=v18=w_24=None - w_self_19=w_args_20=w_argc_21=w_22=w_23=w_25=w_26=w_27=w_28=w_29=None - w_30=w_31=w_32=w_33=w_34=w_35=w_36=w_self_6=w_args_7=w_argc_8=None - w_9=w_10=w_11=w_15=w_16=None + w_argc_0=w_2=w_4=v5=w_self_9=w_args_10=w_argc_11=w_14=v15=w_18=None + w_self_16=w_args_17=w_19=w_20=w_21=w_22=w_23=w_24=w_25=w_26=w_27=None + w_28=w_29=w_30=w_self_6=w_args_7=w_argc_8=w_12=w_13=None goto = 1 # startblock while True: @@ -717,50 +705,48 @@ w_4 = space.ge(w_argc_0, gi_1) v5 = space.is_true(w_4) if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) + w_self_6, w_args_7, w_argc_8 = w_self_3, w_args_1, w_argc_0 goto = 2 else: assert v5 == False - w_self_12, w_args_13, w_argc_14 = w_self_3, w_args_1, w_argc_0 + w_self_9, w_args_10, w_argc_11 = w_self_3, w_args_1, w_argc_0 goto = 3 if goto == 2: - w_15 = space.getitem(w_args_7, gi_0) - w_16 = space.setattr(w_self_6, gs_msg, w_15) - w_self_12, w_args_13, w_argc_14 = w_self_6, w_args_7, w_argc_8 + w_12 = space.getitem(w_args_7, gi_0) + w_13 = space.setattr(w_self_6, gs_msg, w_12) + w_self_9, w_args_10, w_argc_11 = w_self_6, w_args_7, w_argc_8 goto = 3 if goto == 3: - w_17 = space.eq(w_argc_14, gi_2) - v18 = space.is_true(w_17) - if v18 == True: - (w_self_19, w_args_20, w_argc_21, w_22, w_23) = (w_self_12, - w_args_13, w_argc_14, w_17, v18) + w_14 = space.eq(w_argc_11, gi_2) + v15 = space.is_true(w_14) + if v15 == True: + w_self_16, w_args_17 = w_self_9, w_args_10 goto = 4 else: - assert v18 == False - w_24 = space.w_None + assert v15 == False + w_18 = space.w_None goto = 5 if goto == 4: - w_25 = space.getitem(w_args_20, gi_1) - w_26 = space.getitem(w_25, gi_0) - w_27 = space.setattr(w_self_19, gs_filename, w_26) - w_28 = space.getitem(w_args_20, gi_1) - w_29 = space.getitem(w_28, gi_1) - w_30 = space.setattr(w_self_19, gs_lineno, w_29) - w_31 = space.getitem(w_args_20, gi_1) - w_32 = space.getitem(w_31, gi_2) - w_33 = space.setattr(w_self_19, gs_offset, w_32) - w_34 = space.getitem(w_args_20, gi_1) - w_35 = space.getitem(w_34, gi_3) - w_36 = space.setattr(w_self_19, gs_text, w_35) - w_24 = space.w_None + w_19 = space.getitem(w_args_17, gi_1) + w_20 = space.getitem(w_19, gi_0) + w_21 = space.setattr(w_self_16, gs_filename, w_20) + w_22 = space.getitem(w_args_17, gi_1) + w_23 = space.getitem(w_22, gi_1) + w_24 = space.setattr(w_self_16, gs_lineno, w_23) + w_25 = space.getitem(w_args_17, gi_1) + w_26 = space.getitem(w_25, gi_2) + w_27 = space.setattr(w_self_16, gs_offset, w_26) + w_28 = space.getitem(w_args_17, gi_1) + w_29 = space.getitem(w_28, gi_3) + w_30 = space.setattr(w_self_16, gs_text, w_29) + w_18 = space.w_None goto = 5 if goto == 5: - return w_24 + return w_18 fastf_SyntaxError___init__ = globals().pop("__init__") ##SECTION## @@ -819,10 +805,9 @@ def __init__(space, w_self_4, w_args_1): - w_argc_0=w_2=v3=w_self_10=w_args_11=w_argc_12=w_14=w_15=v16=w_self_23=None - w_args_24=w_argc_25=w_28=v29=w_35=w_self_30=w_args_31=w_argc_32=None - w_33=w_34=w_36=w_self_17=w_args_18=w_argc_19=w_20=w_21=w_22=w_26=None - w_27=w_self_5=w_args_6=w_argc_7=w_8=w_9=w_13=None + w_argc_0=w_2=v3=w_self_8=w_args_9=w_argc_10=w_12=w_13=v14=w_self_18=None + w_args_19=w_argc_20=w_23=v24=w_27=w_self_25=w_args_26=w_28=w_self_15=None + w_args_16=w_argc_17=w_21=w_22=w_self_5=w_args_6=w_argc_7=w_11=None goto = 1 # startblock while True: @@ -832,57 +817,54 @@ w_2 = space.eq(w_argc_0, gi_0) v3 = space.is_true(w_2) if v3 == True: - (w_self_5, w_args_6, w_argc_7, w_8, w_9) = (w_self_4, w_args_1, - w_argc_0, w_2, v3) + w_self_5, w_args_6, w_argc_7 = w_self_4, w_args_1, w_argc_0 goto = 2 else: assert v3 == False - w_self_10, w_args_11, w_argc_12 = w_self_4, w_args_1, w_argc_0 + w_self_8, w_args_9, w_argc_10 = w_self_4, w_args_1, w_argc_0 goto = 3 if goto == 2: - w_13 = space.setattr(w_self_5, gs_code, space.w_None) - w_self_10, w_args_11, w_argc_12 = w_self_5, w_args_6, w_argc_7 + w_11 = space.setattr(w_self_5, gs_code, space.w_None) + w_self_8, w_args_9, w_argc_10 = w_self_5, w_args_6, w_argc_7 goto = 3 if goto == 3: - w_14 = space.setattr(w_self_10, gs_args, w_args_11) - w_15 = space.eq(w_argc_12, gi_1) - v16 = space.is_true(w_15) - if v16 == True: - (w_self_17, w_args_18, w_argc_19, w_20, w_21, w_22) = (w_self_10, - w_args_11, w_argc_12, w_14, w_15, v16) + w_12 = space.setattr(w_self_8, gs_args, w_args_9) + w_13 = space.eq(w_argc_10, gi_1) + v14 = space.is_true(w_13) + if v14 == True: + w_self_15, w_args_16, w_argc_17 = w_self_8, w_args_9, w_argc_10 goto = 4 else: - assert v16 == False - w_self_23, w_args_24, w_argc_25 = w_self_10, w_args_11, w_argc_12 + assert v14 == False + w_self_18, w_args_19, w_argc_20 = w_self_8, w_args_9, w_argc_10 goto = 5 if goto == 4: - w_26 = space.getitem(w_args_18, gi_0) - w_27 = space.setattr(w_self_17, gs_code, w_26) - w_self_23, w_args_24, w_argc_25 = w_self_17, w_args_18, w_argc_19 + w_21 = space.getitem(w_args_16, gi_0) + w_22 = space.setattr(w_self_15, gs_code, w_21) + w_self_18, w_args_19, w_argc_20 = w_self_15, w_args_16, w_argc_17 goto = 5 if goto == 5: - w_28 = space.ge(w_argc_25, gi_2) - v29 = space.is_true(w_28) - if v29 == True: - (w_self_30, w_args_31, w_argc_32, w_33, w_34) = (w_self_23, - w_args_24, w_argc_25, w_28, v29) + w_23 = space.ge(w_argc_20, gi_2) + v24 = space.is_true(w_23) + if v24 == True: + w_self_25, w_args_26 = w_self_18, w_args_19 goto = 6 else: - assert v29 == False - w_35 = space.w_None + assert v24 == False + w_27 = space.w_None goto = 7 if goto == 6: - w_36 = space.setattr(w_self_30, gs_code, w_args_31) - w_35 = space.w_None + w_28 = space.setattr(w_self_25, gs_code, w_args_26) + w_27 = space.w_None goto = 7 if goto == 7: - return w_35 + return w_27 fastf_SystemExit___init__ = globals().pop("__init__") ##SECTION## @@ -902,8 +884,8 @@ def __init__(space, w_self_3, w_args_1): - w_argc_0=w_2=w_4=v5=w_12=w_self_6=w_args_7=w_argc_8=w_9=w_10=None - w_11=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=w_22=None + w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None + w_13=w_14=w_15=w_16=w_17=w_18=None goto = 1 # startblock while True: @@ -914,30 +896,29 @@ w_4 = space.eq(w_argc_0, gi_5) v5 = space.is_true(w_4) if v5 == True: - (w_self_6, w_args_7, w_argc_8, w_9, w_10, w_11) = (w_self_3, - w_args_1, w_argc_0, w_2, w_4, v5) + w_self_6, w_args_7 = w_self_3, w_args_1 goto = 2 else: assert v5 == False - w_12 = space.w_None + w_8 = space.w_None goto = 3 if goto == 2: - w_13 = space.getitem(w_args_7, gi_0) - w_14 = space.setattr(w_self_6, gs_encoding, w_13) - w_15 = space.getitem(w_args_7, gi_1) - w_16 = space.setattr(w_self_6, gs_object, w_15) - w_17 = space.getitem(w_args_7, gi_2) - w_18 = space.setattr(w_self_6, gs_start, w_17) - w_19 = space.getitem(w_args_7, gi_3) - w_20 = space.setattr(w_self_6, gs_end, w_19) - w_21 = space.getitem(w_args_7, gi_4) - w_22 = space.setattr(w_self_6, gs_reason, w_21) - w_12 = space.w_None + w_9 = space.getitem(w_args_7, gi_0) + w_10 = space.setattr(w_self_6, gs_encoding, w_9) + w_11 = space.getitem(w_args_7, gi_1) + w_12 = space.setattr(w_self_6, gs_object, w_11) + w_13 = space.getitem(w_args_7, gi_2) + w_14 = space.setattr(w_self_6, gs_start, w_13) + w_15 = space.getitem(w_args_7, gi_3) + w_16 = space.setattr(w_self_6, gs_end, w_15) + w_17 = space.getitem(w_args_7, gi_4) + w_18 = space.setattr(w_self_6, gs_reason, w_17) + w_8 = space.w_None goto = 3 if goto == 3: - return w_12 + return w_8 fastf_UnicodeDecodeError___init__ = globals().pop("__init__") ##SECTION## @@ -1000,7 +981,7 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' ## function 'test_exceptions' -## firstlineno 1246 +## firstlineno 1258 ##SECTION## # global declarations # global object gfunc_test_exceptions Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Sun Jan 30 01:51:05 2005 @@ -44,6 +44,10 @@ from pypy.tool.sourcetools import render_docstr +# this thingy should be moved into a better place +# and be modified to work without annotation. +from pypy.translator.transform import transform_dead_op_vars + # ____________________________________________________________ def c_string(s): @@ -946,10 +950,18 @@ #t.simplify(func) graph = t.getflowgraph(func) + start = graph.startblock allblocks = ordered_blocks(graph) nblocks = len(allblocks) + # HAACK + # I willmove that function to simplify.py, + # removing the dependency of annotated, + # which basically is just a list of blocks. + self.annotated = allblocks + transform_dead_op_vars(self) + blocknum = {} for block in allblocks: blocknum[block] = len(blocknum)+1 From hpk at codespeak.net Sun Jan 30 20:05:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 30 Jan 2005 20:05:08 +0100 (MET) Subject: [pypy-svn] r8743 - pypy/funding Message-ID: <20050130190508.9F40B27B4C@code1.codespeak.net> Author: hpk Date: Sun Jan 30 20:05:08 2005 New Revision: 8743 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: improvements to consistency and reasonsing of the "justification" (which is actually a request for clarifications and confirmation. Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sun Jan 30 20:05:08 2005 @@ -7,25 +7,31 @@ Background ---------- -In the proposal we explicitly state that we are going to do -sprints in different countries. Some of the sprints are planned -to take place outside Europe. Especially Pycon, an important Python -conference, is one of the key conferences to participate in for the -PyPy project. We have a need to clarify with the EU commission if -we have to be aware of problems regarding reimbursment of costs for -travelling and working in countries other than in the EU. Specifically, -we would like to check if our next planned sprint at Pycon, Washington, -imposes any problems with reimbursement. - -The Pycon conference is being held at the George Washington University -in Washington D.C 23-25 March 2005. Before the conference, -between 19 and 22 March 2005 there are community sprints -planned. Last year there where 5 different projects sprinting. -This year there will be 9 different sprints before the -conference, PyPy is to be one of them. - -Sprinting is a key work and dissemination method of the PyPy project, -as noted in the proposal at B.3.4 Dissemniation:: +A key part of our proposal is that we that we are going to do +sprints in different countries in order to probe a new open and +agile development model and also in order to mobilize +resources and receive contributions. Some of the sprints are +planned to take place outside Europe. Especially Pycon, an +important Python conference, is one of the key conferences +to participate in for the PyPy project. + +We have a need to clarify with the EU commission if we have to +be aware of problems regarding reimbursment of costs for +travelling and working in countries other than in the EU. +Specifically, we would like to check if our next planned +sprint at Pycon, Washington, imposes any problems with +reimbursement of costs. + +The Pycon conference is being held at the George Washington +University in Washington D.C 23-25 March 2005. Before the +conference, between 19 and 22 March 2005 there are community +sprints planned. Last year there where 5 different projects +sprinting. This year there will be 9 different sprints before +the conference, PyPy is scheduled to be one of them. + +Note that sprinting is a key work and dissemination method of +the PyPy project, as noted in the proposal at B.3.4 +Dissemniation:: We will also partake in the following official events, forum, conferences to spread information about the ongoing project, @@ -41,43 +47,37 @@ Programming) More conferences will be added once the project gets started. -Also - please see the proposal B.5.5 Communication and reporting:: - - We will present multiple reports and scientific papers on - major conferences such as EuroPython (Python's European - community conference), FOSDEM (Free and Open Source Developer - European Meeting), OSCON (Open Source Convention), PyCon - (Python developer conference) and to domain specific audiences - such as embedded device developers. +Pycon is an important opportunity for the project +------------------------------------------------- It is the intention of the PyPy team to participate and host a -sprint focused on the PyPy work. Main goals are to disseminate +sprint focused on the PyPy work and the open & agile development +model at the Pycon Conference. Other goals are to disseminate knowledge about the technical content of PyPy as well as get active contribution from developers in the community on PyPy -work that is the focus for phase 1 of the project. There will -also be talks (by Holger Krekel and Armin Rigo, PyPy team) -during the actual conference. - -We want to have our full team presence to able to handle what -we expect will be a large follow up of interested and -contributing developers and researchers from the Python community. - -Pycon is a very good opportunity for the project ------------------------------------------------- +work that is the focus for phase 1 of the project. Pycon is the yearly Python conference, our presence there as a project is expected. The planned work of phase 1 fits very well with involving early many key python developers and other experts so that they can follow and contribute to the project. -Please note that there will be a focus on the Microsoft goal of -"Python on the .NET platform" during the conference. This -proprietary aspiration and interest of Python calls for our -nonproprietary counterpart and PyPy is expected by some to be the -next generation of Python in the community. We should be present -there as much as possible to present our views and presenting +There will be a focus on the Microsoft's "Python on the +.NET platform" during the conference. This proprietary +aspiration and interest of Python calls for our nonproprietary +counterpart and PyPy is expected by some to be the next +generation of Python in the community. We should be present +there as much as possible to present our views and presenting our open agile development process in contrast to Microsoft's -rather closed development process. +rather closed development process. + +There will also be talks from the PyPy team (by Holger Krekel +and Armin Rigo during the conference. They will both present +first results of the ongoing project. + +We want to have our full team presence to able to handle what +we expect will be a large follow up of interested and +contributing developers and researchers from the Python community. Participants ------------ @@ -98,6 +98,6 @@ ---------- We would like to get feedback on the above grounds from the commission -as quick as possible as the conference is going to take place +as quick as possible because the conference is going to take place in Mid-March 2005 already and we need to book flights and accomodation accordingly. From hpk at codespeak.net Sun Jan 30 21:59:38 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sun, 30 Jan 2005 21:59:38 +0100 (MET) Subject: [pypy-svn] r8747 - pypy/funding Message-ID: <20050130205938.EC71927B47@code1.codespeak.net> Author: hpk Date: Sun Jan 30 21:59:38 2005 New Revision: 8747 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: ok, and another round on the clarification request. Yes, i do think it's worth to invest some time into refining this document. If there really is a need for asking permission from the EU then some perfectionism can't hurt :-) Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Sun Jan 30 21:59:38 2005 @@ -1,8 +1,8 @@ -PyPy Sprinting in non-european countries -======================================== +PyPy: Sprinting in non-european countries +========================================= -Request for clarification/confirmation for upcoming sprint work -at Pycon, Washington D.C, PyPy project +Request for clarification/confirmation for upcoming +sprint work at Pycon, Washington D.C, PyPy project Background ---------- @@ -25,7 +25,7 @@ The Pycon conference is being held at the George Washington University in Washington D.C 23-25 March 2005. Before the conference, between 19 and 22 March 2005 there are community -sprints planned. Last year there where 5 different projects +sprints planned. Last year there were 5 different projects sprinting. This year there will be 9 different sprints before the conference, PyPy is scheduled to be one of them. @@ -47,37 +47,38 @@ Programming) More conferences will be added once the project gets started. -Pycon is an important opportunity for the project -------------------------------------------------- +Pycon is an important opportunity for the PyPy project +------------------------------------------------------ -It is the intention of the PyPy team to participate and host a -sprint focused on the PyPy work and the open & agile development -model at the Pycon Conference. Other goals are to disseminate -knowledge about the technical content of PyPy as well as get -active contribution from developers in the community on PyPy -work that is the focus for phase 1 of the project. - -Pycon is the yearly Python conference, our presence there as a -project is expected. The planned work of phase 1 fits very well -with involving early many key python developers and other experts -so that they can follow and contribute to the project. - -There will be a focus on the Microsoft's "Python on the -.NET platform" during the conference. This proprietary -aspiration and interest of Python calls for our nonproprietary -counterpart and PyPy is expected by some to be the next -generation of Python in the community. We should be present -there as much as possible to present our views and presenting -our open agile development process in contrast to Microsoft's -rather closed development process. +It is the intention of the PyPy team to host a sprint focused +on the PyPy work and the open & agile development model at the +Pycon Conference. Goals include disseminating knowledge +about the technical content of PyPy as well as getting active +contribution from developers and feedback from the community +on PyPy work (especially for phase 1 of our project). + +Pycon is the yearly Python conference, our presence there is +expected. The planned work of phase 1 fits very well with +involving key python developers and other experts so that +they can follow up and contribute to the project. + +This year there will be an extraordinary a focus on the +Microsoft's plans regarding "Python on the .NET platform". +This proprietary aspiration and Microsoft's recent interest on +Python calls for our nonproprietary counterpart. + +PyPy is a candidate for the "next generation" Python version +in the community. We should not only present our views and +early results but emphasize especially our open agile +development process in contrast to Microsoft's rather closed +one. Therefore we want to have our full team present during +the Pycon sprint days. We also want to be able to handle what +we expect will be a good follow up of interested and +contributing developers and researchers from the Python community. -There will also be talks from the PyPy team (by Holger Krekel +There will be talks from the PyPy team by Holger Krekel and Armin Rigo during the conference. They will both present -first results of the ongoing project. - -We want to have our full team presence to able to handle what -we expect will be a large follow up of interested and -contributing developers and researchers from the Python community. +first results of our ongoing project. Participants ------------ From hpk at codespeak.net Mon Jan 31 00:45:07 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 31 Jan 2005 00:45:07 +0100 (MET) Subject: [pypy-svn] r8755 - pypy/funding Message-ID: <20050130234507.3861627B5A@code1.codespeak.net> Author: hpk Date: Mon Jan 31 00:45:07 2005 New Revision: 8755 Modified: pypy/funding/physical-person-model.txt Log: removed the "swinging door" reference. Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Mon Jan 31 00:45:07 2005 @@ -77,12 +77,12 @@ The model of getting physical persons into the consortium --------------------------------------------------------- -We want to have a lightweight process ("swinging door principle") -for integrating physical persons into the EU project. The technical -board is to actively invite people and partners to join our -sprints and other developments. The board will select people -according to criterias like usefulness for the project, -past contributions and specific fields of knowledge. +We want to implement an effective process for integrating physical +persons into the EU project. The technical board is to +actively invite people and partners to join our sprints and +other developments. The board will select people according to +criterias like usefulness for the project, past contributions +and specific fields of knowledge. However, on the formal side there are still some details to resolve and we ask everyone, including our EU project officer From sanxiyn at codespeak.net Mon Jan 31 07:59:24 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 31 Jan 2005 07:59:24 +0100 (MET) Subject: [pypy-svn] r8756 - pypy/dist/pypy/documentation Message-ID: <20050131065924.9457F27B5E@code1.codespeak.net> Author: sanxiyn Date: Mon Jan 31 07:59:24 2005 New Revision: 8756 Modified: pypy/dist/pypy/documentation/howtosvn.txt Log: Fix repository URL Modified: pypy/dist/pypy/documentation/howtosvn.txt ============================================================================== --- pypy/dist/pypy/documentation/howtosvn.txt (original) +++ pypy/dist/pypy/documentation/howtosvn.txt Mon Jan 31 07:59:24 2005 @@ -6,7 +6,7 @@ If you already know how to use it here is the URL you need to interact with subversion: -``http://codespeak.net/svn/pypy/trunk/`` +``http://codespeak.net/svn/pypy/dist`` If you don't know what to do then Jens-Uwe Mager has prepared some installation files which should help you to install subversion on From hpk at codespeak.net Mon Jan 31 10:38:29 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 31 Jan 2005 10:38:29 +0100 (MET) Subject: [pypy-svn] r8758 - pypy/funding Message-ID: <20050131093829.33D1927B6E@code1.codespeak.net> Author: hpk Date: Mon Jan 31 10:38:29 2005 New Revision: 8758 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: typo fix Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Mon Jan 31 10:38:29 2005 @@ -62,7 +62,7 @@ involving key python developers and other experts so that they can follow up and contribute to the project. -This year there will be an extraordinary a focus on the +This year there will be an extraordinary focus on the Microsoft's plans regarding "Python on the .NET platform". This proprietary aspiration and Microsoft's recent interest on Python calls for our nonproprietary counterpart. From lene at codespeak.net Mon Jan 31 14:26:22 2005 From: lene at codespeak.net (lene at codespeak.net) Date: Mon, 31 Jan 2005 14:26:22 +0100 (MET) Subject: [pypy-svn] r8761 - pypy/funding Message-ID: <20050131132622.20D3D27B71@code1.codespeak.net> Author: lene Date: Mon Jan 31 14:26:21 2005 New Revision: 8761 Added: pypy/funding/form-c-strep.pdf Log: added form c for streps - as sent by alastair on nov 22nd Added: pypy/funding/form-c-strep.pdf ============================================================================== Files (empty file) and pypy/funding/form-c-strep.pdf Mon Jan 31 14:26:21 2005 differ From lac at codespeak.net Mon Jan 31 17:10:53 2005 From: lac at codespeak.net (lac at codespeak.net) Date: Mon, 31 Jan 2005 17:10:53 +0100 (MET) Subject: [pypy-svn] r8762 - pypy/funding Message-ID: <20050131161053.C005C27B7A@code1.codespeak.net> Author: lac Date: Mon Jan 31 17:10:53 2005 New Revision: 8762 Modified: pypy/funding/justificationpycon_pypyproject_050128.txt Log: Fix formatting of Holger's name, and spelling of Anders' and Jacob's Modified: pypy/funding/justificationpycon_pypyproject_050128.txt ============================================================================== --- pypy/funding/justificationpycon_pypyproject_050128.txt (original) +++ pypy/funding/justificationpycon_pypyproject_050128.txt Mon Jan 31 17:10:53 2005 @@ -89,10 +89,10 @@ Sprint 4 days + conference 3 days Logilab 2 (unconfirmed) DFKI Developer X - Strakt Jacob Hallen, Samuele Pedroni, Anders Chrigstroem + Strakt Jacob Hall?n, Samuele Pedroni, Anders Chrigstr?m Change Maker Beatrice D?ring HHU Duesseldorf Armin Rigo - merlinux Holger Krekel + merlinux Holger Krekel Tismerysoft Christian Tismer Time frame From pedronis at codespeak.net Mon Jan 31 18:15:11 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 31 Jan 2005 18:15:11 +0100 (MET) Subject: [pypy-svn] r8763 - pypy/dist/pypy/lib Message-ID: <20050131171511.A518827B71@code1.codespeak.net> Author: pedronis Date: Mon Jan 31 18:15:11 2005 New Revision: 8763 Modified: pypy/dist/pypy/lib/_classobj.py (contents, props changed) Log: fixeol Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Mon Jan 31 18:15:11 2005 @@ -1,9 +1,9 @@ import sys, operator - -def coerce(left, right): - # XXX this is just a surrogate for now - # XXX the builtin coerce needs to be implemented by PyPy - return None + +def coerce(left, right): + # XXX this is just a surrogate for now + # XXX the builtin coerce needs to be implemented by PyPy + return None obj_setattr = object.__setattr__ obj_getattribute = object.__getattribute__ @@ -56,15 +56,15 @@ return v, found return None, None -def get_class_module(cls): - try: - mod = retrieve(cls, "__module__") - except AttributeError: - mod = None - if not isinstance(mod, str): - return "?" - return mod - +def get_class_module(cls): + try: + mod = retrieve(cls, "__module__") + except AttributeError: + mod = None + if not isinstance(mod, str): + return "?" + return mod + def mro_lookup(v, name): try: mro = type(v).__mro__ @@ -81,7 +81,7 @@ def __new__(subtype, name, bases, dic): if not isinstance(name, str): type_err('name', 'string', name) - + if bases is None: bases = () @@ -154,7 +154,7 @@ return v return descr_get(v, None, self) - def __repr__(self): + def __repr__(self): mod = get_class_module(self) return "" % (mod, self.__name__, uid(self)) @@ -164,204 +164,204 @@ return self.__name__ else: return "%s.%s" % (mod, self.__name__) - - def __call__(self, *args, **kwds): - inst = object.__new__(instance) - dic = inst.__dict__ - dic['__class__'] = self - try: - init = self.__init__ - except AttributeError: - pass - else: - ret = init(inst, *args, **kwds) - if ret is not None: - raise TypeError("__init__() should return None") + + def __call__(self, *args, **kwds): + inst = object.__new__(instance) + dic = inst.__dict__ + dic['__class__'] = self + try: + init = self.__init__ + except AttributeError: + pass + else: + ret = init(inst, *args, **kwds) + if ret is not None: + raise TypeError("__init__() should return None") return inst - -# first we use the object's dict for the instance dict. -# with a little more effort, it should be possible -# to provide a clean extra dict with no other attributes -# in it. - -def instance_getattr1(inst, name, exc=True): - if name == "__dict__": - return obj_getattribute(inst, name) - elif name == "__class__": - # for now, it lives in the instance dict - return retrieve(inst, name) - try: - return retrieve(inst, name) - except AttributeError: - cls = retrieve(inst, "__class__") - v, found = lookup(cls, name) - if not found: - if exc: - raise AttributeError, "%s instance has no attribute %s" % (cls.__name__, name) - else: - return None + +# first we use the object's dict for the instance dict. +# with a little more effort, it should be possible +# to provide a clean extra dict with no other attributes +# in it. + +def instance_getattr1(inst, name, exc=True): + if name == "__dict__": + return obj_getattribute(inst, name) + elif name == "__class__": + # for now, it lives in the instance dict + return retrieve(inst, name) + try: + return retrieve(inst, name) + except AttributeError: + cls = retrieve(inst, "__class__") + v, found = lookup(cls, name) + if not found: + if exc: + raise AttributeError, "%s instance has no attribute %s" % (cls.__name__, name) + else: + return None descr_get = mro_lookup(v, '__get__') if descr_get is None: return v return descr_get(v, inst, cls) class instance(object): - def __getattribute__(self, name): - try: - return instance_getattr1(self, name) - except AttributeError: - getattr = instance_getattr1(self, '__getattr__', exc=False) - if getattr is not None: - return getattr(name) + def __getattribute__(self, name): + try: + return instance_getattr1(self, name) + except AttributeError: + getattr = instance_getattr1(self, '__getattr__', exc=False) + if getattr is not None: + return getattr(name) raise - def __new__(typ, klass, dic=None): - # typ is not used at all - if not isinstance(klass,classobj): - raise TypeError("instance() first arg must be class") - if dic is None: - dic = {} - elif not isinstance(dic, dict): - raise TypeError("instance() second arg must be dictionary or None") - inst = object.__new__(instance) - dic['__class__'] = klass - obj_setattr(inst, '__dict__', dic) - return inst - - def __setattr__(self, name, value): - if name == '__dict__': - if not isinstance(value, dict): - raise TypeError("__dict__ must be set to a dictionary") - # for now, we need to copy things, because we are using - # the __dict__for our class as well. This will vanish! - value['__class__'] = self.__class__ - obj_setattr(inst, '__dict__', value) - elif name == '__class__': - if not isinstance(value, classobj): - raise TypeError("__class__ must be set to a class") - self.__dict__['__class__'] = value - else: - setattr = instance_getattr1(self, '__setattr__', exc=False) - if setattr is not None: - setattr(name, value) - else: - self.__dict__[name] = value - - def __delattr__(self, name): - # abuse __setattr__ to get the complaints :-) - # this is as funny as in CPython - if name in ('__dict__', '__class__'): - instance.__setattr__(self, name, None) - else: - delattr = instance_getattr1(self, '__delattr__', exc=False) - if delattr is not None: - delattr(name) - else: - try: - del self.__dict__[name] - except KeyError, ex: - raise AttributeError("%s instance has no attribute '%s'" % ( - self.__class__.__name__,name) ) - - def __repr__(self): - try: - func = instance_getattr1(self, '__repr__') - except AttributeError: - klass = self.__class__ - mod = get_class_module(klass) - return "<%s.%s instance at 0x%x>" % (mod, klass.__name__, uid(self)) - return func() + def __new__(typ, klass, dic=None): + # typ is not used at all + if not isinstance(klass,classobj): + raise TypeError("instance() first arg must be class") + if dic is None: + dic = {} + elif not isinstance(dic, dict): + raise TypeError("instance() second arg must be dictionary or None") + inst = object.__new__(instance) + dic['__class__'] = klass + obj_setattr(inst, '__dict__', dic) + return inst + + def __setattr__(self, name, value): + if name == '__dict__': + if not isinstance(value, dict): + raise TypeError("__dict__ must be set to a dictionary") + # for now, we need to copy things, because we are using + # the __dict__for our class as well. This will vanish! + value['__class__'] = self.__class__ + obj_setattr(inst, '__dict__', value) + elif name == '__class__': + if not isinstance(value, classobj): + raise TypeError("__class__ must be set to a class") + self.__dict__['__class__'] = value + else: + setattr = instance_getattr1(self, '__setattr__', exc=False) + if setattr is not None: + setattr(name, value) + else: + self.__dict__[name] = value + + def __delattr__(self, name): + # abuse __setattr__ to get the complaints :-) + # this is as funny as in CPython + if name in ('__dict__', '__class__'): + instance.__setattr__(self, name, None) + else: + delattr = instance_getattr1(self, '__delattr__', exc=False) + if delattr is not None: + delattr(name) + else: + try: + del self.__dict__[name] + except KeyError, ex: + raise AttributeError("%s instance has no attribute '%s'" % ( + self.__class__.__name__,name) ) + + def __repr__(self): + try: + func = instance_getattr1(self, '__repr__') + except AttributeError: + klass = self.__class__ + mod = get_class_module(klass) + return "<%s.%s instance at 0x%x>" % (mod, klass.__name__, uid(self)) + return func() def __str__(self): - try: - func = instance_getattr1(self, '__str__') - except AttributeError: - return instance.__repr__(self) - return func() - - def __hash__(self): - _eq = instance_getattr1(self, "__eq__", False) - _cmp = instance_getattr1(self, "__cmp__", False) - _hash = instance_getattr1(self, "__hash__", False) - if (_eq or _cmp) and not _hash: - raise TypeError("unhashable instance") - if _hash: - ret = _hash() - if not isinstance(ret, int): - raise TypeError("__hash__() should return an int") - else: - return id(self) - - def __len__(self): - ret = instance_getattr1(self,'__len__')() - if isinstance(ret, int): - if ret < 0: - raise ValueError("__len__() should return >= 0") - return ret - else: - raise TypeError("__len__() should return an int") - - def __getitem__(self, key): - if isinstance(key, slice) and key.step is None: - func = instance_getattr1(self, '__getslice__', False) - if func: - return func(key.start, key.end) - return instance_getattr1(self, '__getitem__')(key) - - def __setitem__(self, key, value): - if isinstance(key, slice) and key.step is None: - func = instance_getattr1(self, '__setslice__', False) - if func: - func(key.start, key.end, value) - instance_getattr1(self, '__setitem__')(key, value) - - def __delitem__(self, key): - if isinstance(key, slice) and key.step is None: - func = instance_getattr1(self, '__delslice__', False) - if func: - func(key.start, key.end) - instance_getattr1(self, '__delitem__')(key) - - def __contains__(self, obj): - func = instance_getattr1(self, '__contains__', False) - if func: - return bool(func(obj)) - # now do it ourselves - for x in self: - if x == obj: - return True - return False - - # unary operators - def __neg__(self): - return instance_getattr1(self, '__neg__')() - def __pos__(self): - return instance_getattr1(self, '__abs__')() - def __abs__(self): - return instance_getattr1(self, '__abs__')() - - # binary operators - for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): - exec(""" -def __%(op)s__(self, other): - coerced = coerce(self, other) - if coerced is None or coerced[0] is self: - func = instance_getattr1(self, '__%(op)s__', False) - if func: - return func(other) - return NotImplemented - else: - return operator.%(op2)s(self, other) - -def __r%(op)s__(self, other): - coerced = coerce(self, other) - if coerced is None or coerced[0] is self: - func = instance_getattr1(self, '__r%(op)s__', False) - if func: - return func(other) - return NotImplemented - else: - return operator.%(op2)s(other, self) -""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')]} - del op - + try: + func = instance_getattr1(self, '__str__') + except AttributeError: + return instance.__repr__(self) + return func() + + def __hash__(self): + _eq = instance_getattr1(self, "__eq__", False) + _cmp = instance_getattr1(self, "__cmp__", False) + _hash = instance_getattr1(self, "__hash__", False) + if (_eq or _cmp) and not _hash: + raise TypeError("unhashable instance") + if _hash: + ret = _hash() + if not isinstance(ret, int): + raise TypeError("__hash__() should return an int") + else: + return id(self) + + def __len__(self): + ret = instance_getattr1(self,'__len__')() + if isinstance(ret, int): + if ret < 0: + raise ValueError("__len__() should return >= 0") + return ret + else: + raise TypeError("__len__() should return an int") + + def __getitem__(self, key): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__getslice__', False) + if func: + return func(key.start, key.end) + return instance_getattr1(self, '__getitem__')(key) + + def __setitem__(self, key, value): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__setslice__', False) + if func: + func(key.start, key.end, value) + instance_getattr1(self, '__setitem__')(key, value) + + def __delitem__(self, key): + if isinstance(key, slice) and key.step is None: + func = instance_getattr1(self, '__delslice__', False) + if func: + func(key.start, key.end) + instance_getattr1(self, '__delitem__')(key) + + def __contains__(self, obj): + func = instance_getattr1(self, '__contains__', False) + if func: + return bool(func(obj)) + # now do it ourselves + for x in self: + if x == obj: + return True + return False + + # unary operators + def __neg__(self): + return instance_getattr1(self, '__neg__')() + def __pos__(self): + return instance_getattr1(self, '__abs__')() + def __abs__(self): + return instance_getattr1(self, '__abs__')() + + # binary operators + for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): + exec(""" +def __%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.%(op2)s(self, other) + +def __r%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__r%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.%(op2)s(other, self) +""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')]} + del op + From pedronis at codespeak.net Mon Jan 31 18:32:07 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 31 Jan 2005 18:32:07 +0100 (MET) Subject: [pypy-svn] r8764 - pypy/dist/pypy/lib Message-ID: <20050131173207.DF7CF27B71@code1.codespeak.net> Author: pedronis Date: Mon Jan 31 18:32:07 2005 New Revision: 8764 Modified: pypy/dist/pypy/lib/_classobj.py Log: inplace operators Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Mon Jan 31 18:32:07 2005 @@ -365,3 +365,16 @@ """) % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')]} del op + + # inplace operators + for op in 'mod and pow truediv lshift xor rshift floordiv div sub mul add or'.split(): + exec (""" +def __i%(op)s__(self, other): + func = instance_getattr1(self, '__i%(op)s__', False) + if func: + return func(other) + return NotImplemented + +""") % {"op": op} + del op + From tismer at codespeak.net Mon Jan 31 21:11:45 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 31 Jan 2005 21:11:45 +0100 (MET) Subject: [pypy-svn] r8772 - in pypy/dist/pypy: lib module tool translator Message-ID: <20050131201145.3030927B4D@code1.codespeak.net> Author: tismer Date: Mon Jan 31 21:11:44 2005 New Revision: 8772 Modified: pypy/dist/pypy/lib/_exceptions.py pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/tool/_enum_exceptions.py pypy/dist/pypy/tool/sourcetools.py pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/simplify.py pypy/dist/pypy/translator/transform.py Log: copied transform_dead_op_vars from transform to simplify. Made a few changes to provide both a view and a blocklist interface. Simplified sourcetools a bit. Modified geninterplevel to make sure that doc strings don't get indented the wrong way. Added a local numbering scheme for "real" names mangling: Every name gets its own counting. Regenerated exceptions which look nicer. Still improvable. Modified: pypy/dist/pypy/lib/_exceptions.py ============================================================================== --- pypy/dist/pypy/lib/_exceptions.py (original) +++ pypy/dist/pypy/lib/_exceptions.py Mon Jan 31 21:11:44 2005 @@ -100,13 +100,14 @@ # auto-generated code, please check carefully! def __str__(self): - argc = len(self.args) + args = self.args + argc = len(args) if argc == 0: return '' elif argc == 1: - return str(self.args[0]) + return str(args[0]) else: - return str(self.args) + return str(args) class StandardError(Exception): """Base class for all standard Python exceptions.""" @@ -140,11 +141,11 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'start=' + str(self.start), - 'reason=' + str(self.reason), - 'args=' + str(self.args), - 'end=' + str(self.end), - 'object=' + str(self.object), + 'start=' + str(getattr(self, 'start', None)), + 'reason=' + str(getattr(self, 'reason', None)), + 'args=' + str(getattr(self, 'args', None)), + 'end=' + str(getattr(self, 'end', None)), + 'object=' + str(getattr(self, 'object', None)), ]) return res @@ -156,13 +157,14 @@ # auto-generated code, please check carefully! def __str__(self): - argc = len(self.args) + args = self.args + argc = len(args) if argc == 0: return '' elif argc == 1: - return repr(self.args[0]) + return repr(args[0]) else: - return str(self.args) + return str(args) class Warning(Exception): """Base class for warning categories.""" @@ -197,10 +199,10 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'errno=' + str(self.errno), - 'args=' + str(self.args), - 'strerror=' + str(self.strerror), - 'filename=' + str(self.filename), + 'errno=' + str(getattr(self, 'errno', None)), + 'args=' + str(getattr(self, 'args', None)), + 'strerror=' + str(getattr(self, 'strerror', None)), + 'filename=' + str(getattr(self, 'filename', None)), ]) return res @@ -228,12 +230,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), + 'object=' + str(getattr(self, 'object', None)), + 'end=' + str(getattr(self, 'end', None)), + 'encoding=' + str(getattr(self, 'encoding', None)), + 'args=' + str(getattr(self, 'args', None)), + 'start=' + str(getattr(self, 'start', None)), + 'reason=' + str(getattr(self, 'reason', None)), ]) return res @@ -280,7 +282,7 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'args=' + str(self.args), + 'args=' + str(getattr(self, 'args', None)), ]) return res @@ -340,12 +342,12 @@ def __str__(self): # this is a bad hack, please supply an implementation res = ' '.join([ - 'object=' + str(self.object), - 'end=' + str(self.end), - 'encoding=' + str(self.encoding), - 'args=' + str(self.args), - 'start=' + str(self.start), - 'reason=' + str(self.reason), + 'object=' + str(getattr(self, 'object', None)), + 'end=' + str(getattr(self, 'end', None)), + 'encoding=' + str(getattr(self, 'encoding', None)), + 'args=' + str(getattr(self, 'args', None)), + 'start=' + str(getattr(self, 'start', None)), + 'reason=' + str(getattr(self, 'reason', None)), ]) return res Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Mon Jan 31 21:11:44 2005 @@ -100,11 +100,11 @@ _args_w = args_w defaults_w = () funcname = "__getitem__" - w_self_1, w_idx_3 = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) - return fastf_Exception___getitem__(space, w_self_1, w_idx_3) + w_self, w_idx = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) + return fastf_Exception___getitem__(space, w_self, w_idx) f_Exception___getitem__ = globals().pop("__getitem__") -def __getitem__(space, w_self_1, w_idx_3): +def __getitem__(space, w_self, w_idx): w_0=w_2=w_4=None @@ -112,8 +112,8 @@ while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_2 = space.getitem(w_0, w_idx_3) + w_0 = space.getattr(w_self, gs_args) + w_2 = space.getitem(w_0, w_idx) w_4 = w_2 goto = 2 @@ -128,15 +128,15 @@ ##SECTION## def __init__(space, *args_w): kwlist = ["self"] - w_args_2 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_Exception___init__(space, w_self_1, w_args_2) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___init__(space, w_self, w_args) f_Exception___init__ = globals().pop("__init__") -def __init__(space, w_self_1, w_args_2): +def __init__(space, w_self, w_args): w_0=w_3=None @@ -144,7 +144,7 @@ while True: if goto == 1: - w_0 = space.setattr(w_self_1, gs_args, w_args_2) + w_0 = space.setattr(w_self, gs_args, w_args) w_3 = space.w_None goto = 2 @@ -167,55 +167,53 @@ _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_Exception___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_Exception___str__(space, w_self) f_Exception___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): - w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=v9=w_self_11=w_15=w_16=None - w_5=w_self_10=w_12=w_13=w_14=None + w_args=w_argc=w_3=v4=w_args_1=w_argc_1=w_6=v7=w_args_3=w_10=w_5=None + w_args_2=w_8=w_9=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_argc_2 = space.len(w_0) - w_3 = space.eq(w_argc_2, gi_0) + w_args = space.getattr(w_self, gs_args) + w_argc = space.len(w_args) + w_3 = space.eq(w_argc, gi_0) v4 = space.is_true(w_3) if v4 == True: w_5 = gs__emptystr_ goto = 5 else: assert v4 == False - w_self_6, w_argc_7 = w_self_1, w_argc_2 + w_args_1, w_argc_1 = w_args, w_argc goto = 2 if goto == 2: - w_8 = space.eq(w_argc_7, gi_1) - v9 = space.is_true(w_8) - if v9 == True: - w_self_10 = w_self_6 + w_6 = space.eq(w_argc_1, gi_1) + v7 = space.is_true(w_6) + if v7 == True: + w_args_2 = w_args_1 goto = 3 else: - assert v9 == False - w_self_11 = w_self_6 + assert v7 == False + w_args_3 = w_args_1 goto = 4 if goto == 3: - w_12 = space.getattr(w_self_10, gs_args) - w_13 = space.getitem(w_12, gi_0) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) - w_5 = w_14 + w_8 = space.getitem(w_args_2, gi_0) + _tup = space.newtuple([w_8]) + w_9 = space.call(space.w_str, _tup) + w_5 = w_9 goto = 5 if goto == 4: - w_15 = space.getattr(w_self_11, gs_args) - _tup = space.newtuple([w_15]) - w_16 = space.call(space.w_str, _tup) - w_5 = w_16 + _tup = space.newtuple([w_args_3]) + w_10 = space.call(space.w_str, _tup) + w_5 = w_10 goto = 5 if goto == 5: @@ -225,7 +223,7 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 130 +## firstlineno 131 ##SECTION## # global declarations # global object gi_4 @@ -234,55 +232,55 @@ def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeTranslateError___init__(space, w_self_3, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___init__(space, w_self, w_args) f_UnicodeTranslateError___init__ = globals().pop("__init__") -def __init__(space, w_self_3, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None - w_13=w_14=w_15=w_16=None + w_argc=w_2=w_4=v5=w_6=w_self_1=w_args_1=w_7=w_8=w_9=w_10=w_11=None + w_12=w_13=w_14=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_4) + w_argc = space.len(w_args) + w_2 = space.setattr(w_self, gs_args, w_args) + w_4 = space.eq(w_argc, gi_4) v5 = space.is_true(w_4) if v5 == True: - w_self_6, w_args_7 = w_self_3, w_args_1 + w_self_1, w_args_1 = w_self, w_args goto = 2 else: assert v5 == False - w_8 = space.w_None + w_6 = space.w_None goto = 3 if goto == 2: - w_9 = space.getitem(w_args_7, gi_0) - w_10 = space.setattr(w_self_6, gs_object, w_9) - w_11 = space.getitem(w_args_7, gi_1) - w_12 = space.setattr(w_self_6, gs_start, w_11) - w_13 = space.getitem(w_args_7, gi_2) - w_14 = space.setattr(w_self_6, gs_end, w_13) - w_15 = space.getitem(w_args_7, gi_3) - w_16 = space.setattr(w_self_6, gs_reason, w_15) - w_8 = space.w_None + w_7 = space.getitem(w_args_1, gi_0) + w_8 = space.setattr(w_self_1, gs_object, w_7) + w_9 = space.getitem(w_args_1, gi_1) + w_10 = space.setattr(w_self_1, gs_start, w_9) + w_11 = space.getitem(w_args_1, gi_2) + w_12 = space.setattr(w_self_1, gs_end, w_11) + w_13 = space.getitem(w_args_1, gi_3) + w_14 = space.setattr(w_self_1, gs_reason, w_13) + w_6 = space.w_None goto = 3 if goto == 3: - return w_8 + return w_6 fastf_UnicodeTranslateError___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 140 +## firstlineno 141 ##SECTION## # global declarations # global object gs_start @@ -303,43 +301,43 @@ _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeTranslateError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeTranslateError___str__(space, w_self) f_UnicodeTranslateError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_16=w_res_17=w_18=None + w_15=w_16=w_res=w_18=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_start) + w_0 = space.getattr(w_self, gs_start, space.w_None) _tup = space.newtuple([w_0]) w_2 = space.call(space.w_str, _tup) w_3 = space.add(gs_start_, w_2) - w_4 = space.getattr(w_self_1, gs_reason) + w_4 = space.getattr(w_self, gs_reason, space.w_None) _tup = space.newtuple([w_4]) w_5 = space.call(space.w_str, _tup) w_6 = space.add(gs_reason_, w_5) - w_7 = space.getattr(w_self_1, gs_args) + w_7 = space.getattr(w_self, gs_args, space.w_None) _tup = space.newtuple([w_7]) w_8 = space.call(space.w_str, _tup) w_9 = space.add(gs_args_, w_8) - w_10 = space.getattr(w_self_1, gs_end) + w_10 = space.getattr(w_self, gs_end, space.w_None) _tup = space.newtuple([w_10]) w_11 = space.call(space.w_str, _tup) w_12 = space.add(gs_end_, w_11) - w_13 = space.getattr(w_self_1, gs_object) + w_13 = space.getattr(w_self, gs_object, space.w_None) _tup = space.newtuple([w_13]) w_14 = space.call(space.w_str, _tup) w_15 = space.add(gs_object_, w_14) w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) _tup = space.newtuple([w_16]) - w_res_17 = space.call(gbltinmethod_join, _tup) - w_18 = w_res_17 + w_res = space.call(gbltinmethod_join, _tup) + w_18 = w_res goto = 2 if goto == 2: @@ -349,61 +347,59 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 158 +## firstlineno 159 ##SECTION## def __str__(space, *args_w): kwlist = ["self"] _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_KeyError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_KeyError___str__(space, w_self) f_KeyError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): - w_0=w_argc_2=w_3=v4=w_self_6=w_argc_7=w_8=v9=w_self_11=w_15=w_16=None - w_5=w_self_10=w_12=w_13=w_14=None + w_args=w_argc=w_3=v4=w_args_1=w_argc_1=w_6=v7=w_args_3=w_10=w_5=None + w_args_2=w_8=w_9=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) - w_argc_2 = space.len(w_0) - w_3 = space.eq(w_argc_2, gi_0) + w_args = space.getattr(w_self, gs_args) + w_argc = space.len(w_args) + w_3 = space.eq(w_argc, gi_0) v4 = space.is_true(w_3) if v4 == True: w_5 = gs__emptystr_ goto = 5 else: assert v4 == False - w_self_6, w_argc_7 = w_self_1, w_argc_2 + w_args_1, w_argc_1 = w_args, w_argc goto = 2 if goto == 2: - w_8 = space.eq(w_argc_7, gi_1) - v9 = space.is_true(w_8) - if v9 == True: - w_self_10 = w_self_6 + w_6 = space.eq(w_argc_1, gi_1) + v7 = space.is_true(w_6) + if v7 == True: + w_args_2 = w_args_1 goto = 3 else: - assert v9 == False - w_self_11 = w_self_6 + assert v7 == False + w_args_3 = w_args_1 goto = 4 if goto == 3: - w_12 = space.getattr(w_self_10, gs_args) - w_13 = space.getitem(w_12, gi_0) - w_14 = space.repr(w_13) - w_5 = w_14 + w_8 = space.getitem(w_args_2, gi_0) + w_9 = space.repr(w_8) + w_5 = w_9 goto = 5 if goto == 4: - w_15 = space.getattr(w_self_11, gs_args) - _tup = space.newtuple([w_15]) - w_16 = space.call(space.w_str, _tup) - w_5 = w_16 + _tup = space.newtuple([w_args_3]) + w_10 = space.call(space.w_str, _tup) + w_5 = w_10 goto = 5 if goto == 5: @@ -413,98 +409,97 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 183 +## firstlineno 185 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_EnvironmentError___init__(space, w_self_3, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___init__(space, w_self, w_args) f_EnvironmentError___init__ = globals().pop("__init__") -def __init__(space, w_self_3, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=w_4=w_5=w_6=w_7=v8=w_self_12=w_args_13=w_argc_14=None - w_15=v17=w_self_21=w_args_22=w_argc_23=w_28=v29=w_32=w_self_30=None - w_args_31=w_33=w_34=w_35=w_36=w_37=w_38=w_self_18=w_args_19=w_argc_20=None - w_24=w_25=w_26=w_27=w_self_9=w_args_10=w_argc_11=w_16=None + w_argc=w_2=w_4=w_5=w_6=w_7=v8=w_self_2=w_args_2=w_argc_2=w_9=None + v11=w_self_4=w_args_4=w_argc_4=w_16=v17=w_18=w_self_5=w_args_5=None + w_19=w_20=w_21=w_22=w_23=w_24=w_self_3=w_args_3=w_argc_3=w_12=None + w_13=w_14=w_15=w_self_1=w_args_1=w_argc_1=w_10=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.setattr(w_self_3, gs_errno, space.w_None) - w_5 = space.setattr(w_self_3, gs_strerror, space.w_None) - w_6 = space.setattr(w_self_3, gs_filename, space.w_None) - w_7 = space.le(gi_2, w_argc_0) + w_argc = space.len(w_args) + w_2 = space.setattr(w_self, gs_args, w_args) + w_4 = space.setattr(w_self, gs_errno, space.w_None) + w_5 = space.setattr(w_self, gs_strerror, space.w_None) + w_6 = space.setattr(w_self, gs_filename, space.w_None) + w_7 = space.le(gi_2, w_argc) v8 = space.is_true(w_7) if v8 == True: - w_self_9, w_args_10, w_argc_11 = w_self_3, w_args_1, w_argc_0 + w_self_1, w_args_1, w_argc_1 = w_self, w_args, w_argc goto = 2 else: assert v8 == False - (w_self_12, w_args_13, w_argc_14, w_15) = (w_self_3, w_args_1, - w_argc_0, w_7) + w_self_2, w_args_2, w_argc_2, w_9 = w_self, w_args, w_argc, w_7 goto = 3 if goto == 2: - w_16 = space.le(w_argc_11, gi_3) - (w_self_12, w_args_13, w_argc_14, w_15) = (w_self_9, w_args_10, - w_argc_11, w_16) + w_10 = space.le(w_argc_1, gi_3) + (w_self_2, w_args_2, w_argc_2, w_9) = (w_self_1, w_args_1, + w_argc_1, w_10) goto = 3 if goto == 3: - v17 = space.is_true(w_15) - if v17 == True: - w_self_18, w_args_19, w_argc_20 = w_self_12, w_args_13, w_argc_14 + v11 = space.is_true(w_9) + if v11 == True: + w_self_3, w_args_3, w_argc_3 = w_self_2, w_args_2, w_argc_2 goto = 4 else: - assert v17 == False - w_self_21, w_args_22, w_argc_23 = w_self_12, w_args_13, w_argc_14 + assert v11 == False + w_self_4, w_args_4, w_argc_4 = w_self_2, w_args_2, w_argc_2 goto = 5 if goto == 4: - w_24 = space.getitem(w_args_19, gi_0) - w_25 = space.setattr(w_self_18, gs_errno, w_24) - w_26 = space.getitem(w_args_19, gi_1) - w_27 = space.setattr(w_self_18, gs_strerror, w_26) - w_self_21, w_args_22, w_argc_23 = w_self_18, w_args_19, w_argc_20 + w_12 = space.getitem(w_args_3, gi_0) + w_13 = space.setattr(w_self_3, gs_errno, w_12) + w_14 = space.getitem(w_args_3, gi_1) + w_15 = space.setattr(w_self_3, gs_strerror, w_14) + w_self_4, w_args_4, w_argc_4 = w_self_3, w_args_3, w_argc_3 goto = 5 if goto == 5: - w_28 = space.eq(w_argc_23, gi_3) - v29 = space.is_true(w_28) - if v29 == True: - w_self_30, w_args_31 = w_self_21, w_args_22 + w_16 = space.eq(w_argc_4, gi_3) + v17 = space.is_true(w_16) + if v17 == True: + w_self_5, w_args_5 = w_self_4, w_args_4 goto = 6 else: - assert v29 == False - w_32 = space.w_None + assert v17 == False + w_18 = space.w_None goto = 7 if goto == 6: - w_33 = space.getitem(w_args_31, gi_2) - w_34 = space.setattr(w_self_30, gs_filename, w_33) - w_35 = space.getitem(w_args_31, gi_0) - w_36 = space.getitem(w_args_31, gi_1) - w_37 = space.newtuple([w_35, w_36]) - w_38 = space.setattr(w_self_30, gs_args, w_37) - w_32 = space.w_None + w_19 = space.getitem(w_args_5, gi_2) + w_20 = space.setattr(w_self_5, gs_filename, w_19) + w_21 = space.getitem(w_args_5, gi_0) + w_22 = space.getitem(w_args_5, gi_1) + w_23 = space.newtuple([w_21, w_22]) + w_24 = space.setattr(w_self_5, gs_args, w_23) + w_18 = space.w_None goto = 7 if goto == 7: - return w_32 + return w_18 fastf_EnvironmentError___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 197 +## firstlineno 199 ##SECTION## # global declarations # global object gs_errno @@ -518,39 +513,39 @@ _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_EnvironmentError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_EnvironmentError___str__(space, w_self) f_EnvironmentError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): - w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res_14=None + w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_res=None w_15=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_errno) + w_0 = space.getattr(w_self, gs_errno, space.w_None) _tup = space.newtuple([w_0]) w_2 = space.call(space.w_str, _tup) w_3 = space.add(gs_errno_, w_2) - w_4 = space.getattr(w_self_1, gs_args) + w_4 = space.getattr(w_self, gs_args, space.w_None) _tup = space.newtuple([w_4]) w_5 = space.call(space.w_str, _tup) w_6 = space.add(gs_args_, w_5) - w_7 = space.getattr(w_self_1, gs_strerror) + w_7 = space.getattr(w_self, gs_strerror, space.w_None) _tup = space.newtuple([w_7]) w_8 = space.call(space.w_str, _tup) w_9 = space.add(gs_strerror_, w_8) - w_10 = space.getattr(w_self_1, gs_filename) + w_10 = space.getattr(w_self, gs_filename, space.w_None) _tup = space.newtuple([w_10]) w_11 = space.call(space.w_str, _tup) w_12 = space.add(gs_filename_, w_11) w_13 = space.newlist([w_3, w_6, w_9, w_12]) _tup = space.newtuple([w_13]) - w_res_14 = space.call(gbltinmethod_join, _tup) - w_15 = w_res_14 + w_res = space.call(gbltinmethod_join, _tup) + w_15 = w_res goto = 2 if goto == 2: @@ -560,64 +555,64 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 217 +## firstlineno 219 ##SECTION## # global declaration # global object gi_5 def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___init__(space, w_self_3, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___init__(space, w_self, w_args) f_UnicodeEncodeError___init__ = globals().pop("__init__") -def __init__(space, w_self_3, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None - w_13=w_14=w_15=w_16=w_17=w_18=None + w_argc=w_2=w_4=v5=w_6=w_self_1=w_args_1=w_7=w_8=w_9=w_10=w_11=None + w_12=w_13=w_14=w_15=w_16=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_5) + w_argc = space.len(w_args) + w_2 = space.setattr(w_self, gs_args, w_args) + w_4 = space.eq(w_argc, gi_5) v5 = space.is_true(w_4) if v5 == True: - w_self_6, w_args_7 = w_self_3, w_args_1 + w_self_1, w_args_1 = w_self, w_args goto = 2 else: assert v5 == False - w_8 = space.w_None + w_6 = space.w_None goto = 3 if goto == 2: - w_9 = space.getitem(w_args_7, gi_0) - w_10 = space.setattr(w_self_6, gs_encoding, w_9) - w_11 = space.getitem(w_args_7, gi_1) - w_12 = space.setattr(w_self_6, gs_object, w_11) - w_13 = space.getitem(w_args_7, gi_2) - w_14 = space.setattr(w_self_6, gs_start, w_13) - w_15 = space.getitem(w_args_7, gi_3) - w_16 = space.setattr(w_self_6, gs_end, w_15) - w_17 = space.getitem(w_args_7, gi_4) - w_18 = space.setattr(w_self_6, gs_reason, w_17) - w_8 = space.w_None + w_7 = space.getitem(w_args_1, gi_0) + w_8 = space.setattr(w_self_1, gs_encoding, w_7) + w_9 = space.getitem(w_args_1, gi_1) + w_10 = space.setattr(w_self_1, gs_object, w_9) + w_11 = space.getitem(w_args_1, gi_2) + w_12 = space.setattr(w_self_1, gs_start, w_11) + w_13 = space.getitem(w_args_1, gi_3) + w_14 = space.setattr(w_self_1, gs_end, w_13) + w_15 = space.getitem(w_args_1, gi_4) + w_16 = space.setattr(w_self_1, gs_reason, w_15) + w_6 = space.w_None goto = 3 if goto == 3: - return w_8 + return w_6 fastf_UnicodeEncodeError___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 228 +## firstlineno 230 ##SECTION## # global declarations # global object gs_encoding @@ -628,47 +623,47 @@ _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeEncodeError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeEncodeError___str__(space, w_self) f_UnicodeEncodeError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + w_15=w_16=w_17=w_18=w_19=w_res=w_21=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_object) + w_0 = space.getattr(w_self, gs_object, space.w_None) _tup = space.newtuple([w_0]) w_2 = space.call(space.w_str, _tup) w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self_1, gs_end) + w_4 = space.getattr(w_self, gs_end, space.w_None) _tup = space.newtuple([w_4]) w_5 = space.call(space.w_str, _tup) w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self_1, gs_encoding) + w_7 = space.getattr(w_self, gs_encoding, space.w_None) _tup = space.newtuple([w_7]) w_8 = space.call(space.w_str, _tup) w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self_1, gs_args) + w_10 = space.getattr(w_self, gs_args, space.w_None) _tup = space.newtuple([w_10]) w_11 = space.call(space.w_str, _tup) w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self_1, gs_start) + w_13 = space.getattr(w_self, gs_start, space.w_None) _tup = space.newtuple([w_13]) w_14 = space.call(space.w_str, _tup) w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self_1, gs_reason) + w_16 = space.getattr(w_self, gs_reason, space.w_None) _tup = space.newtuple([w_16]) w_17 = space.call(space.w_str, _tup) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join, _tup) - w_21 = w_res_20 + w_res = space.call(gbltinmethod_join, _tup) + w_21 = w_res goto = 2 if goto == 2: @@ -678,107 +673,107 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 268 +## firstlineno 270 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SyntaxError___init__(space, w_self_3, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___init__(space, w_self, w_args) f_SyntaxError___init__ = globals().pop("__init__") -def __init__(space, w_self_3, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=w_4=v5=w_self_9=w_args_10=w_argc_11=w_14=v15=w_18=None - w_self_16=w_args_17=w_19=w_20=w_21=w_22=w_23=w_24=w_25=w_26=w_27=None - w_28=w_29=w_30=w_self_6=w_args_7=w_argc_8=w_12=w_13=None + w_argc=w_2=w_4=v5=w_self_2=w_args_2=w_argc_2=w_8=v9=w_10=w_self_3=None + w_args_3=w_11=w_12=w_13=w_14=w_15=w_16=w_17=w_18=w_19=w_20=w_21=None + w_22=w_self_1=w_args_1=w_argc_1=w_6=w_7=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.ge(w_argc_0, gi_1) + w_argc = space.len(w_args) + w_2 = space.setattr(w_self, gs_args, w_args) + w_4 = space.ge(w_argc, gi_1) v5 = space.is_true(w_4) if v5 == True: - w_self_6, w_args_7, w_argc_8 = w_self_3, w_args_1, w_argc_0 + w_self_1, w_args_1, w_argc_1 = w_self, w_args, w_argc goto = 2 else: assert v5 == False - w_self_9, w_args_10, w_argc_11 = w_self_3, w_args_1, w_argc_0 + w_self_2, w_args_2, w_argc_2 = w_self, w_args, w_argc goto = 3 if goto == 2: - w_12 = space.getitem(w_args_7, gi_0) - w_13 = space.setattr(w_self_6, gs_msg, w_12) - w_self_9, w_args_10, w_argc_11 = w_self_6, w_args_7, w_argc_8 + w_6 = space.getitem(w_args_1, gi_0) + w_7 = space.setattr(w_self_1, gs_msg, w_6) + w_self_2, w_args_2, w_argc_2 = w_self_1, w_args_1, w_argc_1 goto = 3 if goto == 3: - w_14 = space.eq(w_argc_11, gi_2) - v15 = space.is_true(w_14) - if v15 == True: - w_self_16, w_args_17 = w_self_9, w_args_10 + w_8 = space.eq(w_argc_2, gi_2) + v9 = space.is_true(w_8) + if v9 == True: + w_self_3, w_args_3 = w_self_2, w_args_2 goto = 4 else: - assert v15 == False - w_18 = space.w_None + assert v9 == False + w_10 = space.w_None goto = 5 if goto == 4: - w_19 = space.getitem(w_args_17, gi_1) - w_20 = space.getitem(w_19, gi_0) - w_21 = space.setattr(w_self_16, gs_filename, w_20) - w_22 = space.getitem(w_args_17, gi_1) - w_23 = space.getitem(w_22, gi_1) - w_24 = space.setattr(w_self_16, gs_lineno, w_23) - w_25 = space.getitem(w_args_17, gi_1) - w_26 = space.getitem(w_25, gi_2) - w_27 = space.setattr(w_self_16, gs_offset, w_26) - w_28 = space.getitem(w_args_17, gi_1) - w_29 = space.getitem(w_28, gi_3) - w_30 = space.setattr(w_self_16, gs_text, w_29) - w_18 = space.w_None + w_11 = space.getitem(w_args_3, gi_1) + w_12 = space.getitem(w_11, gi_0) + w_13 = space.setattr(w_self_3, gs_filename, w_12) + w_14 = space.getitem(w_args_3, gi_1) + w_15 = space.getitem(w_14, gi_1) + w_16 = space.setattr(w_self_3, gs_lineno, w_15) + w_17 = space.getitem(w_args_3, gi_1) + w_18 = space.getitem(w_17, gi_2) + w_19 = space.setattr(w_self_3, gs_offset, w_18) + w_20 = space.getitem(w_args_3, gi_1) + w_21 = space.getitem(w_20, gi_3) + w_22 = space.setattr(w_self_3, gs_text, w_21) + w_10 = space.w_None goto = 5 if goto == 5: - return w_18 + return w_10 fastf_SyntaxError___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 280 +## firstlineno 282 ##SECTION## def __str__(space, *args_w): kwlist = ["self"] _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SyntaxError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SyntaxError___str__(space, w_self) f_SyntaxError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): - w_0=w_2=w_3=w_4=w_res_5=w_6=None + w_0=w_2=w_3=w_4=w_res=w_6=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_args) + w_0 = space.getattr(w_self, gs_args, space.w_None) _tup = space.newtuple([w_0]) w_2 = space.call(space.w_str, _tup) w_3 = space.add(gs_args_, w_2) w_4 = space.newlist([w_3]) _tup = space.newtuple([w_4]) - w_res_5 = space.call(gbltinmethod_join, _tup) - w_6 = w_res_5 + w_res = space.call(gbltinmethod_join, _tup) + w_6 = w_res goto = 2 if goto == 2: @@ -788,190 +783,190 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 294 +## firstlineno 296 ##SECTION## # global declaration # global object gs_code def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_4, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_SystemExit___init__(space, w_self_4, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_SystemExit___init__(space, w_self, w_args) f_SystemExit___init__ = globals().pop("__init__") -def __init__(space, w_self_4, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=v3=w_self_8=w_args_9=w_argc_10=w_12=w_13=v14=w_self_18=None - w_args_19=w_argc_20=w_23=v24=w_27=w_self_25=w_args_26=w_28=w_self_15=None - w_args_16=w_argc_17=w_21=w_22=w_self_5=w_args_6=w_argc_7=w_11=None + w_argc=w_2=v3=w_self_2=w_args_2=w_argc_2=w_6=w_7=v8=w_self_4=None + w_args_4=w_argc_4=w_11=v12=w_13=w_self_5=w_args_5=w_14=w_self_3=None + w_args_3=w_argc_3=w_9=w_10=w_self_1=w_args_1=w_argc_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.eq(w_argc_0, gi_0) + w_argc = space.len(w_args) + w_2 = space.eq(w_argc, gi_0) v3 = space.is_true(w_2) if v3 == True: - w_self_5, w_args_6, w_argc_7 = w_self_4, w_args_1, w_argc_0 + w_self_1, w_args_1, w_argc_1 = w_self, w_args, w_argc goto = 2 else: assert v3 == False - w_self_8, w_args_9, w_argc_10 = w_self_4, w_args_1, w_argc_0 + w_self_2, w_args_2, w_argc_2 = w_self, w_args, w_argc goto = 3 if goto == 2: - w_11 = space.setattr(w_self_5, gs_code, space.w_None) - w_self_8, w_args_9, w_argc_10 = w_self_5, w_args_6, w_argc_7 + w_5 = space.setattr(w_self_1, gs_code, space.w_None) + w_self_2, w_args_2, w_argc_2 = w_self_1, w_args_1, w_argc_1 goto = 3 if goto == 3: - w_12 = space.setattr(w_self_8, gs_args, w_args_9) - w_13 = space.eq(w_argc_10, gi_1) - v14 = space.is_true(w_13) - if v14 == True: - w_self_15, w_args_16, w_argc_17 = w_self_8, w_args_9, w_argc_10 + w_6 = space.setattr(w_self_2, gs_args, w_args_2) + w_7 = space.eq(w_argc_2, gi_1) + v8 = space.is_true(w_7) + if v8 == True: + w_self_3, w_args_3, w_argc_3 = w_self_2, w_args_2, w_argc_2 goto = 4 else: - assert v14 == False - w_self_18, w_args_19, w_argc_20 = w_self_8, w_args_9, w_argc_10 + assert v8 == False + w_self_4, w_args_4, w_argc_4 = w_self_2, w_args_2, w_argc_2 goto = 5 if goto == 4: - w_21 = space.getitem(w_args_16, gi_0) - w_22 = space.setattr(w_self_15, gs_code, w_21) - w_self_18, w_args_19, w_argc_20 = w_self_15, w_args_16, w_argc_17 + w_9 = space.getitem(w_args_3, gi_0) + w_10 = space.setattr(w_self_3, gs_code, w_9) + w_self_4, w_args_4, w_argc_4 = w_self_3, w_args_3, w_argc_3 goto = 5 if goto == 5: - w_23 = space.ge(w_argc_20, gi_2) - v24 = space.is_true(w_23) - if v24 == True: - w_self_25, w_args_26 = w_self_18, w_args_19 + w_11 = space.ge(w_argc_4, gi_2) + v12 = space.is_true(w_11) + if v12 == True: + w_self_5, w_args_5 = w_self_4, w_args_4 goto = 6 else: - assert v24 == False - w_27 = space.w_None + assert v12 == False + w_13 = space.w_None goto = 7 if goto == 6: - w_28 = space.setattr(w_self_25, gs_code, w_args_26) - w_27 = space.w_None + w_14 = space.setattr(w_self_5, gs_code, w_args_5) + w_13 = space.w_None goto = 7 if goto == 7: - return w_27 + return w_13 fastf_SystemExit___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__init__' -## firstlineno 329 +## firstlineno 331 ##SECTION## def __init__(space, *args_w): kwlist = ["self"] - w_args_1 = space.newtuple(list(args_w[1:])) + w_args = space.newtuple(list(args_w[1:])) _args_w = args_w[:1] defaults_w = () funcname = "__init__" - w_self_3, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeDecodeError___init__(space, w_self_3, w_args_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___init__(space, w_self, w_args) f_UnicodeDecodeError___init__ = globals().pop("__init__") -def __init__(space, w_self_3, w_args_1): +def __init__(space, w_self, w_args): - w_argc_0=w_2=w_4=v5=w_8=w_self_6=w_args_7=w_9=w_10=w_11=w_12=None - w_13=w_14=w_15=w_16=w_17=w_18=None + w_argc=w_2=w_4=v5=w_6=w_self_1=w_args_1=w_7=w_8=w_9=w_10=w_11=None + w_12=w_13=w_14=w_15=w_16=None goto = 1 # startblock while True: if goto == 1: - w_argc_0 = space.len(w_args_1) - w_2 = space.setattr(w_self_3, gs_args, w_args_1) - w_4 = space.eq(w_argc_0, gi_5) + w_argc = space.len(w_args) + w_2 = space.setattr(w_self, gs_args, w_args) + w_4 = space.eq(w_argc, gi_5) v5 = space.is_true(w_4) if v5 == True: - w_self_6, w_args_7 = w_self_3, w_args_1 + w_self_1, w_args_1 = w_self, w_args goto = 2 else: assert v5 == False - w_8 = space.w_None + w_6 = space.w_None goto = 3 if goto == 2: - w_9 = space.getitem(w_args_7, gi_0) - w_10 = space.setattr(w_self_6, gs_encoding, w_9) - w_11 = space.getitem(w_args_7, gi_1) - w_12 = space.setattr(w_self_6, gs_object, w_11) - w_13 = space.getitem(w_args_7, gi_2) - w_14 = space.setattr(w_self_6, gs_start, w_13) - w_15 = space.getitem(w_args_7, gi_3) - w_16 = space.setattr(w_self_6, gs_end, w_15) - w_17 = space.getitem(w_args_7, gi_4) - w_18 = space.setattr(w_self_6, gs_reason, w_17) - w_8 = space.w_None + w_7 = space.getitem(w_args_1, gi_0) + w_8 = space.setattr(w_self_1, gs_encoding, w_7) + w_9 = space.getitem(w_args_1, gi_1) + w_10 = space.setattr(w_self_1, gs_object, w_9) + w_11 = space.getitem(w_args_1, gi_2) + w_12 = space.setattr(w_self_1, gs_start, w_11) + w_13 = space.getitem(w_args_1, gi_3) + w_14 = space.setattr(w_self_1, gs_end, w_13) + w_15 = space.getitem(w_args_1, gi_4) + w_16 = space.setattr(w_self_1, gs_reason, w_15) + w_6 = space.w_None goto = 3 if goto == 3: - return w_8 + return w_6 fastf_UnicodeDecodeError___init__ = globals().pop("__init__") ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' ## function '__str__' -## firstlineno 340 +## firstlineno 342 ##SECTION## def __str__(space, *args_w): kwlist = ["self"] _args_w = args_w defaults_w = () funcname = "__str__" - w_self_1, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) - return fastf_UnicodeDecodeError___str__(space, w_self_1) + w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + return fastf_UnicodeDecodeError___str__(space, w_self) f_UnicodeDecodeError___str__ = globals().pop("__str__") -def __str__(space, w_self_1): +def __str__(space, w_self): w_0=w_2=w_3=w_4=w_5=w_6=w_7=w_8=w_9=w_10=w_11=w_12=w_13=w_14=None - w_15=w_16=w_17=w_18=w_19=w_res_20=w_21=None + w_15=w_16=w_17=w_18=w_19=w_res=w_21=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.getattr(w_self_1, gs_object) + w_0 = space.getattr(w_self, gs_object, space.w_None) _tup = space.newtuple([w_0]) w_2 = space.call(space.w_str, _tup) w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self_1, gs_end) + w_4 = space.getattr(w_self, gs_end, space.w_None) _tup = space.newtuple([w_4]) w_5 = space.call(space.w_str, _tup) w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self_1, gs_encoding) + w_7 = space.getattr(w_self, gs_encoding, space.w_None) _tup = space.newtuple([w_7]) w_8 = space.call(space.w_str, _tup) w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self_1, gs_args) + w_10 = space.getattr(w_self, gs_args, space.w_None) _tup = space.newtuple([w_10]) w_11 = space.call(space.w_str, _tup) w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self_1, gs_start) + w_13 = space.getattr(w_self, gs_start, space.w_None) _tup = space.newtuple([w_13]) w_14 = space.call(space.w_str, _tup) w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self_1, gs_reason) + w_16 = space.getattr(w_self, gs_reason, space.w_None) _tup = space.newtuple([w_16]) w_17 = space.call(space.w_str, _tup) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) _tup = space.newtuple([w_19]) - w_res_20 = space.call(gbltinmethod_join, _tup) - w_21 = w_res_20 + w_res = space.call(gbltinmethod_join, _tup) + w_21 = w_res goto = 2 if goto == 2: @@ -981,7 +976,7 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' ## function 'test_exceptions' -## firstlineno 1258 +## firstlineno 1261 ##SECTION## # global declarations # global object gfunc_test_exceptions @@ -1572,9 +1567,9 @@ _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs_exceptions) _doc = space.wrap("""Internal error in the Python interpreter. - - Please report this to the Python maintainer, along with the traceback, - the Python version, and the hardware/OS platform and version.""") + +Please report this to the Python maintainer, along with the traceback, +the Python version, and the hardware/OS platform and version.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_SystemError, _bases, _dic]) Modified: pypy/dist/pypy/tool/_enum_exceptions.py ============================================================================== --- pypy/dist/pypy/tool/_enum_exceptions.py (original) +++ pypy/dist/pypy/tool/_enum_exceptions.py Mon Jan 31 21:11:44 2005 @@ -43,8 +43,7 @@ f = sys.stdout import exceptions - for line in render_docstr(exceptions, ""): - print >> f, line + print >> f, render_docstr(exceptions, "") for exc in enumClassesInOrder(exceptions): name = exc.__name__ @@ -307,13 +306,14 @@ simple = arg1_methods and min(arg1_methods) == max(arg1_methods) if simple: yield "def __str__(self):" - yield " argc = len(self.args)" + yield " args = self.args" + yield " argc = len(args)" yield " if argc == 0:" yield " return ''" yield " elif argc == 1:" - yield " return %s(self.args[0])" % arg1_methods.pop() + yield " return %s(args[0])" % arg1_methods.pop() yield " else:" - yield " return str(self.args)" + yield " return str(args)" return # no idea how I should do this probe = exc(*working[0]) @@ -325,7 +325,7 @@ yield " # this is a bad hack, please supply an implementation" yield " res = ' '.join([" for key in dic.keys(): - yield " '%s=' + str(self.%s)," % (key, key) + yield " '%s=' + str(getattr(self, '%s', None))," % (key, key) yield " ])" yield " return res" Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Mon Jan 31 21:11:44 2005 @@ -1,21 +1,24 @@ # a couple of support functions which # help with generating Python source. -def render_docstr(func, indent_str='', closing_str='', q='"""', redo=True): - """ Render a docstring as a sequence of lines. - The argument is either a docstring or an object""" +def render_docstr(func, indent_str='', closing_str=''): + """ Render a docstring as a string of lines. + The argument is either a docstring or an object. + Note that we don't use a sequence, since we want + the docstring to line up left, reagrdless of + indentation.""" if type(func) is not str: doc = func.__doc__ else: doc = func if doc is None: - return [] - doc = indent_str + q + doc.replace(q, "\\"+q) + q + closing_str - doc2 = doc - if q in doc and redo: - doc2 = render_docstr(func, indent_str, closing_str, "'''", False) - if not redo: - return doc # recursion case + return None + compare = [] + for q in '"""', "'''": + txt = indent_str + q + doc.replace(q[0], "\\"+q[0]) + q + closing_str + compare.append(txt) + doc, doc2 = compare doc = (doc, doc2)[len(doc2) < len(doc)] - return [line for line in doc.split('\n')] + return doc + Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Jan 31 21:11:44 2005 @@ -44,10 +44,6 @@ from pypy.tool.sourcetools import render_docstr -# this thingy should be moved into a better place -# and be modified to work without annotation. -from pypy.translator.transform import transform_dead_op_vars - # ____________________________________________________________ def c_string(s): @@ -149,13 +145,20 @@ scorepos = n.rfind("_") if scorepos >= 0 and n[scorepos+1:].isdigit(): name = n[:scorepos] - ret = localnames.get(v.name) + # do individual numbering on named vars + thesenames = localnames.setdefault(name, {}) + ret = thesenames.get(v.name) if not ret: if wrapped: fmt = "w_%s_%d" else: fmt = "%s_%d" - localnames[v.name] = ret = fmt % (name, len(localnames)) + # don't use zero + if len(thesenames) == 0: + fmt = fmt[:-3] + thesenames[v.name] = ret = fmt % name + else: + thesenames[v.name] = ret = fmt % (name, len(thesenames)) return ret elif isinstance(v, Constant): return self.nameof(v.value, @@ -572,8 +575,8 @@ if cls.__doc__ is not None: sdoc = self.nameof("__doc__") - lines = list(render_docstr(cls, "_doc = space.wrap(", ")")) - self.initcode.extend(lines) + docstr = render_docstr(cls, "_doc = space.wrap(", ")") + self.initcode.append((docstr,)) # not splitted self.initcode.appendnew("space.setitem(_dic, %s, _doc)" % ( self.nameof("__doc__"),)) self.initcode.append('_bases = space.newtuple([%(bases)s])\n' @@ -760,8 +763,7 @@ # doc if self.moddict and self.moddict.get("__doc__"): doc = self.moddict["__doc__"] - for line in render_docstr(doc): - print >> f, line + print >> f, render_docstr(doc) print >> f # make sure it is not rendered again key = Constant(doc).key @@ -787,8 +789,16 @@ # footer print >> f, self.RPY_INIT_HEADER % info for codelines in self.initcode: - for codeline in codelines.split("\n"): - print >> f, " %s" % codeline + # keep docstrings unindented + indent = " " + if type(codelines) is tuple: + codelines = codelines[0].split("\n", 1) + codelines[0] = indent + codelines[0] + indent = "" + else: + codelines = codelines.split("\n") + for codeline in codelines: + print >> f, indent + codeline print >> f, self.RPY_INIT_FOOTER % info f.close() @@ -824,7 +834,7 @@ self.gen_global_declarations() # print header - doc_lines = render_docstr(func, " ") + docstr = render_docstr(func, " ") cname = self.nameof(func) assert cname.startswith('gfunc_') f_name = 'f_' + cname[6:] @@ -861,8 +871,8 @@ % (name, argstr)) print >> f, 'def %s(space, *args_w):' % (name,) - for line in doc_lines: - print >> f, line + if docstr is not None: + print >> f, docstr kwlist = ['"%s"' % var for var in func.func_code.co_varnames[:func.func_code.co_argcount]] print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) @@ -906,8 +916,8 @@ print >> f print >> f, fast_function_header - for line in doc_lines: - print >> f, line + if docstr is not None: + print >> f, docstr fast_locals = [arg for arg in localnames if arg not in fast_set] if fast_locals: @@ -955,13 +965,6 @@ allblocks = ordered_blocks(graph) nblocks = len(allblocks) - # HAACK - # I willmove that function to simplify.py, - # removing the dependency of annotated, - # which basically is just a list of blocks. - self.annotated = allblocks - transform_dead_op_vars(self) - blocknum = {} for block in allblocks: blocknum[block] = len(blocknum)+1 Modified: pypy/dist/pypy/translator/simplify.py ============================================================================== --- pypy/dist/pypy/translator/simplify.py (original) +++ pypy/dist/pypy/translator/simplify.py Mon Jan 31 21:11:44 2005 @@ -91,6 +91,7 @@ eliminate_empty_blocks(graph) remove_implicit_exceptions(graph) join_blocks(graph) + transform_dead_op_vars(graph) checkgraph(graph) def remove_direct_loops(graph): @@ -107,3 +108,106 @@ b.closeblock(Link(intermediate, link.target)) link.target = b traverse(visit, graph) + +def transform_dead_op_vars(graph): + """Remove dead operations and variables that are passed over a link + but not used in the target block. Input is a graph.""" + blocklist = [] + def visit(block): + if isinstance(block, Block): + blocklist.append(block) + traverse(visit, graph) + return transform_dead_op_vars_blocklist(blocklist) + +def transform_dead_op_vars_blocklist(blocklist): + """Remove dead operations and variables that are passed over a link + but not used in the target block. Input is a block list""" + # the set of operations that can safely be removed (no side effects) + CanRemove = {'newtuple': True, + 'newlist': True, + 'newdict': True, + 'is_': True, + 'is_true': True} + read_vars = {} # set of variables really used + variable_flow = {} # map {Var: list-of-Vars-it-depends-on} + + # compute variable_flow and an initial read_vars + for block in blocklist: + # figure out which variables are ever read + for op in block.operations: + if op.opname not in CanRemove: # mark the inputs as really needed + for arg in op.args: + read_vars[arg] = True + else: + # if CanRemove, only mark dependencies of the result + # on the input variables + deps = variable_flow.setdefault(op.result, []) + deps.extend(op.args) + + if isinstance(block.exitswitch, Variable): + read_vars[block.exitswitch] = True + + if block.exits: + for link in block.exits: + if link.target not in blocklist: + for arg, targetarg in zip(link.args, link.target.inputargs): + read_vars[arg] = True + read_vars[targetarg] = True + else: + for arg, targetarg in zip(link.args, link.target.inputargs): + deps = variable_flow.setdefault(targetarg, []) + deps.append(arg) + else: + # return and except blocks implicitely use their input variable(s) + for arg in block.inputargs: + read_vars[arg] = True + # an input block's inputargs should not be modified, even if some + # of the function's input arguments are not actually used + if block.isstartblock: + for arg in block.inputargs: + read_vars[arg] = True + + # flow read_vars backwards so that any variable on which a read_vars + # depends is also included in read_vars + pending = list(read_vars) + for var in pending: + for prevvar in variable_flow.get(var, []): + if prevvar not in read_vars: + read_vars[prevvar] = True + pending.append(prevvar) + + for block in blocklist: + + # look for removable operations whose result is never used + for i in range(len(block.operations)-1, -1, -1): + op = block.operations[i] + if op.result not in read_vars: + if op.opname in CanRemove: + del block.operations[i] + elif op.opname == 'simple_call': + # XXX we want to have a more effective and safe + # way to check if this operation has side effects + # ... + if op.args and isinstance(op.args[0], Constant): + func = op.args[0].value + if func is isinstance: + del block.operations[i] + + # look for output variables never used + # warning: this must be completely done *before* we attempt to + # remove the corresponding variables from block.inputargs! + # Otherwise the link.args get out of sync with the + # link.target.inputargs. + for link in block.exits: + assert len(link.args) == len(link.target.inputargs) + for i in range(len(link.args)-1, -1, -1): + if link.target.inputargs[i] not in read_vars: + del link.args[i] + # the above assert would fail here + + for block in blocklist: + # look for input variables never used + # The corresponding link.args have already been all removed above + for i in range(len(block.inputargs)-1, -1, -1): + if block.inputargs[i] not in read_vars: + del block.inputargs[i] Modified: pypy/dist/pypy/translator/transform.py ============================================================================== --- pypy/dist/pypy/translator/transform.py (original) +++ pypy/dist/pypy/translator/transform.py Mon Jan 31 21:11:44 2005 @@ -119,6 +119,9 @@ ## block.operations = operations +# XXX this function now lives in simplify, too. +# there, it accepts a graph or a block list as argument. +# Fell free to use it instead, and remove the function here. def transform_dead_op_vars(self): """Remove dead operations and variables that are passed over a link but not used in the target block.""" From sanxiyn at codespeak.net Sat Jan 29 07:37:09 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 29 Jan 2005 07:37:09 +0100 (MET) Subject: [pypy-svn] r8688 - in pypy/dist/pypy: appspace/test appspace/test/patched lib/test2 Message-ID: <20050129063709.85D3027B96@code1.codespeak.net> Author: sanxiyn Date: Sat Jan 29 07:37:09 2005 New Revision: 8688 Added: pypy/dist/pypy/lib/test2/autopath.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/autopath.py pypy/dist/pypy/lib/test2/builtin_functions_test.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/builtin_functions_test.py pypy/dist/pypy/lib/test2/cpy_test_types.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/cpy_test_types.py pypy/dist/pypy/lib/test2/no_test_stringmodule.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/no_test_stringmodule.py pypy/dist/pypy/lib/test2/support_tests.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/support_tests.py pypy/dist/pypy/lib/test2/test_cmathmodule.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_cmathmodule.py pypy/dist/pypy/lib/test2/test_complexobject.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_complexobject.py pypy/dist/pypy/lib/test2/test_exceptions.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_exceptions.py pypy/dist/pypy/lib/test2/test_file.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_file.py pypy/dist/pypy/lib/test2/test_md5.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_md5.py pypy/dist/pypy/lib/test2/test_sha.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_sha.py pypy/dist/pypy/lib/test2/test_struct.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_struct.py pypy/dist/pypy/lib/test2/test_sys.py - copied unchanged from r8687, pypy/dist/pypy/appspace/test/patched/test_sys.py Removed: pypy/dist/pypy/appspace/test/autopath.py pypy/dist/pypy/appspace/test/builtin_functions_test.py pypy/dist/pypy/appspace/test/cpy_test_types.py pypy/dist/pypy/appspace/test/no_test_stringmodule.py pypy/dist/pypy/appspace/test/patched/test_sys.py pypy/dist/pypy/appspace/test/support_tests.py pypy/dist/pypy/appspace/test/test_cmathmodule.py pypy/dist/pypy/appspace/test/test_complexobject.py pypy/dist/pypy/appspace/test/test_exceptions.py pypy/dist/pypy/appspace/test/test_file.py pypy/dist/pypy/appspace/test/test_md5.py pypy/dist/pypy/appspace/test/test_sha.py pypy/dist/pypy/appspace/test/test_struct.py Log: more file moves Deleted: /pypy/dist/pypy/appspace/test/autopath.py ============================================================================== --- /pypy/dist/pypy/appspace/test/autopath.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,114 +0,0 @@ -""" -self cloning, automatic path configuration - -copy this into any subdirectory of pypy from which scripts need -to be run, typically all of the test subdirs. -The idea is that any such script simply issues - - import autopath - -and this will make sure that the parent directory containing "pypy" -is in sys.path. - -If you modify the master "autopath.py" version (in pypy/tool/autopath.py) -you can directly run it which will copy itself on all autopath.py files -it finds under the pypy root directory. - -This module always provides these attributes: - - pypydir pypy root directory path - this_dir directory where this autopath.py resides - -""" - - -def __dirinfo(part): - """ return (partdir, this_dir) and insert parent of partdir - into sys.path. If the parent directories don't have the part - an EnvironmentError is raised.""" - - import sys, os - try: - head = this_dir = os.path.realpath(os.path.dirname(__file__)) - except NameError: - head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) - - while head: - partdir = head - head, tail = os.path.split(head) - if tail == part: - break - else: - raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) - - checkpaths = sys.path[:] - pypy_root = os.path.join(head, '') - - while checkpaths: - orig = checkpaths.pop() - if os.path.join(os.path.realpath(orig), '').startswith(pypy_root): - sys.path.remove(orig) - sys.path.insert(0, head) - - munged = {} - for name, mod in sys.modules.items(): - fn = getattr(mod, '__file__', None) - if '.' in name or not isinstance(fn, str): - continue - newname = os.path.splitext(os.path.basename(fn))[0] - if not newname.startswith(part + '.'): - continue - path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') - if path.startswith(pypy_root) and newname != part: - modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) - if newname != '__init__': - modpaths.append(newname) - modpath = '.'.join(modpaths) - if modpath not in sys.modules: - munged[modpath] = mod - - for name, mod in munged.iteritems(): - if name not in sys.modules: - sys.modules[name] = mod - if '.' in name: - prename = name[:name.rfind('.')] - postname = name[len(prename)+1:] - if prename not in sys.modules: - __import__(prename) - if not hasattr(sys.modules[prename], postname): - setattr(sys.modules[prename], postname, mod) - - return partdir, this_dir - -def __clone(): - """ clone master version of autopath.py into all subdirs """ - from os.path import join, walk - if not this_dir.endswith(join('pypy','tool')): - raise EnvironmentError("can only clone master version " - "'%s'" % join(pypydir, 'tool',_myname)) - - - def sync_walker(arg, dirname, fnames): - if _myname in fnames: - fn = join(dirname, _myname) - f = open(fn, 'rwb+') - try: - if f.read() == arg: - print "checkok", fn - else: - print "syncing", fn - f = open(fn, 'w') - f.write(arg) - finally: - f.close() - s = open(join(pypydir, 'tool', _myname), 'rb').read() - walk(pypydir, sync_walker, s) - -_myname = 'autopath.py' - -# set guaranteed attributes - -pypydir, this_dir = __dirinfo('pypy') - -if __name__ == '__main__': - __clone() Deleted: /pypy/dist/pypy/appspace/test/builtin_functions_test.py ============================================================================== --- /pypy/dist/pypy/appspace/test/builtin_functions_test.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,1234 +0,0 @@ -# Python test set -- built-in functions -import autopath -from pypy.interpreter.gateway import app2interp_temp - -def app_init_globals(): - ''' support functionality for these tests ''' - import __builtin__ as b - - from sets import Set - from support_tests import fcmp, have_unicode, TESTFN, unlink - - if not have_unicode: - b.basestring = str - - import sys, cStringIO - - class Squares: - - def __init__(self, max): - self.max = max - self.sofar = [] - - def __len__(self): return len(self.sofar) - - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n += 1 - return self.sofar[i] - - class StrSquares: - - def __init__(self, max): - self.max = max - self.sofar = [] - - def __len__(self): - return len(self.sofar) - - def __getitem__(self, i): - if not 0 <= i < self.max: - raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(str(n*n)) - n += 1 - return self.sofar[i] - - class BitBucket: - def write(self, line): - pass - - L = [ - ('0', 0), - ('1', 1), - ('9', 9), - ('10', 10), - ('99', 99), - ('100', 100), - ('314', 314), - (' 314', 314), - ('314 ', 314), - (' \t\t 314 \t\t ', 314), - (`sys.maxint`, sys.maxint), - (' 1x', ValueError), - (' 1 ', 1), - (' 1\02 ', ValueError), - ('', ValueError), - (' ', ValueError), - (' \t\t ', ValueError) - ] - if have_unicode: - L += [ - (unicode('0'), 0), - (unicode('1'), 1), - (unicode('9'), 9), - (unicode('10'), 10), - (unicode('99'), 99), - (unicode('100'), 100), - (unicode('314'), 314), - (unicode(' 314'), 314), - (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), - (unicode(' \t\t 314 \t\t '), 314), - (unicode(' 1x'), ValueError), - (unicode(' 1 '), 1), - (unicode(' 1\02 '), ValueError), - (unicode(''), ValueError), - (unicode(' '), ValueError), - (unicode(' \t\t '), ValueError), - (unichr(0x200), ValueError), - ] - b.Set = Set - b.fcmp = fcmp - b.have_unicode = have_unicode - b.TESTFN = TESTFN - b.unlink = unlink - b.sys = sys - b.cStringIO = cStringIO - b.Squares = Squares - b.StrSquares = StrSquares - b.BitBucket = BitBucket - b.L = L - - -class AppTestBuiltin: - objspacename = 'std' - - full_test = 1 - - def setup_class(cls): - app2interp_temp(app_init_globals)(cls.space) - - # we use "if 1:" to keep all method definitions indented, making - # it maximally easy to edit this file to pick and choose which - # ones to run (running everything takes 4 minutes or so...) - if 1: - def test_import(self): - __import__('sys') - __import__('time') - __import__('string') - raises(ImportError, __import__, 'spamspam') - raises(TypeError, __import__, 1, 2, 3, 4) - - def test_abs(self): - # int - assert abs(0) == 0 - assert abs(1234) == 1234 - assert abs(-1234) == 1234 - # float - assert abs(0.0) == 0.0 - assert abs(3.14) == 3.14 - assert abs(-3.14) == 3.14 - # long - assert abs(0L) == 0L - assert abs(1234L) == 1234L - assert abs(-1234L) == 1234L - # str - raises(TypeError, abs, 'a') - - def test_apply(self): - def f0(*args): - assert args == () - def f1(a1): - assert a1 == 1 - def f2(a1, a2): - assert a1 == 1 - assert a2 == 2 - def f3(a1, a2, a3): - assert a1 == 1 - assert a2 == 2 - assert a3 == 3 - apply(f0, ()) - apply(f1, (1,)) - apply(f2, (1, 2)) - apply(f3, (1, 2, 3)) - - # A PyCFunction that takes only positional parameters should allow - # an empty keyword dictionary to pass without a complaint, but - # raise a TypeError if the dictionary is non-empty. - apply(id, (1,), {}) - raises(TypeError, apply, id, (1,), {"foo": 1}) - raises(TypeError, apply) - raises(TypeError, apply, id, 42) - raises(TypeError, apply, id, (42,), 42) - - def test_callable(self): - assert callable(len) - def f(): pass - assert callable(f) - class C: - def meth(self): pass - assert callable(C) - x = C() - assert callable(x.meth) - assert not callable(x) - class D(C): - def __call__(self): pass - y = D() - assert callable(y) - y() - - def test_chr(self): - assert chr(32) == ' ' - assert chr(65) == 'A' - assert chr(97) == 'a' - assert chr(0xff) == '\xff' - raises(ValueError, chr, 256) - raises(TypeError, chr) - - def test_cmp(self): - assert cmp(-1, 1) == -1 - assert cmp(1, -1) == 1 - assert cmp(1, 1) == 0 - ''' TODO XXX Circular objects not handled yet - # verify that circular objects are handled - a = []; a.append(a) - b = []; b.append(b) - from UserList import UserList - c = UserList(); c.append(c) - assert cmp(a, b) == 0 - assert cmp(b, c) == 0 - assert cmp(c, a) == 0 - assert cmp(a, c) == 0 - # okay, now break the cycles - a.pop(); b.pop(); c.pop() - ''' - raises(TypeError, cmp) - - ''' TODO: XXX Coerce is not implemented - def test_coerce(self): - assert not fcmp(coerce(1, 1.1), (1.0, 1.1)) - assert coerce(1, 1L) == (1L, 1L) - assert not fcmp(coerce(1L, 1.1), (1.0, 1.1)) - raises(TypeError, coerce) - class BadNumber: - def __coerce__(self, other): - raise ValueError - raises(ValueError, coerce, 42, BadNumber()) - raises(OverflowError, coerce, 0.5, int("12345" * 1000)) - ''' - - def test_compile(self): - compile('print 1\n', '', 'exec') - bom = '\xef\xbb\xbf' - compile(bom + 'print 1\n', '', 'exec') - raises(TypeError, compile) - raises(ValueError, compile, - 'print 42\n', '', 'badmode') - raises(ValueError, compile, - 'print 42\n', '', 'single', 0xff) - if have_unicode: - compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') - - def test_delattr(self): - import sys - sys.spam = 1 - delattr(sys, 'spam') - raises(TypeError, delattr) - - def test_dir(self): - x = 1 - assert 'x' in dir() - import sys - assert 'modules' in dir(sys) - raises(TypeError, dir, 42, 42) - - def test_divmod(self): - assert divmod(12, 7) == (1, 5) - assert divmod(-12, 7) == (-2, 2) - assert divmod(12, -7) == (-2, -2) - assert divmod(-12, -7) == (1, -5) - - assert divmod(12L, 7L) == (1L, 5L) - assert divmod(-12L, 7L) == (-2L, 2L) - assert divmod(12L, -7L) == (-2L, -2L) - assert divmod(-12L, -7L) == (1L, -5L) - - assert divmod(12, 7L) == (1, 5L) - assert divmod(-12, 7L) == (-2, 2L) - assert divmod(12L, -7) == (-2L, -2) - assert divmod(-12L, -7) == (1L, -5) - - assert not fcmp(divmod(3.25, 1.0), (3.0, 0.25)) - assert not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)) - assert not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)) - assert not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)) - - raises(TypeError, divmod) - - ''' XXX TODO No eval() support yet - def test_eval(self): - assert eval('1+1') == 2 - assert eval(' 1+1\n') == 2 - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - assert eval('a', globals) == 1 - assert eval('a', globals, locals) == 1 - assert eval('b', globals, locals) == 200 - assert eval('c', globals, locals) == 300 - if have_unicode: - assert eval(unicode('1+1')) == 2 - assert eval(unicode(' 1+1\n')) == 2 - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - if have_unicode: - assert eval(unicode('a'), globals) == 1 - assert eval(unicode('a'), globals, locals) == 1 - assert eval(unicode('b'), globals, locals) == 200 - assert eval(unicode('c'), globals, locals) == 300 - bom = '\xef\xbb\xbf' - assert eval(bom + 'a', globals, locals) == 1 - assert eval(unicode('u"\xc3\xa5"', 'utf8'), globals) == ( - unicode('\xc3\xa5', 'utf8')) - raises(TypeError, eval) - raises(TypeError, eval, ()) - - '\'' XXX TODO: Figure out later - # Done outside of the method test_z to get the correct scope - z = 0 - f = open(TESTFN, 'w') - f.write('z = z+1\n') - f.write('z = z*2\n') - f.close() - execfile(TESTFN) - - def test_execfile(self): - globals = {'a': 1, 'b': 2} - locals = {'b': 200, 'c': 300} - - assert self.__class__.z == 2 - globals['z'] = 0 - execfile(TESTFN, globals) - assert globals['z'] == 2 - locals['z'] = 0 - execfile(TESTFN, globals, locals) - assert locals['z'] == 2 - unlink(TESTFN) - raises(TypeError, execfile) - import os - raises(IOError, execfile, os.curdir) - raises(IOError, execfile, "I_dont_exist") - '\'' - ''' - - ''' XXX TODO: filter does NOT rely on __getitem__, but rather on - __iter__; it appears to me that the following two tests, - therefore, pass in CPython only because of the accident that - in that implementation str does not define __iter__ (while - list and tuple do, in 2.3). Probably best to substitute - most of these tests with more appropriate ones! - ''' - def test_filter(self): - assert filter(lambda c: 'a' <= c <= 'z', 'Hello World') == ( - 'elloorld') - assert (filter(None, [1, 'hello', [], [3], '', None, 9, 0]) - ) == [1, 'hello', [3], 9] - assert filter(lambda x: x > 0, [1, -3, 9, 0, 2]) == ( - [1, 9, 2]) - assert filter(None, Squares(10)) == ( - [1, 4, 9, 16, 25, 36, 49, 64, 81]) - assert filter(lambda x: x%2, Squares(10)) == ( - [1, 9, 25, 49, 81]) - def identity(item): - return 1 - filter(identity, Squares(5)) - raises(TypeError, filter) - ''' XXX rest of test disabled as above explained - class BadSeq(object): - def __getitem__(self, index): - if index<4: - return 42 - raise ValueError - raises(ValueError, filter, lambda x: x, BadSeq()) - def badfunc(): - pass - raises(TypeError, filter, badfunc, range(5)) - - # test bltinmodule.c::filtertuple() - assert filter(None, (1, 2)) == (1, 2) - assert filter(lambda x: x>=3, (1, 2, 3, 4)) == (3, 4) - raises(TypeError, filter, 42, (1, 2)) - - # test bltinmodule.c::filterstring() - assert filter(None, "12") == "12" - assert filter(lambda x: x>="3", "1234") == "34" - raises(TypeError, filter, 42, "12") - class badstr(str): - def __getitem__(self, index): - raise ValueError - raises(ValueError, filter, - lambda x: x >="3", badstr("1234")) - - class badstr2(str): - def __getitem__(self, index): - return 42 - raises(TypeError, filter, - lambda x: x >=42, badstr2("1234")) - - class weirdstr(str): - def __getitem__(self, index): - return weirdstr(2*str.__getitem__(self, index)) - assert filter(lambda x: x>="33", weirdstr("1234")) == ( - "3344") - - class shiftstr(str): - def __getitem__(self, index): - return chr(ord(str.__getitem__(self, index))+1) - assert filter(lambda x: x>="3", shiftstr("1234")) == "345" - - if have_unicode: - # test bltinmodule.c::filterunicode() - assert filter(None, unicode("12")) == unicode("12") - assert filter(lambda x: x>="3", unicode("1234")) == ( - unicode("34")) - raises(TypeError, filter, 42, unicode("12")) - raises(ValueError, filter, lambda x: x >="3", - badstr(unicode("1234"))) - - class badunicode(unicode): - def __getitem__(self, index): - return 42 - raises(TypeError, filter, lambda x: x >=42, - badunicode("1234")) - - class weirdunicode(unicode): - def __getitem__(self, index): - return weirdunicode(2*unicode.__getitem__(self, index)) - assert ( - filter(lambda x: x>=unicode("33"), weirdunicode("1234"))) == ( - unicode("3344")) - - class shiftunicode(unicode): - def __getitem__(self, index): - return unichr(ord(unicode.__getitem__(self, index))+1) - assert ( - filter(lambda x: x>=unicode("3"), shiftunicode("1234"))) == ( - unicode("345") - ) - - def test_filter_subclasses(self): - # test that filter() never returns tuple, str or unicode subclasses - # and that the result always goes through __getitem__ - funcs = (None, bool, lambda x: True) - class tuple2(tuple): - def __getitem__(self, index): - return 2*tuple.__getitem__(self, index) - class str2(str): - def __getitem__(self, index): - return 2*str.__getitem__(self, index) - inputs = { - tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, - str2: {"": "", "123": "112233"} - } - if have_unicode: - class unicode2(unicode): - def __getitem__(self, index): - return 2*unicode.__getitem__(self, index) - inputs[unicode2] = { - unicode(): unicode(), - unicode("123"): unicode("112233") - } - - for (cls, inps) in inputs.iteritems(): - for (inp, exp) in inps.iteritems(): - # make sure the output goes through __getitem__ - # even if func is None - assert ( - filter(funcs[0], cls(inp))) == ( - filter(funcs[1], cls(inp)) - ) - for func in funcs: - outp = filter(func, cls(inp)) - assert outp == exp - assert not isinstance(outp, cls) - ''' - - def test_float(self): - assert float(3.14) == 3.14 - assert float(314) == 314.0 - assert float(314L) == 314.0 - assert float(" 3.14 ") == 3.14 - if have_unicode: - assert float(unicode(" 3.14 ")) == 3.14 - assert float(unicode( - " \u0663.\u0661\u0664 ",'raw-unicode-escape')) == 3.14 - - def test_getattr(self): - import sys - assert getattr(sys, 'stdout') is sys.stdout - raises(TypeError, getattr, sys, 1) - raises(TypeError, getattr, sys, 1, "foo") - raises(TypeError, getattr) - if have_unicode: - raises(UnicodeError, getattr, sys, - unichr(sys.maxunicode)) - - def test_hasattr(self): - import sys - assert hasattr(sys, 'stdout') - raises(TypeError, hasattr, sys, 1) - raises(TypeError, hasattr) - if have_unicode: - raises(UnicodeError, hasattr, sys, - unichr(sys.maxunicode)) - - def test_hash(self): - hash(None) - assert hash(1) == hash(1L) - assert hash(1) == hash(1.0) - hash('spam') - if have_unicode: - assert hash('spam') == hash(unicode('spam')) - hash((0,1,2,3)) - def f(): pass - raises(TypeError, hash, []) - raises(TypeError, hash, {}) - - def test_hex(self): - assert hex(16) == '0x10' - assert hex(16L) == '0x10L' - assert len(hex(-1)) == len(hex(sys.maxint)) - assert hex(-16) in ('0xfffffff0', '0xfffffffffffffff0') - assert hex(-16L) == '-0x10L' - raises(TypeError, hex, {}) - - def test_id(self): - id(None) - id(1) - id(1L) - id(1.0) - id('spam') - id((0,1,2,3)) - id([0,1,2,3]) - id({'spam': 1, 'eggs': 2, 'ham': 3}) - - # Test input() later, together with raw_input - - def test_int(self): - assert int(314) == 314 - assert int(3.14) == 3 - assert int(314L) == 314 - # Check that conversion from float truncates towards zero - assert int(-3.14) == -3 - assert int(3.9) == 3 - assert int(-3.9) == -3 - assert int(3.5) == 3 - assert int(-3.5) == -3 - # Different base: - assert int("10",16) == 16L - if have_unicode: - assert int(unicode("10"),16) == 16L - # Test conversion from strings and various anomalies - for s, v in L: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - assert int(ss) == vv - except v: - pass - - s = `-1-sys.maxint` - assert int(s)+1 == -sys.maxint - # should return long - ''' XXX TODO: Longs not well supported yet - int(s[1:]) - - # should return long - x = int(1e100) - assert isinstance(x, long) - x = int(-1e100) - assert isinstance(x, long) - ''' - - # SF bug 434186: 0x80000000/2 != 0x80000000>>1. - # Worked by accident in Windows release build, but failed in - # debug build. Failed in all Linux builds. - x = -1-sys.maxint - assert x >> 1 == x//2 - - raises(ValueError, int, '123\0') - raises(ValueError, int, '53', 40) - - ''' XXX TODO: Longs not supported yet - x = int('1' * 600) - assert isinstance(x, long) - - if have_unicode: - x = int(unichr(0x661) * 600) - assert isinstance(x, long) - - raises(TypeError, int, 1, 12) - ''' - - assert int('0123', 0) == 83 - - def test_intern(self): - raises(TypeError, intern) - s = "never interned before" - assert intern(s) is s - s2 = s.swapcase().swapcase() - assert intern(s2) is s - - def test_iter(self): - raises(TypeError, iter) - raises(TypeError, iter, 42, 42) - lists = [("1", "2"), ["1", "2"], "12"] - if have_unicode: - lists.append(unicode("12")) - for l in lists: - i = iter(l) - assert i.next() == '1' - assert i.next() == '2' - raises(StopIteration, i.next) - - def test_isinstance(self): - class C: - pass - class D(C): - pass - class E: - pass - c = C() - d = D() - e = E() - assert isinstance(c, C) - assert isinstance(d, C) - assert not isinstance(e, C) - assert not isinstance(c, D) - assert not isinstance('foo', E) - raises(TypeError, isinstance, E, 'foo') - raises(TypeError, isinstance) - - def test_issubclass(self): - class C: - pass - class D(C): - pass - class E: - pass - c = C() - d = D() - e = E() - assert issubclass(D, C) - assert issubclass(C, C) - assert not issubclass(C, D) - raises(TypeError, issubclass, 'foo', E) - raises(TypeError, issubclass, E, 'foo') - raises(TypeError, issubclass) - - def test_len(self): - assert len('123') == 3 - assert len(()) == 0 - assert len((1, 2, 3, 4)) == 4 - assert len([1, 2, 3, 4]) == 4 - assert len({}) == 0 - assert len({'a':1, 'b': 2}) == 2 - class BadSeq: - def __len__(self): - raise ValueError - raises(ValueError, len, BadSeq()) - - if 1: - - def test_list(self): - assert list([]) == [] - l0_3 = [0, 1, 2, 3] - l0_3_bis = list(l0_3) - assert l0_3 == l0_3_bis - assert l0_3 is not l0_3_bis - assert list(()) == [] - assert list((0, 1, 2, 3)) == [0, 1, 2, 3] - assert list('') == [] - assert list('spam') == ['s', 'p', 'a', 'm'] - - ''' XXX TODO: disabled for now -- far too slow! - if sys.maxint == 0x7fffffff: - # This test can currently only work on 32-bit machines. - # XXX If/when PySequence_Length() returns a ssize_t, it should be - # XXX re-enabled. - # Verify clearing of bug #556025. - # This assumes that the max data size (sys.maxint) == max - # address size this also assumes that the address size is at - # least 4 bytes with 8 byte addresses, the bug is not well - # tested - # - # Note: This test is expected to SEGV under Cygwin 1.3.12 or - # earlier due to a newlib bug. See the following mailing list - # thread for the details: - - # http://sources.redhat.com/ml/newlib/2002/msg00369.html - raises(MemoryError, list, xrange(sys.maxint // 2)) - ''' - - ''' XXX TODO: disabled for now -- long not yet well supported - def test_long(self): - assert long(314) == 314L - assert long(3.14) == 3L - assert long(314L) == 314L - # Check that conversion from float truncates towards zero - assert long(-3.14) == -3L - assert long(3.9) == 3L - assert long(-3.9) == -3L - assert long(3.5) == 3L - assert long(-3.5) == -3L - assert long("-3") == -3L - if have_unicode: - assert long(unicode("-3")) == -3L - # Different base: - assert long("10",16) == 16L - if have_unicode: - assert long(unicode("10"),16) == 16L - # Check conversions from string (same test set as for int(), and then some) - LL = [ - ('1' + '0'*20, 10L**20), - ('1' + '0'*100, 10L**100) - ] - L2 = L[:] - if have_unicode: - L2 += [ - (unicode('1') + unicode('0')*20, 10L**20), - (unicode('1') + unicode('0')*100, 10L**100), - ] - for s, v in L2 + LL: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - assert long(ss) == long(vv) - except v: - pass - - raises(ValueError, long, '123\0') - raises(ValueError, long, '53', 40) - raises(TypeError, long, 1, 12) - ''' - - def test_map(self): - assert ( - map(None, 'hello world')) == ( - ['h','e','l','l','o',' ','w','o','r','l','d'] - ) - assert ( - map(None, 'abcd', 'efg')) == ( - [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)] - ) - assert ( - map(None, range(10))) == ( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - ) - assert ( - map(lambda x: x*x, range(1,4))) == ( - [1, 4, 9] - ) - try: - from math import sqrt - except ImportError: - def sqrt(x): - return pow(x, 0.5) - assert ( - map(lambda x: map(sqrt,x), [[16, 4], [81, 9]])) == ( - [[4.0, 2.0], [9.0, 3.0]] - ) - assert ( - map(lambda x, y: x+y, [1,3,2], [9,1,4])) == ( - [10, 4, 6] - ) - - def plus(*v): - accu = 0 - for i in v: accu = accu + i - return accu - assert ( - map(plus, [1, 3, 7])) == ( - [1, 3, 7] - ) - assert ( - map(plus, [1, 3, 7], [4, 9, 2])) == ( - [1+4, 3+9, 7+2] - ) - assert ( - map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])) == ( - [1+4+1, 3+9+1, 7+2+0] - ) - assert ( - map(None, Squares(10))) == ( - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ) - assert ( - map(int, Squares(10))) == ( - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ) - assert ( - map(None, Squares(3), Squares(2))) == ( - [(0,0), (1,1), (4,None)] - ) - assert ( - map(max, Squares(3), Squares(2))) == ( - [0, 1, 4] - ) - raises(TypeError, map) - raises(TypeError, map, lambda x: x, 42) - assert map(None, [42]) == [42] - class BadSeq: - def __getitem__(self, index): - raise ValueError - raises(ValueError, map, lambda x: x, BadSeq()) - - def test_max(self): - assert max('123123') == '3' - assert max(1, 2, 3) == 3 - assert max((1, 2, 3, 1, 2, 3)) == 3 - assert max([1, 2, 3, 1, 2, 3]) == 3 - - assert max(1, 2L, 3.0) == 3.0 - assert max(1L, 2.0, 3) == 3 - assert max(1.0, 2, 3L) == 3L - - def test_min(self): - assert min('123123') == '1' - assert min(1, 2, 3) == 1 - assert min((1, 2, 3, 1, 2, 3)) == 1 - assert min([1, 2, 3, 1, 2, 3]) == 1 - - assert min(1, 2L, 3.0) == 1 - assert min(1L, 2.0, 3) == 1L - assert min(1.0, 2, 3L) == 1.0 - - raises(TypeError, min) - raises(TypeError, min, 42) - raises(ValueError, min, ()) - class BadSeq: - def __getitem__(self, index): - raise ValueError - raises(ValueError, min, BadSeq()) - ''' XXX TODO: some weird bug in pypy here -- fix later - class BadNumber: - def __cmp__(self, other): - raise ValueError - raises(ValueError, min, (42, BadNumber())) - ''' - - def test_oct(self): - assert oct(100) == '0144' - assert oct(100L) == '0144L' - assert oct(-100) in ('037777777634', '01777777777777777777634') - assert oct(-100L) == '-0144L' - raises(TypeError, oct, ()) - - - def test_open(self): - def write_testfile(): - # NB the first 4 lines are also used to test input and raw_input, below - fp = open(TESTFN, 'w') - try: - fp.write('1+1\n') - fp.write('1+1\n') - fp.write('The quick brown fox jumps over the lazy dog') - fp.write('.\n') - fp.write('Dear John\n') - fp.write('XXX'*100) - fp.write('YYY'*100) - finally: - fp.close() - write_testfile() - fp = open(TESTFN, 'r') - try: - assert fp.readline(4) == '1+1\n' - assert fp.readline(4) == '1+1\n' - assert fp.readline() == 'The quick brown fox jumps over the lazy dog.\n' - assert fp.readline(4) == 'Dear' - assert fp.readline(100) == ' John\n' - assert fp.read(300) == 'XXX'*100 - assert fp.read(1000) == 'YYY'*100 - finally: - fp.close() - unlink(TESTFN) - - def test_ord(self): - assert ord(' ') == 32 - assert ord('A') == 65 - assert ord('a') == 97 - raises(TypeError, ord, 42) - if have_unicode: - assert ord(unichr(sys.maxunicode)) == sys.maxunicode - raises(TypeError, ord, unicode("12")) - - def test_pow(self): - assert pow(0,0) == 1 - assert pow(0,1) == 0 - assert pow(1,0) == 1 - assert pow(1,1) == 1 - - assert pow(2,0) == 1 - assert pow(2,10) == 1024 - assert pow(2,20) == 1024*1024 - assert pow(2,30) == 1024*1024*1024 - - assert pow(-2,0) == 1 - assert pow(-2,1) == -2 - assert pow(-2,2) == 4 - assert pow(-2,3) == -8 - - assert pow(0L,0) == 1 - assert pow(0L,1) == 0 - assert pow(1L,0) == 1 - assert pow(1L,1) == 1 - - assert pow(2L,0) == 1 - assert pow(2L,10) == 1024 - assert pow(2L,20) == 1024*1024 - assert pow(2L,30) == 1024*1024*1024 - - assert pow(-2L,0) == 1 - assert pow(-2L,1) == -2 - assert pow(-2L,2) == 4 - assert pow(-2L,3) == -8 - - assert round(pow(0.,0) - 1., 7) == 0 - assert round(pow(0.,1) - 0., 7) == 0 - assert round(pow(1.,0) - 1., 7) == 0 - assert round(pow(1.,1) - 1., 7) == 0 - - assert round(pow(2.,0) - 1., 7) == 0 - assert round(pow(2.,10) - 1024., 7) == 0 - assert round(pow(2.,20) - 1024.*1024., 7) == 0 - assert round(pow(2.,30) - 1024.*1024.*1024., 7) == 0 - - assert round(pow(-2.,0) - 1., 7) == 0 - assert round(pow(-2.,1) - -2., 7) == 0 - assert round(pow(-2.,2) - 4., 7) == 0 - assert round(pow(-2.,3) - -8., 7) == 0 - - for x in 2, 2L, 2.0: - for y in 10, 10L, 10.0: - for z in 1000, 1000L, 1000.0: - if isinstance(x, float) or \ - isinstance(y, float) or \ - isinstance(z, float): - raises(TypeError, pow, x, y, z) - else: - assert round(pow(x, y, z) - 24.0, 7) == 0 - - raises(TypeError, pow, -1, -2, 3) - raises(ValueError, pow, 1, 2, 0) - raises(TypeError, pow, -1L, -2L, 3L) - raises(ValueError, pow, 1L, 2L, 0L) - raises(ValueError, pow, -342.43, 0.234) - - raises(TypeError, pow) - - def test_range(self): - assert range(3) == [0, 1, 2] - assert range(1, 5) == [1, 2, 3, 4] - assert range(0) == [] - assert range(-3) == [] - assert range(1, 10, 3) == [1, 4, 7] - assert range(5, -5, -3) == [5, 2, -1, -4] - - # Now test range() with longs - assert range(-2**100) == [] - assert range(0, -2**100) == [] - assert range(0, 2**100, -1) == [] - assert range(0, 2**100, -1) == [] - - a = long(10 * sys.maxint) - b = long(100 * sys.maxint) - c = long(50 * sys.maxint) - - assert range(a, a+2) == [a, a+1] - assert range(a+2, a, -1L) == [a+2, a+1] - assert range(a+4, a, -2) == [a+4, a+2] - - seq = range(a, b, c) - assert a in seq - assert b not in seq - assert len(seq) == 2 - - seq = range(b, a, -c) - assert b in seq - assert a not in seq - assert len(seq) == 2 - - seq = range(-a, -b, -c) - assert -a in seq - assert -b not in seq - assert len(seq) == 2 - - raises(TypeError, range) - raises(TypeError, range, 1, 2, 3, 4) - raises(ValueError, range, 1, 2, 0) - - # Reject floats when it would require PyLongs to represent. - # (smaller floats still accepted, but deprecated) - raises(TypeError, range, 1e100, 1e101, 1e101) - - raises(TypeError, range, 0, "spam") - raises(TypeError, range, 0, 42, "spam") - - raises(OverflowError, range, -sys.maxint, sys.maxint) - raises(OverflowError, range, 0, 2*sys.maxint) - - ''' XXX TODO: input and raw_input not supported yet - def test_input_and_raw_input(self): - self.write_testfile() - fp = open(TESTFN, 'r') - savestdin = sys.stdin - savestdout = sys.stdout # Eats the echo - try: - sys.stdin = fp - sys.stdout = BitBucket() - assert input() == 2 - assert input('testing\n') == 2 - assert raw_input() == 'The quick brown fox jumps over the lazy dog.' - assert raw_input('testing\n') == 'Dear John' - sys.stdin = cStringIO.StringIO("NULL\0") - raises(TypeError, input, 42, 42) - sys.stdin = cStringIO.StringIO(" 'whitespace'") - assert input() == 'whitespace' - sys.stdin = cStringIO.StringIO() - raises(EOFError, input) - del sys.stdout - raises(RuntimeError, input, 'prompt') - del sys.stdin - raises(RuntimeError, input, 'prompt') - finally: - sys.stdin = savestdin - sys.stdout = savestdout - fp.close() - unlink(TESTFN) - ''' - - def test_reduce(self): - assert reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') == 'abc' - assert ( - reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], [])) == ( - ['a','c','d','w'] - ) - assert reduce(lambda x, y: x*y, range(2,8), 1) == 5040 - assert ( - reduce(lambda x, y: x*y, range(2,21), 1L)) == ( - 2432902008176640000L - ) - assert reduce(lambda x, y: x+y, Squares(10)) == 285 - assert reduce(lambda x, y: x+y, Squares(10), 0) == 285 - assert reduce(lambda x, y: x+y, Squares(0), 0) == 0 - raises(TypeError, reduce) - raises(TypeError, reduce, 42, 42) - raises(TypeError, reduce, 42, 42, 42) - assert reduce(42, "1") == "1" # func is never called with one item - assert reduce(42, "", "1") == "1" # func is never called with one item - raises(TypeError, reduce, 42, (42, 42)) - - class BadSeq: - def __getitem__(self, index): - raise ValueError - raises(ValueError, reduce, 42, BadSeq()) - - ''' XXX TODO: we don't have reload yet - def test_reload(self): - import sys - reload(sys) - import string - reload(string) - ## import sys - ## raises(ImportError, reload, sys) - ''' - - def test_repr(self): - assert repr('') == '\'\'' - assert repr(0) == '0' - assert repr(0L) == '0L' - assert repr(()) == '()' - assert repr([]) == '[]' - assert repr({}) == '{}' - ''' XXX TODO: we don't yet support "circular" objects! - a = [] - a.append(a) - assert repr(a) == '[[...]]' - a = {} - a[0] = a - assert repr(a) == '{0: {...}}' - ''' - - def test_round(self): - assert round(0.0) == 0.0 - assert round(1.0) == 1.0 - assert round(10.0) == 10.0 - assert round(1000000000.0) == 1000000000.0 - assert round(1e20) == 1e20 - - assert round(-1.0) == -1.0 - assert round(-10.0) == -10.0 - assert round(-1000000000.0) == -1000000000.0 - assert round(-1e20) == -1e20 - - assert round(0.1) == 0.0 - assert round(1.1) == 1.0 - assert round(10.1) == 10.0 - assert round(1000000000.1) == 1000000000.0 - - assert round(-1.1) == -1.0 - assert round(-10.1) == -10.0 - assert round(-1000000000.1) == -1000000000.0 - - assert round(0.9) == 1.0 - assert round(9.9) == 10.0 - assert round(999999999.9) == 1000000000.0 - - assert round(-0.9) == -1.0 - assert round(-9.9) == -10.0 - assert round(-999999999.9) == -1000000000.0 - - assert round(-8.0, -1) == -10.0 - - raises(TypeError, round) - - def test_setattr(self): - setattr(sys, 'spam', 1) - assert sys.spam == 1 - raises(TypeError, setattr, sys, 1, 'spam') - raises(TypeError, setattr) - - def test_str(self): - assert str('') == '' - assert str(0) == '0' - assert str(0L) == '0' - assert str(()) == '()' - assert str([]) == '[]' - assert str({}) == '{}' - ''' XXX TODO: we don't yet support "circular" objects! - a = [] - a.append(a) - assert str(a) == '[[...]]' - a = {} - a[0] = a - assert str(a) == '{0: {...}}' - ''' - - def test_sum(self): - assert sum([]) == 0 - assert sum(range(2,8)) == 27 - assert sum(iter(range(2,8))) == 27 - assert sum(Squares(10)) == 285 - assert sum(iter(Squares(10))) == 285 - assert sum([[1], [2], [3]], []) == [1, 2, 3] - - raises(TypeError, sum) - raises(TypeError, sum, 42) - raises(TypeError, sum, ['a', 'b', 'c']) - raises(TypeError, sum, ['a', 'b', 'c'], '') - raises(TypeError, sum, [[1], [2], [3]]) - raises(TypeError, sum, [{2:3}]) - raises(TypeError, sum, [{2:3}]*2, {2:3}) - - class BadSeq: - def __getitem__(self, index): - raise ValueError - raises(ValueError, sum, BadSeq()) - - def test_tuple(self): - assert tuple(()) == () - t0_3 = (0, 1, 2, 3) - t0_3_bis = tuple(t0_3) - ''' XXX TODO: tuples are immutable -- returns same object in CPython ''' - #self.assert_(t0_3 is t0_3_bis) - assert t0_3 == t0_3_bis - assert tuple([]) == () - assert tuple([0, 1, 2, 3]) == (0, 1, 2, 3) - assert tuple('') == () - assert tuple('spam') == ('s', 'p', 'a', 'm') - - def test_type(self): - assert type('') == type('123') - assert type('') != type(()) - - def test_unichr(self): - if have_unicode: - assert unichr(32) == unicode(' ') - assert unichr(65) == unicode('A') - assert unichr(97) == unicode('a') - assert ( - unichr(sys.maxunicode)) == ( - unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape') - ) - raises(ValueError, unichr, sys.maxunicode+1) - raises(TypeError, unichr) - - def test_vars(self): - def get_vars_f0(): - return vars() - def get_vars_f2(): - get_vars_f0() - a = 1 - b = 2 - return vars() - assert Set(vars()) == Set(dir()) - import sys - assert Set(vars(sys)) == Set(dir(sys)) - assert get_vars_f0() == {} - assert get_vars_f2() == {'a': 1, 'b': 2} - raises(TypeError, vars, 42, 42) - raises(TypeError, vars, 42) - - def test_zip(self): - a = (1, 2, 3) - b = (4, 5, 6) - t = [(1, 4), (2, 5), (3, 6)] - assert zip(a, b) == t - b = [4, 5, 6] - assert zip(a, b) == t - b = (4, 5, 6, 7) - assert zip(a, b) == t - class I: - def __getitem__(self, i): - if i < 0 or i > 2: raise IndexError - return i + 4 - assert zip(a, I()) == t - raises(TypeError, zip) - raises(TypeError, zip, None) - class G: - pass - raises(TypeError, zip, a, G()) - - # Make sure zip doesn't try to allocate a billion elements for the - # result list when one of its arguments doesn't say how long it is. - # A MemoryError is the most likely failure mode. - class SequenceWithoutALength: - def __getitem__(self, i): - if i == 5: - raise IndexError - else: - return i - s = SequenceWithoutALength() - assert ( - zip(s, xrange(2**30))) == ( - [(x,x) for x in s] - ) - - class BadSeq: - def __getitem__(self, i): - if i == 5: - raise ValueError - else: - return i - raises(ValueError, zip, BadSeq(), BadSeq()) Deleted: /pypy/dist/pypy/appspace/test/cpy_test_types.py ============================================================================== --- /pypy/dist/pypy/appspace/test/cpy_test_types.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,787 +0,0 @@ -# Python test set -- part 6, built-in types -# Slightly edited version for PyPy. - -from support_tests import * - -print '6. Built-in types' - -print '6.1 Truth value testing' -if None: raise TestFailed, 'None is true instead of false' -if 0: raise TestFailed, '0 is true instead of false' -if 0L: raise TestFailed, '0L is true instead of false' -if 0.0: raise TestFailed, '0.0 is true instead of false' -if '': raise TestFailed, '\'\' is true instead of false' -if (): raise TestFailed, '() is true instead of false' -if []: raise TestFailed, '[] is true instead of false' -if {}: raise TestFailed, '{} is true instead of false' -if not 1: raise TestFailed, '1 is false instead of true' -if not 1L: raise TestFailed, '1L is false instead of true' -if not 1.0: raise TestFailed, '1.0 is false instead of true' -if not 'x': raise TestFailed, '\'x\' is false instead of true' -if not (1, 1): raise TestFailed, '(1, 1) is false instead of true' -if not [1]: raise TestFailed, '[1] is false instead of true' -if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true' -def f(): pass -class C: pass -import sys -x = C() -if not f: raise TestFailed, 'f is false instead of true' -if not C: raise TestFailed, 'C is false instead of true' -if not sys: raise TestFailed, 'sys is false instead of true' -if not x: raise TestFailed, 'x is false instead of true' - -print '6.2 Boolean operations' -if 0 or 0: raise TestFailed, '0 or 0 is true instead of false' -if 1 and 1: pass -else: raise TestFailed, '1 and 1 is false instead of false' -if not 1: raise TestFailed, 'not 1 is true instead of false' - -print '6.3 Comparisons' -if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass -else: raise TestFailed, 'int comparisons failed' -if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass -else: raise TestFailed, 'long int comparisons failed' -if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass -else: raise TestFailed, 'float comparisons failed' -if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass -else: raise TestFailed, 'string comparisons failed' -if 0 in [0] and 0 not in [1]: pass -else: raise TestFailed, 'membership test failed' -if None is None and [] is not []: pass -else: raise TestFailed, 'identity test failed' - - -print '6.3.1 Conversion errors' -try: float('') -except ValueError: pass -else: raise TestFailed, "float('') didn't raise ValueError" - -try: float('5\0') -except ValueError: pass -else: raise TestFailed, "float('5\0') didn't raise ValueError" - -print '6.3.2 Division errors' -try: 5.0 / 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError" - -try: 5.0 // 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError" - -try: 5.0 % 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError" - -try: 5L / 0 -except ZeroDivisionError: pass -else: raise TestFailed, "5L / 0 didn't raise ZeroDivisionError" - -try: 5 / 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError" - -try: 5 // 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError" - -try: 5 % 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError" - -print '6.4 Numeric types (mostly conversions)' -if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons' -if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons' -if -1 != -1L or -1 != -1.0 or -1L != -1.0: - raise TestFailed, 'int/long/float value not equal' -# calling built-in types without argument must return 0 -if int() != 0: raise TestFailed, 'int() does not return 0' -if long() != 0L: raise TestFailed, 'long() does not return 0L' -if float() != 0.0: raise TestFailed, 'float() does not return 0.0' -if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass -else: raise TestFailed, 'int() does not round properly' -if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass -else: raise TestFailed, 'long() does not round properly' -if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass -else: raise TestFailed, 'float() does not work properly' -print '6.4.1 32-bit integers' -if 12 + 24 != 36: raise TestFailed, 'int op' -if 12 + (-24) != -12: raise TestFailed, 'int op' -if (-12) + 24 != 12: raise TestFailed, 'int op' -if (-12) + (-24) != -36: raise TestFailed, 'int op' -if not 12 < 24: raise TestFailed, 'int op' -if not -24 < -12: raise TestFailed, 'int op' -# Test for a particular bug in integer multiply -xsize, ysize, zsize = 238, 356, 4 -if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): - raise TestFailed, 'int mul commutativity' -# And another. -m = -sys.maxint - 1 -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - prod = divisor * j - if prod != m: - raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m) - if type(prod) is not int: - raise TestFailed, ("expected type(prod) to be int, not %r" % - type(prod)) -# Check for expected * overflow to long. -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) -# Check for expected * overflow to long. -m = sys.maxint -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor + 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) - -print '6.4.2 Long integers' -if 12L + 24L != 36L: raise TestFailed, 'long op' -if 12L + (-24L) != -12L: raise TestFailed, 'long op' -if (-12L) + 24L != 12L: raise TestFailed, 'long op' -if (-12L) + (-24L) != -36L: raise TestFailed, 'long op' -if not 12L < 24L: raise TestFailed, 'long op' -if not -24L < -12L: raise TestFailed, 'long op' -x = sys.maxint -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)+1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' -x = -x -if int(long(x)) != x: raise TestFailed, 'long op' -x = x-1 -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)-1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' - -try: 5 << -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift <<' - -try: 5L << -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift <<' - -try: 5 >> -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift >>' - -try: 5L >> -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift >>' - -print '6.4.3 Floating point numbers' -if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op' -if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op' -if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op' -if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op' -if not 12.0 < 24.0: raise TestFailed, 'float op' -if not -24.0 < -12.0: raise TestFailed, 'float op' - -print '6.5 Sequence types' - -print '6.5.1 Strings' -if len('') != 0: raise TestFailed, 'len(\'\')' -if len('a') != 1: raise TestFailed, 'len(\'a\')' -if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')' -if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation' -if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3' -if 0*'abcde' != '': raise TestFailed, 'string repetition 0*' -if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string' -if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass -else: raise TestFailed, 'in/not in string' -x = 'x'*103 -if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug' - -#extended slices for strings -a = '0123456789' -vereq(a[::], a) -vereq(a[::2], '02468') -vereq(a[1::2], '13579') -vereq(a[::-1],'9876543210') -vereq(a[::-2], '97531') -vereq(a[3::-2], '31') -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], '02468') - -if have_unicode: - a = unicode('0123456789', 'ascii') - vereq(a[::], a) - vereq(a[::2], unicode('02468', 'ascii')) - vereq(a[1::2], unicode('13579', 'ascii')) - vereq(a[::-1], unicode('9876543210', 'ascii')) - vereq(a[::-2], unicode('97531', 'ascii')) - vereq(a[3::-2], unicode('31', 'ascii')) - vereq(a[-100:100:], a) - vereq(a[100:-100:-1], a[::-1]) - vereq(a[-100L:100L:2L], unicode('02468', 'ascii')) - - -print '6.5.2 Tuples' -# calling built-in types without argument must return empty -if tuple() != (): raise TestFailed,'tuple() does not return ()' -if len(()) != 0: raise TestFailed, 'len(())' -if len((1,)) != 1: raise TestFailed, 'len((1,))' -if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))' -if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation' -if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3' -if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*' -if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple' -if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass -else: raise TestFailed, 'in/not in tuple' -try: ()[0] -except IndexError: pass -else: raise TestFailed, "tuple index error didn't raise IndexError" -x = () -x += () -if x != (): raise TestFailed, 'tuple inplace add from () to () failed' -x += (1,) -if x != (1,): raise TestFailed, 'tuple resize from () failed' - -# extended slicing - subscript only for tuples -a = (0,1,2,3,4) -vereq(a[::], a) -vereq(a[::2], (0,2,4)) -vereq(a[1::2], (1,3)) -vereq(a[::-1], (4,3,2,1,0)) -vereq(a[::-2], (4,2,0)) -vereq(a[3::-2], (3,1)) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], (0,2,4)) - -# Check that a specific bug in _PyTuple_Resize() is squashed. -def f(): - for i in range(1000): - yield i -vereq(list(tuple(f())), range(1000)) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO: this fails with PyPy because overriding __getitem__ will -# really override what the sequence iterator returns -#class T(tuple): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(T((1,2))).next(), 1) - -print '6.5.3 Lists' -# calling built-in types without argument must return empty -if list() != []: raise TestFailed,'list() does not return []' -if len([]) != 0: raise TestFailed, 'len([])' -if len([1,]) != 1: raise TestFailed, 'len([1,])' -if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])' -if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation' -if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3' -if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L' -if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*' -if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*' -if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list' -if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass -else: raise TestFailed, 'in/not in list' -a = [1, 2, 3, 4, 5] -a[:-1] = a -if a != [1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (head)" -a = [1, 2, 3, 4, 5] -a[1:] = a -if a != [1, 1, 2, 3, 4, 5]: - raise TestFailed, "list self-slice-assign (tail)" -a = [1, 2, 3, 4, 5] -a[1:-1] = a -if a != [1, 1, 2, 3, 4, 5, 5]: - raise TestFailed, "list self-slice-assign (center)" -try: [][0] -except IndexError: pass -else: raise TestFailed, "list index error didn't raise IndexError" -try: [][0] = 5 -except IndexError: pass -else: raise TestFailed, "list assignment index error didn't raise IndexError" -try: [].pop() -except IndexError: pass -else: raise TestFailed, "empty list.pop() didn't raise IndexError" -try: [1].pop(5) -except IndexError: pass -else: raise TestFailed, "[1].pop(5) didn't raise IndexError" -try: [][0:1] = 5 -except TypeError: pass -else: raise TestFailed, "bad list slice assignment didn't raise TypeError" -try: [].extend(None) -except TypeError: pass -else: raise TestFailed, "list.extend(None) didn't raise TypeError" -a = [1, 2, 3, 4] -a *= 0 -if a != []: - raise TestFailed, "list inplace repeat" - -a = [] -a[:] = tuple(range(10)) -if a != range(10): - raise TestFailed, "assigning tuple to slice" - -print '6.5.3a Additional list operations' -a = [0,1,2,3,4] -a[0L] = 1 -a[1L] = 2 -a[2L] = 3 -if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]' -a[0] = 5 -a[1] = 6 -a[2] = 7 -if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]' -a[-2L] = 88 -a[-1L] = 99 -if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]' -a[-2] = 8 -a[-1] = 9 -if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]' -a[:2] = [0,4] -a[-3:] = [] -a[1:1] = [1,2,3] -if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment' -a[ 1L : 4L] = [7,8,9] -if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints' -del a[1:4] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=range(0,5) -del a[1L:4L] -if a != [0,4]: raise TestFailed, 'list slice deletion' -del a[0L] -if a != [4]: raise TestFailed, 'list item deletion [0]' -del a[-1L] -if a != []: raise TestFailed, 'list item deletion [-1]' -a=[] -a.append(0) -a.append(1) -a.append(2) -if a != [0,1,2]: raise TestFailed, 'list append' -a.insert(0, -2) -a.insert(1, -1) -a.insert(2,0) -if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert' -b = a[:] -b.insert(-2, "foo") -b.insert(-200, "left") -b.insert(200, "right") -if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2' -# a = [-2,-1,0,0,1,2] -if a.count(0) != 2: raise TestFailed, ' list count' -if a.index(0) != 2: raise TestFailed, 'list index' -if a.index(0,2) != 2: raise TestFailed, 'list index, start argument' -if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' -if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument' -if a.index(0,3) != 3: raise TestFailed, 'list index, start argument' -if a.index(0,-3) != 3: raise TestFailed, 'list index, -start argument' -if a.index(0,3,4) != 3: raise TestFailed, 'list index, stop argument' -if a.index(0,-3,-2) != 3: raise TestFailed, 'list index, -stop argument' -if a.index(0,-4*sys.maxint,4*sys.maxint) != 2: - raise TestFailed, 'list index, -maxint, maxint argument' -try: - a.index(0, 4*sys.maxint,-4*sys.maxint) -except ValueError: - pass -else: - raise TestFailed, 'list index, maxint,-maxint argument' - -try: - a.index(2,0,-10) -except ValueError: - pass -else: - raise TestFailed, 'list index, very -stop argument' -a.remove(0) -try: - a.index(2,0,4) -except ValueError: - pass -else: - raise TestFailed, 'list index, stop argument.' -if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove' -a.reverse() -if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse' -a.sort() -if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort' -def revcmp(a, b): return cmp(b, a) -a.sort(revcmp) -if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func' -# The following dumps core in unpatched Python 1.5: -def myComparison(x,y): - return cmp(x%3, y%7) -z = range(12) -z.sort(myComparison) - -try: z.sort(2) -except TypeError: pass -else: raise TestFailed, 'list sort compare function is not callable' - -''' XXX TODO: add detection of list modification during sort -def selfmodifyingComparison(x,y): - z.append(1) - return cmp(x, y) -try: z.sort(selfmodifyingComparison) -except ValueError: pass -else: raise TestFailed, 'modifying list during sort' -''' - -try: z.sort(lambda x, y: 's') -except TypeError: pass -else: raise TestFailed, 'list sort compare function does not return int' - -# Test extreme cases with long ints -a = [0,1,2,3,4] -if a[ -pow(2,128L): 3 ] != [0,1,2]: - raise TestFailed, "list slicing with too-small long integer" -if a[ 3: pow(2,145L) ] != [3,4]: - raise TestFailed, "list slicing with too-large long integer" - -# extended slicing - -# subscript -a = [0,1,2,3,4] -vereq(a[::], a) -vereq(a[::2], [0,2,4]) -vereq(a[1::2], [1,3]) -vereq(a[::-1], [4,3,2,1,0]) -vereq(a[::-2], [4,2,0]) -vereq(a[3::-2], [3,1]) -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], [0,2,4]) -vereq(a[1000:2000:2], []) -vereq(a[-1000:-2000:-2], []) -# deletion -del a[::2] -vereq(a, [1,3]) -a = range(5) -del a[1::2] -vereq(a, [0,2,4]) -a = range(5) -del a[1::-2] -vereq(a, [0,2,3,4]) -a = range(10) -del a[::1000] -vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9]) -# assignment -a = range(10) -a[::2] = [-1]*5 -vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]) -a = range(10) -a[::-4] = [10]*3 -vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]) -a = range(4) -a[::-1] = a -vereq(a, [3, 2, 1, 0]) -a = range(10) -b = a[:] -c = a[:] -a[2:3] = ["two", "elements"] -b[slice(2,3)] = ["two", "elements"] -c[2:3:] = ["two", "elements"] -vereq(a, b) -vereq(a, c) -a = range(10) -a[::2] = tuple(range(5)) -vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9]) - -# Verify that __getitem__ overrides are not recognized by __iter__ -# XXX TODO same as class T(tuple) above -#class L(list): -# def __getitem__(self, key): -# return str(key) + '!!!' -#vereq(iter(L([1,2])).next(), 1) - - -print '6.6 Mappings == Dictionaries' -# calling built-in types without argument must return empty -if dict() != {}: raise TestFailed,'dict() does not return {}' -d = {} -if d.keys() != []: raise TestFailed, '{}.keys()' -if d.values() != []: raise TestFailed, '{}.values()' -if d.items() != []: raise TestFailed, '{}.items()' -if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')' -if ('a' in d) != 0: raise TestFailed, "'a' in {}" -if ('a' not in d) != 1: raise TestFailed, "'a' not in {}" -if len(d) != 0: raise TestFailed, 'len({})' -d = {'a': 1, 'b': 2} -if len(d) != 2: raise TestFailed, 'len(dict)' -k = d.keys() -k.sort() -if k != ['a', 'b']: raise TestFailed, 'dict keys()' -if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass -else: raise TestFailed, 'dict keys()' -if 'a' in d and 'b' in d and 'c' not in d: pass -else: raise TestFailed, 'dict keys() # in/not in version' -if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item' -d['c'] = 3 -d['a'] = 4 -if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment' -del d['b'] -if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion' -print '6.6.1 dict methods' -# dict.clear() -d = {1:1, 2:2, 3:3} -d.clear() -if d != {}: raise TestFailed, 'dict clear' -# dict.update() -d.update({1:100}) -d.update({2:20}) -d.update({1:1, 2:2, 3:3}) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update' -d.clear() -try: d.update(None) -except AttributeError: pass -else: raise TestFailed, 'dict.update(None), AttributeError expected' -print '6.6.2 user-dict methods' -class SimpleUserDict: - def __init__(self): - self.d = {1:1, 2:2, 3:3} - def keys(self): - return self.d.keys() - def __getitem__(self, i): - return self.d[i] -d.update(SimpleUserDict()) -if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)' -d.clear() -class FailingUserDict: - def keys(self): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.keys() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __iter__(self): - raise ValueError - return BogonIter() -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()) expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = 1 - def __iter__(self): - return self - def next(self): - if self.i: - self.i = 0 - return 'a' - raise ValueError - return BogonIter() - def __getitem__(self, key): - return key -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError' -class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = ord('a') - def __iter__(self): - return self - def next(self): - if self.i <= ord('z'): - rtn = chr(self.i) - self.i += 1 - return rtn - raise StopIteration - return BogonIter() - def __getitem__(self, key): - raise ValueError -try: d.update(FailingUserDict()) -except ValueError: pass -else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError' -print '6.6.3 dict.fromkeys' -# dict.fromkeys() -if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys did not work as a class method' -d = {} -if d.fromkeys('abc') is d: - raise TestFailed, 'dict.fromkeys did not return a new dict' -if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: - raise TestFailed, 'dict.fromkeys failed with default value' -if d.fromkeys((4,5),0) != {4:0, 5:0}: - raise TestFailed, 'dict.fromkeys failed with specified value' -if d.fromkeys([]) != {}: - raise TestFailed, 'dict.fromkeys failed with null sequence' -def g(): - yield 1 -if d.fromkeys(g()) != {1:None}: - raise TestFailed, 'dict.fromkeys failed with a generator' -try: {}.fromkeys(3) -except TypeError: pass -else: raise TestFailed, 'dict.fromkeys failed to raise TypeError' -class dictlike(dict): pass -if dictlike.fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if dictlike().fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if type(dictlike.fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' -if type(dictlike().fromkeys('a')) is not dictlike: - raise TestFailed, 'dictsubclass.fromkeys created wrong type' - -from UserDict import UserDict -class mydict(dict): - def __new__(cls): - return UserDict() -ud = mydict.fromkeys('ab') -if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): - raise TestFailed, 'fromkeys did not instantiate using __new__' - -print '6.6.4 dict copy, get, setdefault' - -# dict.copy() -d = {1:1, 2:2, 3:3} -if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy' -if {}.copy() != {}: raise TestFailed, 'empty dict copy' -# dict.get() -d = {} -if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg' -d = {'a' : 1, 'b' : 2} -if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg' -if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg' -if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg' -if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg' -# dict.setdefault() -d = {} -if d.setdefault('key0') is not None: - raise TestFailed, 'missing {} setdefault, no 2nd arg' -if d.setdefault('key0') is not None: - raise TestFailed, 'present {} setdefault, no 2nd arg' -d.setdefault('key', []).append(3) -if d['key'][0] != 3: - raise TestFailed, 'missing {} setdefault, w/ 2nd arg' -d.setdefault('key', []).append(4) -if len(d['key']) != 2: - raise TestFailed, 'present {} setdefault, w/ 2nd arg' - -print '6.6.5 dict popitem' - -# dict.popitem() -for copymode in -1, +1: - # -1: b has same structure as a - # +1: b is a.copy() - for log2size in range(4):#(12): - size = 2**log2size - a = {} - b = {} - for i in range(size): - a[`i`] = i - if copymode < 0: - b[`i`] = i - if copymode > 0: - b = a.copy() - for i in range(size): - ka, va = ta = a.popitem() - if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta) - kb, vb = tb = b.popitem() - if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb) - if copymode < 0 and ta != tb: - raise TestFailed, "a.popitem != b.popitem: %s, %s" % ( - str(ta), str(tb)) - if a: raise TestFailed, 'a not empty after popitems: %s' % str(a) - if b: raise TestFailed, 'b not empty after popitems: %s' % str(b) - -d.clear() -try: d.popitem() -except KeyError: pass -else: raise TestFailed, "{}.popitem doesn't raise KeyError" - -print '6.6.6 dict pop' - -# Tests for pop with specified key -d.clear() -k, v = 'abc', 'def' -d[k] = v -try: d.pop('ghi') -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary" - -if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair" -if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair" - -try: d.pop(k) -except KeyError: pass -else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty" - -# verify longs/ints get same value when key > 32 bits (for 64-bit archs) -# see SF bug #689659 -x = 4503599627370496L -y = 4503599627370496 -h = {x: 'anything', y: 'something else'} -if h[x] != h[y]: - raise TestFailed, "long/int key should match" - -if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value" -d[k] = v -if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair" - -''' TODO: doesn't raise correctly -d[1] = 1 -try: - for i in d: - d[i+1] = 1 -except RuntimeError: - pass -else: - raise TestFailed, "changing dict size during iteration doesn't raise Error" -''' - -print '6.7 type' - -try: type(1, 2) -except TypeError: pass -else: raise TestFailed, 'type(), w/2 args expected TypeError' - -try: type(1, 2, 3, 4) -except TypeError: pass -else: raise TestFailed, 'type(), w/4 args expected TypeError' - -''' TODO: No buffer support yet XXX -print '6.8 buffer' - -try: buffer('asdf', -1) -except ValueError: pass -else: raise TestFailed, "buffer('asdf', -1) should raise ValueError" - -try: buffer(None) -except TypeError: pass -else: raise TestFailed, "buffer(None) should raise TypeError" - -a = buffer('asdf') -hash(a) -b = a * 5 -if a == b: - raise TestFailed, 'buffers should not be equal' -if str(b) != ('asdf' * 5): - raise TestFailed, 'repeated buffer has wrong content' -if str(a * 0) != '': - raise TestFailed, 'repeated buffer zero times has wrong content' -if str(a + buffer('def')) != 'asdfdef': - raise TestFailed, 'concatenation of buffers yields wrong content' - -try: a[1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer assignment should raise TypeError" - -try: a[0:1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer slice assignment should raise TypeError" -''' -print '6.99999999... All tests ran to completion' Deleted: /pypy/dist/pypy/appspace/test/no_test_stringmodule.py ============================================================================== --- /pypy/dist/pypy/appspace/test/no_test_stringmodule.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,39 +0,0 @@ -#!/usr/bin/env python - - -""" -Test module for functions in stringmodule.py - -""" - -import string as c_py_string -import unittest - -import autopath -from pypy.tool import testit -from pypy.appspace import string as pypy_string - -class TestStringmodule(unittest.TestCase): - def regression(self, sFuncname, *args, **kwargs): - try: - c_py_res = getattr(c_py_string, sFuncname)(*args, **kwargs) - except Exception, ce: - c_py_res = ce.__class__ - - try: - pypy_res = getattr(pypy_string, sFuncname)(*args, **kwargs) - except Exception, pe: - pypy_res = pe.__class__ - - self.assertEqual(c_py_res, pypy_res, 'not equal \n1:<%s>\n2:<%s>' % (c_py_res, pypy_res)) - - - def test_maketrans(self): - self.regression('maketrans','','') - self.regression('maketrans','a','b') - self.regression('maketrans','aa','bb') - self.regression('maketrans','aa','') - - -if __name__ == "__main__": - testit.main() \ No newline at end of file Deleted: /pypy/dist/pypy/appspace/test/patched/test_sys.py ============================================================================== --- /pypy/dist/pypy/appspace/test/patched/test_sys.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,256 +0,0 @@ -# -*- coding: iso-8859-1 -*- -import unittest, test.test_support -import sys, cStringIO - -class SysModuleTest(unittest.TestCase): - - def test_original_displayhook(self): - import __builtin__ - savestdout = sys.stdout - out = cStringIO.StringIO() - sys.stdout = out - - dh = sys.__displayhook__ - - self.assertRaises(TypeError, dh) - if hasattr(__builtin__, "_"): - del __builtin__._ - - dh(None) - self.assertEqual(out.getvalue(), "") - self.assert_(not hasattr(__builtin__, "_")) - dh(42) - self.assertEqual(out.getvalue(), "42\n") - self.assertEqual(__builtin__._, 42) - - del sys.stdout - self.assertRaises(RuntimeError, dh, 42) - - sys.stdout = savestdout - - def test_lost_displayhook(self): - olddisplayhook = sys.displayhook - del sys.displayhook - code = compile("42", "", "single") - self.assertRaises(RuntimeError, eval, code) - sys.displayhook = olddisplayhook - - def test_custom_displayhook(self): - olddisplayhook = sys.displayhook - def baddisplayhook(obj): - raise ValueError - sys.displayhook = baddisplayhook - code = compile("42", "", "single") - self.assertRaises(ValueError, eval, code) - sys.displayhook = olddisplayhook - - def test_original_excepthook(self): - savestderr = sys.stderr - err = cStringIO.StringIO() - sys.stderr = err - - eh = sys.__excepthook__ - - self.assertRaises(TypeError, eh) - try: - raise ValueError(42) - except ValueError, exc: - eh(*sys.exc_info()) - - sys.stderr = savestderr - self.assert_(err.getvalue().endswith("ValueError: 42\n")) - - # FIXME: testing the code for a lost or replaced excepthook in - # Python/pythonrun.c::PyErr_PrintEx() is tricky. - - def test_exc_clear(self): - self.assertRaises(TypeError, sys.exc_clear, 42) - - # Verify that exc_info is present and matches exc, then clear it, and - # check that it worked. - def clear_check(exc): - typ, value, traceback = sys.exc_info() - self.assert_(typ is not None) - self.assert_(value is exc) - self.assert_(traceback is not None) - - sys.exc_clear() - - typ, value, traceback = sys.exc_info() - self.assert_(typ is None) - self.assert_(value is None) - self.assert_(traceback is None) - - def clear(): - try: - raise ValueError, 42 - except ValueError, exc: - clear_check(exc) - - # Raise an exception and check that it can be cleared - clear() - - # Verify that a frame currently handling an exception is - # unaffected by calling exc_clear in a nested frame. - try: - raise ValueError, 13 - except ValueError, exc: - typ1, value1, traceback1 = sys.exc_info() - clear() - typ2, value2, traceback2 = sys.exc_info() - - self.assert_(typ1 is typ2) - self.assert_(value1 is exc) - self.assert_(value1 is value2) - self.assert_(traceback1 is traceback2) - - # Check that an exception can be cleared outside of an except block - clear_check(exc) - - def test_exit(self): - self.assertRaises(TypeError, sys.exit, 42, 42) - - # call without argument - try: - sys.exit(0) - except SystemExit, exc: - self.assertEquals(exc.code, 0) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with tuple argument with one entry - # entry will be unpacked - try: - sys.exit(42) - except SystemExit, exc: - self.assertEquals(exc.code, 42) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with integer argument - try: - sys.exit((42,)) - except SystemExit, exc: - self.assertEquals(exc.code, 42) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with string argument - try: - sys.exit("exit") - except SystemExit, exc: - self.assertEquals(exc.code, "exit") - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - # call with tuple argument with two entries - try: - sys.exit((17, 23)) - except SystemExit, exc: - self.assertEquals(exc.code, (17, 23)) - except: - self.fail("wrong exception") - else: - self.fail("no exception") - - def test_getdefaultencoding(self): - if test.test_support.have_unicode: - self.assertRaises(TypeError, sys.getdefaultencoding, 42) - # can't check more than the type, as the user might have changed it - self.assert_(isinstance(sys.getdefaultencoding(), str)) - - # testing sys.settrace() is done in test_trace.py - # testing sys.setprofile() is done in test_profile.py - - def test_setcheckinterval(self): - self.assertRaises(TypeError, sys.setcheckinterval) - orig = sys.getcheckinterval() - for n in 0, 100, 120, orig: # orig last to restore starting state - sys.setcheckinterval(n) - self.assertEquals(sys.getcheckinterval(), n) - - def test_recursionlimit(self): - self.assertRaises(TypeError, sys.getrecursionlimit, 42) - oldlimit = sys.getrecursionlimit() - self.assertRaises(TypeError, sys.setrecursionlimit) - self.assertRaises(ValueError, sys.setrecursionlimit, -42) - sys.setrecursionlimit(10000) - self.assertEqual(sys.getrecursionlimit(), 10000) - sys.setrecursionlimit(oldlimit) - - def test_getwindowsversion(self): - if hasattr(sys, "getwindowsversion"): - v = sys.getwindowsversion() - self.assert_(isinstance(v, tuple)) - self.assertEqual(len(v), 5) - self.assert_(isinstance(v[0], int)) - self.assert_(isinstance(v[1], int)) - self.assert_(isinstance(v[2], int)) - self.assert_(isinstance(v[3], int)) - self.assert_(isinstance(v[4], str)) - - def test_dlopenflags(self): - if hasattr(sys, "setdlopenflags"): - self.assert_(hasattr(sys, "getdlopenflags")) - self.assertRaises(TypeError, sys.getdlopenflags, 42) - oldflags = sys.getdlopenflags() - self.assertRaises(TypeError, sys.setdlopenflags) - sys.setdlopenflags(oldflags+1) - self.assertEqual(sys.getdlopenflags(), oldflags+1) - sys.setdlopenflags(oldflags) - - def test_refcount(self): - if hasattr(sys, 'getrefcount'): - self.assertRaises(TypeError, sys.getrefcount) - c = sys.getrefcount(None) - n = None - self.assertEqual(sys.getrefcount(None), c+1) - del n - self.assertEqual(sys.getrefcount(None), c) - if hasattr(sys, "gettotalrefcount"): - self.assert_(isinstance(sys.gettotalrefcount(), int)) - - def test_getframe(self): - self.assertRaises(TypeError, sys._getframe, 42, 42) - self.assertRaises(ValueError, sys._getframe, 2000000000) - self.assert_( - SysModuleTest.test_getframe.im_func.func_code \ - is sys._getframe().f_code - ) - - def test_attributes(self): - self.assert_(isinstance(sys.api_version, int)) - self.assert_(isinstance(sys.argv, list)) - self.assert_(sys.byteorder in ("little", "big")) - self.assert_(isinstance(sys.builtin_module_names, tuple)) - self.assert_(isinstance(sys.copyright, basestring)) - self.assert_(isinstance(sys.exec_prefix, basestring)) - self.assert_(isinstance(sys.executable, basestring)) - self.assert_(isinstance(sys.hexversion, int)) - self.assert_(isinstance(sys.maxint, int)) - self.assert_(isinstance(sys.maxunicode, int)) - self.assert_(isinstance(sys.platform, basestring)) - self.assert_(isinstance(sys.prefix, basestring)) - self.assert_(isinstance(sys.version, basestring)) - vi = sys.version_info - self.assert_(isinstance(vi, tuple)) - self.assertEqual(len(vi), 5) - self.assert_(isinstance(vi[0], int)) - self.assert_(isinstance(vi[1], int)) - self.assert_(isinstance(vi[2], int)) - self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) - self.assert_(isinstance(vi[4], int)) - -def test_main(): - test.test_support.run_unittest(SysModuleTest) - -if __name__ == "__main__": - test_main() Deleted: /pypy/dist/pypy/appspace/test/support_tests.py ============================================================================== --- /pypy/dist/pypy/appspace/test/support_tests.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,184 +0,0 @@ -"""Supporting definitions for the Python regression tests.""" - -''' -if __name__ != 'test.test_support': - raise ImportError, 'test_support must be imported from the test package' -''' - -import sys, os -from os import unlink - -try: - tmpdir = sys.pypy_getudir() -except AttributeError: - import py - tmpdir = str(py.test.config.tmpdir) -TESTFN = os.path.join(tmpdir, '@test') - -class Error(Exception): - """Base class for regression test exceptions.""" - -class TestFailed(Error): - """Test failed.""" - -class TestSkipped(Error): - """Test skipped. - - This can be raised to indicate that a test was deliberatly - skipped, but not because a feature wasn't available. For - example, if some resource can't be used, such as the network - appears to be unavailable, this should be raised instead of - TestFailed. - """ - -class ResourceDenied(TestSkipped): - """Test skipped because it requested a disallowed resource. - - This is raised when a test calls requires() for a resource that - has not be enabled. It is used to distinguish between expected - and unexpected skips. - """ - -verbose = 0 # Flag set to 0 by regrtest.py -use_resources = None # Flag set to [] by regrtest.py - -# _original_stdout is meant to hold stdout at the time regrtest began. -# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. -# The point is to have some flavor of stdout the user can actually see. -_original_stdout = None -def record_original_stdout(stdout): - global _original_stdout - _original_stdout = stdout - -def get_original_stdout(): - return _original_stdout or sys.stdout - -def unload(name): - try: - del sys.modules[name] - except KeyError: - pass - -def forget(modname): - '''"Forget" a module was ever imported by removing it from sys.modules and - deleting any .pyc and .pyo files.''' - unload(modname) - import os - for dirname in sys.path: - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) - except os.error: - pass - # Deleting the .pyo file cannot be within the 'try' for the .pyc since - # the chance exists that there is no .pyc (and thus the 'try' statement - # is exited) but there is a .pyo file. - try: - os.unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) - except os.error: - pass - -def is_resource_enabled(resource): - """Test whether a resource is enabled. Known resources are set by - regrtest.py.""" - return use_resources is not None and resource in use_resources - -def requires(resource, msg=None): - """Raise ResourceDenied if the specified resource is not available. - - If the caller's module is __main__ then automatically return True. The - possibility of False being returned occurs when regrtest.py is executing.""" - # see if the caller's module is __main__ - if so, treat as if - # the resource was set - if sys._getframe().f_back.f_globals.get("__name__") == "__main__": - return - if not is_resource_enabled(resource): - if msg is None: - msg = "Use of the `%s' resource not enabled" % resource - raise ResourceDenied(msg) - -FUZZ = 1e-6 - -def fcmp(x, y): # fuzzy comparison function - if type(x) == type(0.0) or type(y) == type(0.0): - try: - x, y = float(x), float(y) - fuzz = (abs(x) + abs(y)) * FUZZ - if abs(x-y) <= fuzz: - return 0 - except: - pass - elif type(x) == type(y) and type(x) in (type(()), type([])): - for i in range(min(len(x), len(y))): - outcome = fcmp(x[i], y[i]) - if outcome != 0: - return outcome - return cmp(len(x), len(y)) - return cmp(x, y) - -try: - unicode - have_unicode = 0 # XXX UNICODE 1 -except NameError: - have_unicode = 0 - -is_jython = sys.platform.startswith('java') - - - -##if fp is not None: -## fp.close() -##del fp - -def findfile(file, here=__file__): - """Try to find a file on sys.path and the working directory. If it is not - found the argument passed to the function is returned (this does not - necessarily signal failure; could still be the legitimate path).""" - import os - if os.path.isabs(file): - return file - path = sys.path - path = [os.path.dirname(here)] + path - for dn in path: - fn = os.path.join(dn, file) - if os.path.exists(fn): return fn - return file - -def verify(condition, reason='test failed'): - """Verify that condition is true. If not, raise TestFailed. - - The optional argument reason can be given to provide - a better error text. - """ - - if not condition: - raise TestFailed(reason) - -def vereq(a, b): - """Raise TestFailed if a == b is false. - - This is better than verify(a == b) because, in case of failure, the - error message incorporates repr(a) and repr(b) so you can see the - inputs. - - Note that "not (a == b)" isn't necessarily the same as "a != b"; the - former is tested. - """ - - if not (a == b): - raise TestFailed, "%r == %r" % (a, b) - -def sortdict(dict): - "Like repr(dict), but in sorted order." - items = dict.items() - items.sort() - reprpairs = ["%r: %r" % pair for pair in items] - withcommas = ", ".join(reprpairs) - return "{%s}" % withcommas - -def check_syntax(statement): - try: - compile(statement, '', 'exec') - except SyntaxError: - pass - else: - print 'Missing SyntaxError: "%s"' % statement Deleted: /pypy/dist/pypy/appspace/test/test_cmathmodule.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_cmathmodule.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,62 +0,0 @@ -#!/usr/bin/env python - -# taken from CPython 2.3 - -""" -Test module for functions in cmathmodule.py - -It seems the log and log10 functions are generating errors -due to numerical problems with floor() in complex.__div__. -""" - -import math -import cmath -import sys -import unittest -import autopath - -from pypy.appspace import cmathmodule -from pypy.appspace.test.test_complexobject import equal - -def enumerate(): - valueRange = [-12.34, -3, -1, -0.5, 0, 0.5, 1, 3, 12.34] - res = [] - for x0 in valueRange: - for y0 in valueRange: - z = complex(x0,y0) - res.append(z) - return res - - - -class TestCMathModule: - - def assertAEqual(self, a, b): - if not equal(a, b): - raise self.failureException, '%s ~== %s'%(a, b) - - def test_funcs(self): - "Compare many functions with CPython." - - for z in enumerate(): - - for op in "sqrt acos acosh asin asinh atan atanh cos cosh exp".split(): - if op == "atan" and equal(z, complex(0,-1)) or equal(z, complex(0,1)): - continue - if op == "atanh" and equal(z, complex(-1,0)) or equal(z, complex(1,0)): - continue - op0 = cmath.__dict__[op](z) - op1 = cmathmodule.__dict__[op](z) - self.assertAEqual(op0, op1) - - - def test_log_log10(self): - "Compare log/log10 functions with CPython." - - for z in enumerate(): - for op in "log log10".split(): - if z != 0: - op0 = cmath.__dict__[op](z) - op1 = cmathmodule.__dict__[op](z) - self.assertAEqual(op0, op1) - Deleted: /pypy/dist/pypy/appspace/test/test_complexobject.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_complexobject.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,255 +0,0 @@ -#!/usr/bin/env python - -""" - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -Note that this test currently runs at cpython-level and not -at any application level .... - -""" -#taken from CPython 2.3 (?) - -""" -Test module for class complex in complexobject.py - -As it seems there are some numerical differences in -the __div__ and __divmod__ methods which have to be -sorted out. -""" - -import autopath - -import math -import cmath -import sys -import types -import unittest - -from pypy.tool import testit -#from pypy.appspace.complexobject import complex as pycomplex -from pypy.module.test.applevel_in_cpython import applevel_in_cpython -our_own_builtin = applevel_in_cpython('__builtin__') -pycomplex = our_own_builtin.complex - - -try: - unicode - have_unicode = 0 # pypy doesn't have unicode, we know it ... -except NameError: - have_unicode = 0 - - -def equal(a, b): - "Compare two complex or normal numbers. 0 if different, 1 if roughly equal." - - numTypes = [types.IntType, types.LongType, types.FloatType] - da, db = dir(a), dir(b) - - if 'real' in da and 'real' in db and 'imag' in da and 'imag' in db: - if math.fabs(a.real-b.real) > 1e-10: - return 0 - if math.fabs(a.imag-b.imag) > 1e-10: - return 0 - else: - return 1 - elif type(a) in numTypes and type(b) in numTypes: - if math.fabs(a-b) > 1e-10: - return 0 - else: - return 1 - - - - -def enumerate(): - valueRange = [-3, -0.5, 0, 1] - res = [] - for x0 in valueRange: - for y0 in valueRange: - for x1 in valueRange: - for y1 in valueRange: - z0c = complex(x0,y0) - z1c = complex(x1,y1) - z0p = pycomplex(x0,y0) - z1p = pycomplex(x1,y1) - res.append((z0c, z1c, z0p, z1p)) - - return res - - - -class TestComplex(unittest.TestCase): - - def assertAEqual(self, a, b): - if not equal(a, b): - raise self.failureException, '%s ~== %s'%(a, b) - - def test_wrongInit1(self): - "Compare wrong init. with CPython." - - try: - complex("1", "1") - except TypeError: - pass - else: - self.fail('complex("1", "1")') - - try: - pycomplex("1", "1") - except TypeError: - pass - else: - self.fail('complex("1", "1")') - - - def test_wrongInit2(self): - "Compare wrong init. with CPython." - - try: - complex(1, "1") - except TypeError: - pass - else: - self.fail('complex(1, "1")') - - try: - pycomplex(1, "1") - except TypeError: - pass - else: - self.fail('complex(1, "1")') - - - def test_wrongInitFromString(self): - "Compare string init. with CPython." - - if complex(" 3.14+J ") != 3.14+1j: - self.fail('complex(" 3.14+J )"') - if not equal(pycomplex(" 3.14+J "), pycomplex(3.14,1)): - self.fail('complex(" 3.14+J )"') - - - def test_wrongInitFromUnicodeString(self): - "Compare unicode string init. with CPython." - - if have_unicode: - if complex(unicode(" 3.14+J ")) != 3.14+1j: - self.fail('complex(u" 3.14+J )"') - if not equal(pycomplex(unicode(" 3.14+J ")), pycomplex(3.14, 1)): - self.fail('complex(u" 3.14+J )"') - - - def test_class(self): - "Compare class with CPython." - - class Z: - def __complex__(self): - return 3.14j - z = Z() - if complex(z) != 3.14j: - self.fail('complex(classinstance)') - - if not equal(complex(z), pycomplex(0, 3.14)): - self.fail('complex(classinstance)') - - - def test_add_sub_mul_div(self): - "Compare add/sub/mul/div with CPython." - - for (z0c, z1c, z0p, z1p) in enumerate(): - mc = z0c*z1c - mp = z0p*z1p - self.assertAEqual(mc, mp) - - sc = z0c+z1c - sp = z0p+z1p - self.assertAEqual(sc, sp) - - dc = z0c-z1c - dp = z0p-z1p - self.assertAEqual(dc, dp) - - if not equal(z1c, complex(0,0)): - qc = z0c/z1c - qp = z0p/z1p - self.assertAEqual(qc, qp) - - - def test_special(self): - "Compare special methods with CPython." - - for (x, y) in [(0,0), (0,1), (1,3.)]: - zc = complex(x, y) - zp = pycomplex(x, y) - - self.assertAEqual(zc, zp) - self.assertAEqual(-zc, -zp) - self.assertAEqual(+zc, +zp) - self.assertAEqual(abs(zc), abs(zp)) - self.assertAEqual(zc, zp) - #self.assertEqual(zc.conjugate(), zp.conjugate()) XXX - self.assertEqual(str(zc), str(zp)) - self.assertEqual(hash(zc), hash(zp)) - - - # this fails on python2.3 and is depreacted anyway - def _test_divmod(self): - "Compare divmod with CPython." - - for (z0c, z1c, z0p, z1p) in enumerate(): - mc = z0c*z1c - mp = z0p*z1p - self.assertAEqual(mc, mp) - - if not equal(z1c, complex(0,0)): - ddc, mmc = divmod(z0c, z1c) - self.assertAEqual(ddc*z1c + mmc, z0c) - ddp, mmp = divmod(z0p, z1p) - self.assertAEqual(ddp*z1p + mmp, z0p) - self.assertAEqual(ddc, ddp) - self.assertAEqual(mmc, mmp) - - - # these fail on python2.3 - def _test_mod(self): - "Compare mod with CPython." - - for (z0c, z1c, z0p, z1p) in enumerate(): - mc = z0c*z1c - mp = z0p*z1p - self.assertAEqual(mc, mp) - - if not equal(z1c, complex(0,0)): - rc = z0c%z1c - rp = z0p%z1p - self.assertAEqual(rc, rp) - - def test_div(self): - "Compare mod with CPython." - - for (z0c, z1c, z0p, z1p) in enumerate(): - mc = z0c*z1c - mp = z0p*z1p - self.assertAEqual(mc, mp) - - if not equal(z1c, complex(0,0)): - rc = z0c/z1c - rp = z0p/z1p - self.assertAEqual(rc, rp) - - - def test_pow(self): - "Compare pow with CPython." - - for (z0c, z1c, z0p, z1p) in enumerate(): - if not equal(z0c, 0j) and (z1c.imag != 0.0): - pc = z0c**z1c - pp = z0p**z1p - self.assertAEqual(pc, pp) - pc = z0c**z0c.real - pp = z0p**z0p.real - self.assertAEqual(pc, pp) - -if __name__ == "__main__": - testit.main() Deleted: /pypy/dist/pypy/appspace/test/test_exceptions.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_exceptions.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,5 +0,0 @@ -import autopath - -def failing_app_test_import(): - import exceptions - assert exceptions.SyntaxError is SyntaxError Deleted: /pypy/dist/pypy/appspace/test/test_file.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_file.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,193 +0,0 @@ -import os -import autopath -from pypy.appspace import _file -from pypy.tool.udir import udir -import py -import unittest - -class TestFile: - def setup_method(self, method): - filename = os.path.join(autopath.this_dir, 'test_file.py') - self.fd = _file.file_(filename, 'r') - - def teardown_method(self, method): - self.fd.close() - - def test_case_1(self): - assert self.fd.tell() == 0 - - def test_case_readonly(self): - fn = str(udir.join('temptestfile')) - f=_file.file_(fn, 'w') - assert f.name == fn - assert f.mode == 'w' - assert f.closed == False - assert f.encoding == None # Fix when we find out what this is - py.test.raises(TypeError, setattr, f, 'name', 42) - - - def test_from_cpython(self): - - from test.test_support import verify, TESTFN, TestFailed - from UserList import UserList - - # verify expected attributes exist - f = file(TESTFN, 'w') - softspace = f.softspace - f.name # merely shouldn't blow up - f.mode # ditto - f.closed # ditto - - # verify softspace is writable - f.softspace = softspace # merely shouldn't blow up - - # verify the others aren't - for attr in 'name', 'mode', 'closed': - try: - setattr(f, attr, 'oops') - except TypeError: - pass - else: - raise TestFailed('expected TypeError setting file attr %r' % attr) - f.close() - - # verify writelines with instance sequence - l = UserList(['1', '2']) - f = open(TESTFN, 'wb') - f.writelines(l) - f.close() - f = open(TESTFN, 'rb') - buf = f.read() - f.close() - verify(buf == '12') - - # verify writelines with integers - f = open(TESTFN, 'wb') - try: - f.writelines([1, 2, 3]) - except TypeError: - pass - else: - print "writelines accepted sequence of integers" - f.close() - - # verify writelines with integers in UserList - f = open(TESTFN, 'wb') - l = UserList([1,2,3]) - try: - f.writelines(l) - except TypeError: - pass - else: - print "writelines accepted sequence of integers" - f.close() - - # verify writelines with non-string object - class NonString: pass - - f = open(TESTFN, 'wb') - try: - f.writelines([NonString(), NonString()]) - except TypeError: - pass - else: - print "writelines accepted sequence of non-string objects" - f.close() - - # verify that we get a sensible error message for bad mode argument - bad_mode = "qwerty" - try: - open(TESTFN, bad_mode) - except IOError, msg: - pass # We have problems with Exceptions - if msg[0] != 0: - s = str(msg) - if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: - print "bad error message for invalid mode: %s" % s - # if msg[0] == 0, we're probably on Windows where there may be - # no obvious way to discover why open() failed. - else: - print "no error for invalid mode: %s" % bad_mode - - f = open(TESTFN) - if f.name != TESTFN: - raise TestFailed, 'file.name should be "%s"' % TESTFN - - if f.isatty(): - raise TestFailed, 'file.isatty() should be false' - - if f.closed: - raise TestFailed, 'file.closed should be false' - - - f.close() - if not f.closed: - raise TestFailed, 'file.closed should be true' - - # make sure that explicitly setting the buffer size doesn't cause - # misbehaviour especially with repeated close() calls - for s in (-1, 0, 1, 512): - try: - f = open(TESTFN, 'w', s) - f.write(str(s)) - f.close() - f.close() - f = open(TESTFN, 'r', s) - d = int(f.read()) - f.close() - f.close() - except IOError, msg: - raise TestFailed, 'error setting buffer size %d: %s' % (s, str(msg)) - if d != s: - raise TestFailed, 'readback failure using buffer size %d' - - methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readline', - 'readlines', 'seek', 'tell', 'truncate', 'write', - 'xreadlines', '__iter__'] - - for methodname in methods: - method = getattr(f, methodname) - try: - method() - except ValueError: - pass - else: - raise TestFailed, 'file.%s() on a closed file should raise a ValueError' % methodname - - try: - f.writelines([]) - except ValueError: - pass - else: - raise TestFailed, 'file.writelines([]) on a closed file should raise a ValueError' - - os.unlink(TESTFN) - - def bug801631(): - # SF bug - # "file.truncate fault on windows" - f = file(TESTFN, 'wb') - f.write('12345678901') # 11 bytes - f.close() - - f = file(TESTFN,'rb+') - data = f.read(5) - if data != '12345': - raise TestFailed("Read on file opened for update failed %r" % data) - if f.tell() != 5: - raise TestFailed("File pos after read wrong %d" % f.tell()) - - f.truncate() - if f.tell() != 5: - raise TestFailed("File pos after ftruncate wrong %d" % f.tell()) - - f.close() - size = os.path.getsize(TESTFN) - if size != 5: - raise TestFailed("File size after ftruncate wrong %d" % size) - - try: - bug801631() - finally: - os.unlink(TESTFN) - Deleted: /pypy/dist/pypy/appspace/test/test_md5.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_md5.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,241 +0,0 @@ -"""A test script to compare MD5 implementations. - -A note about performance: the pure Python MD5 takes roughly -160 sec. per MB of data on a 233 MHz Intel Pentium CPU. -""" - -import autopath -import string, unittest -import md5 # CPython's implementation in C. -from pypy.appspace import md5 as pymd5 # The pure Python implementation. - - -# Helpers... - -def formatHex(str): - "Print a string's HEX code in groups of two digits." - - d = map(None, str) - d = map(ord, d) - d = map(lambda x:"%02x" % x, d) - return string.join(d, " ") - - -def format(str): - "Print a string as-is in groups of two characters." - - s = '' - for i in range(0, len(str)-1, 2): - s = s + "%03s" % str[i:i+2] - return s[1:] - - -def printDiff(message, d1, d2, expectedResult=None): - "Print different outputs for same message." - - print "Message: '%s'" % message - print "Message length: %d" % len(message) - if expectedResult: - print "%-48s (expected)" % format(expectedResult) - print "%-48s (Std. lib. MD5)" % formatHex(d1) - print "%-48s (Pure Python MD5)" % formatHex(d2) - print - - -# The real comparison function. - -def compareImp(message): - """Compare two MD5 implementations, C vs. pure Python module. - - For equal digests this returns None, otherwise it returns - a tuple of both digests. - """ - - # Use Python's standard library MD5 compiled C module. - m1 = md5.md5() - m1.update(message) - d1 = m1.digest() - d1h = m1.hexdigest() - - # Use MD5 module in pure Python. - m2 = pymd5.md5() - m2.update(message) - d2 = m2.digest() - d2h = m2.hexdigest() - - # Return None if equal or the different digests if not equal. - if d1 == d2 and d1h == d2h: - return - else: - return d1, d2 - - -class MD5CompareTestCase(unittest.TestCase): - "Compare pure Python MD5 against Python's std. lib. version." - - def test1(self): - "Test cases with known digest result." - - cases = ( - ("", - "d41d8cd98f00b204e9800998ecf8427e"), - ("a", - "0cc175b9c0f1b6a831c399e269772661"), - ("abc", - "900150983cd24fb0d6963f7d28e17f72"), - ("message digest", - "f96b697d7cb7938d525a2f31aaf161d0"), - ("abcdefghijklmnopqrstuvwxyz", - "c3fcd3d76192e4007dfb496cca67e13b"), - ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "d174ab98d277d9f5a5611c2c9f419d9f"), - ("1234567890"*8, - "57edf4a22be3c955ac49da2e2107b67a"), - ) - - for i in xrange(len(cases)): - res = compareImp(cases[i][0]) - try: - assert res == None - except AssertionError, details: - d1, d2 = res - message, expectedResult = cases[i][0], None - if len(cases[i]) == 2: - expectedResult = cases[i][1] - printDiff(message, d1, d2, expectedResult) - - - def test2(self): - "Test cases without known digest result." - - cases = ( - "123", - "1234", - "12345", - "123456", - "1234567", - "12345678", - "123456789 123456789 123456789 ", - "123456789 123456789 ", - "123456789 123456789 1", - "123456789 123456789 12", - "123456789 123456789 123", - "123456789 123456789 1234", - "123456789 123456789 123456789 1", - "123456789 123456789 123456789 12", - "123456789 123456789 123456789 123", - "123456789 123456789 123456789 1234", - "123456789 123456789 123456789 12345", - "123456789 123456789 123456789 123456", - "123456789 123456789 123456789 1234567", - "123456789 123456789 123456789 12345678", - ) - - for i in xrange(len(cases)): - res = compareImp(cases[i][0]) - try: - assert res == None - except AssertionError, details: - d1, d2 = res - message = cases[i][0] - printDiff(message, d1, d2) - - - def test3(self): - "Test cases with long messages (can take a while)." - - cases = ( - (2**10*'a',), - (2**10*'abcd',), -## (2**20*'a',), ## 1 MB, takes about 160 sec. on a 233 Mhz Pentium. - ) - - for i in xrange(len(cases)): - res = compareImp(cases[i][0]) - try: - assert res == None - except AssertionError, details: - d1, d2 = res - message = cases[i][0] - printDiff(message, d1, d2) - - - def test4(self): - "Test cases with increasingly growing message lengths." - - i = 0 - while i < 2**5: - message = i * 'a' - res = compareImp(message) - try: - assert res == None - except AssertionError, details: - d1, d2 = res - printDiff(message, d1, d2) - i = i + 1 - - - def test5(self): - "Test updating cloned objects." - - cases = ( - "123", - "1234", - "12345", - "123456", - "1234567", - "12345678", - "123456789 123456789 123456789 ", - "123456789 123456789 ", - "123456789 123456789 1", - "123456789 123456789 12", - "123456789 123456789 123", - "123456789 123456789 1234", - "123456789 123456789 123456789 1", - "123456789 123456789 123456789 12", - "123456789 123456789 123456789 123", - "123456789 123456789 123456789 1234", - "123456789 123456789 123456789 12345", - "123456789 123456789 123456789 123456", - "123456789 123456789 123456789 1234567", - "123456789 123456789 123456789 12345678", - ) - - # Load both with same prefix. - prefix1 = 2**10 * 'a' - - m1 = md5.md5() - m1.update(prefix1) - m1c = m1.copy() - - m2 = pymd5.md5() - m2.update(prefix1) - m2c = m2.copy() - - # Update and compare... - for i in xrange(len(cases)): - message = cases[i][0] - - m1c.update(message) - d1 = m1c.hexdigest() - - m2c.update(message) - d2 = m2c.hexdigest() - - assert d1 == d2 - - -def makeSuite(): - suite = unittest.TestSuite() - - suite.addTest(MD5CompareTestCase('test1')) - suite.addTest(MD5CompareTestCase('test2')) - suite.addTest(MD5CompareTestCase('test3')) - suite.addTest(MD5CompareTestCase('test4')) - suite.addTest(MD5CompareTestCase('test5')) - - return suite - - -if __name__ == "__main__": - unittest.TextTestRunner().run(makeSuite()) Deleted: /pypy/dist/pypy/appspace/test/test_sha.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_sha.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,25 +0,0 @@ -# Testing sha module (NIST's Secure Hash Algorithm) - -# use the three examples from Federal Information Processing Standards -# Publication 180-1, Secure Hash Standard, 1995 April 17 -# http://www.itl.nist.gov/div897/pubs/fip180-1.htm - -import autopath -from pypy.appspace import sha - -class TestSHA: - def check(self, data, digest): - computed = sha.new(data).hexdigest() - assert computed == digest - - def test_case_1(self): - self.check("abc", - "a9993e364706816aba3e25717850c26c9cd0d89d") - - def test_case_2(self): - self.check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "84983e441c3bd26ebaae4aa1f95129e5e54670f1") - - def disabled_too_slow_test_case_3(self): - self.check("a" * 1000000, - "34aa973cd4c4daa4f61eeb2bdbad27316534016f") Deleted: /pypy/dist/pypy/appspace/test/test_struct.py ============================================================================== --- /pypy/dist/pypy/appspace/test/test_struct.py Sat Jan 29 07:37:09 2005 +++ (empty file) @@ -1,439 +0,0 @@ -import autopath -from pypy.appspace.test.support_tests import TestFailed, verbose, verify -from pypy.appspace import struct -import sys - -ISBIGENDIAN = sys.byteorder == "big" -del sys -verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN, - "bigendian determination appears wrong") - -def string_reverse(s): - chars = list(s) - chars.reverse() - return "".join(chars) - -def bigendian_to_native(value): - if ISBIGENDIAN: - return value - else: - return string_reverse(value) - -def simple_err(func, *args): - try: - func(*args) - except struct.error: - pass - else: - raise TestFailed, "%s%s did not raise struct.error" % ( - func.__name__, args) - -def any_err(func, *args): - try: - func(*args) - except (struct.error, OverflowError, TypeError): - pass - else: - raise TestFailed, "%s%s did not raise error" % ( - func.__name__, args) - - -simple_err(struct.calcsize, 'Z') - -sz = struct.calcsize('i') -if sz * 3 != struct.calcsize('iii'): - raise TestFailed, 'inconsistent sizes' - -fmt = 'cbxxxxxxhhhhiillffd' -fmt3 = '3c3b18x12h6i6l6f3d' -sz = struct.calcsize(fmt) -sz3 = struct.calcsize(fmt3) -if sz * 3 != sz3: - raise TestFailed, 'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % ( - fmt, sz, 3*sz, fmt3, sz3) - -simple_err(struct.pack, 'iii', 3) -simple_err(struct.pack, 'i', 3, 3, 3) -simple_err(struct.pack, 'i', 'foo') -simple_err(struct.pack, 'P', 'foo') -simple_err(struct.unpack, 'd', 'flap') -s = struct.pack('ii', 1, 2) -simple_err(struct.unpack, 'iii', s) -simple_err(struct.unpack, 'i', s) - -c = 'a' -b = 0 -h = 255 -i = 65535 -l = 65536 -f = 3.1415 -d = 3.1415 - -for prefix in ('', '@', '<', '>', '=', '!'): - for format in ('xcbhilfd', 'xcBHILfd'): - format = prefix + format - if verbose: - print "trying:", format - s = struct.pack(format, c, b, h, i, l, f, d) - cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) - if (cp != c or bp != b or hp != h or ip != i or lp != l or - int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): - # ^^^ calculate only to two decimal places - raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( - str(format), str((cp, bp, hp, ip, lp, fp, dp))) - -# Test some of the new features in detail - -# (format, argument, big-endian result, little-endian result, asymmetric) -tests = [ - ('c', 'a', 'a', 'a', 0), - ('xc', 'a', '\0a', '\0a', 0), - ('cx', 'a', 'a\0', 'a\0', 0), - ('s', 'a', 'a', 'a', 0), - ('0s', 'helloworld', '', '', 1), - ('1s', 'helloworld', 'h', 'h', 1), - ('9s', 'helloworld', 'helloworl', 'helloworl', 1), - ('10s', 'helloworld', 'helloworld', 'helloworld', 0), - ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1), - ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1), - ('b', 7, '\7', '\7', 0), - ('b', -7, '\371', '\371', 0), - ('B', 7, '\7', '\7', 0), - ('B', 249, '\371', '\371', 0), - ('h', 700, '\002\274', '\274\002', 0), - ('h', -700, '\375D', 'D\375', 0), - ('H', 700, '\002\274', '\274\002', 0), - ('H', 0x10000-700, '\375D', 'D\375', 0), - ('i', 70000000, '\004,\035\200', '\200\035,\004', 0), - ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0), - ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('l', 70000000, '\004,\035\200', '\200\035,\004', 0), - ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0), - ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('f', 2.0, '@\000\000\000', '\000\000\000@', 0), - ('d', 2.0, '@\000\000\000\000\000\000\000','\000\000\000\000\000\000\000@', 0), - ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), - ('d', -2.0, '\300\000\000\000\000\000\000\000','\000\000\000\000\000\000\000\300', 0), -] - -for fmt, arg, big, lil, asy in tests: - if verbose: - print "%r %r %r %r" % (fmt, arg, big, lil) - for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), - ('='+fmt, ISBIGENDIAN and big or lil)]: - res = struct.pack(xfmt, arg) - if res != exp: - raise TestFailed, "pack(%r, %r) -> %r # expected %r" % ( - fmt, arg, res, exp) - n = struct.calcsize(xfmt) - if n != len(res): - raise TestFailed, "calcsize(%r) -> %d # expected %d" % ( - xfmt, n, len(res)) - rev = struct.unpack(xfmt, res)[0] - if rev != arg and not asy: - raise TestFailed, "unpack(%r, %r) -> (%r,) # expected (%r,)" % ( - fmt, res, rev, arg) - -########################################################################### -# Simple native q/Q tests. - -has_native_qQ = 1 -try: - struct.pack("q", 5) -except struct.error: - has_native_qQ = 0 - -if verbose: - print "Platform has native q/Q?", has_native_qQ and "Yes." or "No." - -any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless -simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless -simple_err(struct.pack, "Q", "a") # ditto, but 'Q' - -def test_native_qQ(): - bytes = struct.calcsize('q') - # The expected values here are in big-endian format, primarily because - # I'm on a little-endian machine and so this is the clearest way (for - # me) to force the code to get exercised. - for format, input, expected in ( - ('q', -1, '\xff' * bytes), - ('q', 0, '\x00' * bytes), - ('Q', 0, '\x00' * bytes), - ('q', 1L, '\x00' * (bytes-1) + '\x01'), - ('Q', (1L << (8*bytes))-1, '\xff' * bytes), - ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): - got = struct.pack(format, input) - native_expected = bigendian_to_native(expected) - verify(got == native_expected, - "%r-pack of %r gave %r, not %r" % - (format, input, got, native_expected)) - retrieved = struct.unpack(format, got)[0] - verify(retrieved == input, - "%r-unpack of %r gave %r, not %r" % - (format, got, retrieved, input)) - -if has_native_qQ: - test_native_qQ() - -########################################################################### -# Standard integer tests (bBhHiIlLqQ). - -import binascii - -class IntTester: - - # XXX Most std integer modes fail to test for out-of-range. - # The "i" and "l" codes appear to range-check OK on 32-bit boxes, but - # fail to check correctly on some 64-bit ones (Tru64 Unix + Compaq C - # reported by Mark Favas). - BUGGY_RANGE_CHECK = "bBhHiIlL" - - def __init__(self, formatpair, bytesize): - assert len(formatpair) == 2 - self.formatpair = formatpair - for direction in "<>!=": - for code in formatpair: - format = direction + code - verify(struct.calcsize(format) == bytesize) - self.bytesize = bytesize - self.bitsize = bytesize * 8 - self.signed_code, self.unsigned_code = formatpair - self.unsigned_min = 0 - self.unsigned_max = 2L**self.bitsize - 1 - self.signed_min = -(2L**(self.bitsize-1)) - self.signed_max = 2L**(self.bitsize-1) - 1 - - def test_one(self, x, pack=struct.pack, - unpack=struct.unpack, - unhexlify=binascii.unhexlify): - if verbose: - print "trying std", self.formatpair, "on", x, "==", hex(x) - - # Try signed. - code = self.signed_code - if self.signed_min <= x <= self.signed_max: - # Try big -endian. - expected = long(x) - if x < 0: - expected += 1L << self.bitsize - assert expected > 0 - expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' - if len(expected) & 1: - expected = "0" + expected - expected = unhexlify(expected) - expected = "\x00" * (self.bytesize - len(expected)) + expected - - # Pack work? - format = ">" + code - got = pack(format, x) - verify(got == expected, - "'%s'-pack of %r gave %r, not %r" % - (format, x, got, expected)) - - # Unpack work? - retrieved = unpack(format, got)[0] - verify(x == retrieved, - "'%s'-unpack of %r gave %r, not %r" % - (format, got, retrieved, x)) - - # Adding any byte should cause a "too big" error. - any_err(unpack, format, '\x01' + got) - - # Try little-endian. - format = "<" + code - expected = string_reverse(expected) - - # Pack work? - got = pack(format, x) - verify(got == expected, - "'%s'-pack of %r gave %r, not %r" % - (format, x, got, expected)) - - # Unpack work? - retrieved = unpack(format, got)[0] - verify(x == retrieved, - "'%s'-unpack of %r gave %r, not %r" % - (format, got, retrieved, x)) - - # Adding any byte should cause a "too big" error. - any_err(unpack, format, '\x01' + got) - - else: - # x is out of range -- verify pack realizes that. - if code in self.BUGGY_RANGE_CHECK: - if verbose: - print "Skipping buggy range check for code", code - else: - any_err(pack, ">" + code, x) - any_err(pack, "<" + code, x) - - # Much the same for unsigned. - code = self.unsigned_code - if self.unsigned_min <= x <= self.unsigned_max: - # Try big-endian. - format = ">" + code - expected = long(x) - expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' - if len(expected) & 1: - expected = "0" + expected - expected = unhexlify(expected) - expected = "\x00" * (self.bytesize - len(expected)) + expected - - # Pack work? - got = pack(format, x) - verify(got == expected, - "'%s'-pack of %r gave %r, not %r" % - (format, x, got, expected)) - - # Unpack work? - retrieved = unpack(format, got)[0] - verify(x == retrieved, - "'%s'-unpack of %r gave %r, not %r" % - (format, got, retrieved, x)) - - # Adding any byte should cause a "too big" error. - any_err(unpack, format, '\x01' + got) - - # Try little-endian. - format = "<" + code - expected = string_reverse(expected) - - # Pack work? - got = pack(format, x) - verify(got == expected, - "'%s'-pack of %r gave %r, not %r" % - (format, x, got, expected)) - - # Unpack work? - retrieved = unpack(format, got)[0] - verify(x == retrieved, - "'%s'-unpack of %r gave %r, not %r" % - (format, got, retrieved, x)) - - # Adding any byte should cause a "too big" error. - any_err(unpack, format, '\x01' + got) - - else: - # x is out of range -- verify pack realizes that. - if code in self.BUGGY_RANGE_CHECK: - if verbose: - print "Skipping buggy range check for code", code - else: - any_err(pack, ">" + code, x) - any_err(pack, "<" + code, x) - - def run(self): - from random import randrange - - # Create all interesting powers of 2. - values = [] - for exp in range(self.bitsize + 3): - values.append(1L << exp) - - # Add some random values. - for i in range(self.bitsize): - val = 0L - for j in range(self.bytesize): - val = (val << 8) | randrange(256) - values.append(val) - - # Try all those, and their negations, and +-1 from them. Note - # that this tests all power-of-2 boundaries in range, and a few out - # of range, plus +-(2**n +- 1). - for base in values: - for val in -base, base: - for incr in -1, 0, 1: - x = val + incr - try: - x = int(x) - except OverflowError: - pass - self.test_one(x) - - # Some error cases. - for direction in "<>": - for code in self.formatpair: - for badobject in "a string", 3+42j, randrange: - any_err(struct.pack, direction + code, badobject) - -for args in [("bB", 1), - ("hH", 2), - ("iI", 4), - ("lL", 4), - ("qQ", 8)]: - t = IntTester(*args) - t.run() - - -########################################################################### -# The p ("Pascal string") code. - -def test_p_code(): - for code, input, expected, expectedback in [ - ('p','abc', '\x00', ''), - ('1p', 'abc', '\x00', ''), - ('2p', 'abc', '\x01a', 'a'), - ('3p', 'abc', '\x02ab', 'ab'), - ('4p', 'abc', '\x03abc', 'abc'), - ('5p', 'abc', '\x03abc\x00', 'abc'), - ('6p', 'abc', '\x03abc\x00\x00', 'abc'), - ('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]: - got = struct.pack(code, input) - if got != expected: - raise TestFailed("pack(%r, %r) == %r but expected %r" % - (code, input, got, expected)) - (got,) = struct.unpack(code, got) - if got != expectedback: - raise TestFailed("unpack(%r, %r) == %r but expected %r" % - (code, input, got, expectedback)) - -test_p_code() - - -########################################################################### -# SF bug 705836. "f" had a severe rounding bug, where a carry -# from the low-order discarded bits could propagate into the exponent -# field, causing the result to be wrong by a factor of 2. - -def test_705836(): - import math - - for base in range(1, 33): - # smaller <- largest representable float less than base. - delta = 0.5 - while base - delta / 2.0 != base: - delta /= 2.0 - smaller = base - delta - # Packing this rounds away a solid string of trailing 1 bits. - packed = struct.pack("f", smaller) - verify(bigpacked == string_reverse(packed), - ">f pack should be byte-reversal of f", bigpacked)[0] - verify(base == unpacked) - - # Largest finite IEEE single. - big = (1 << 24) - 1 - big = math.ldexp(big, 127 - 23) - packed = struct.pack(">f", big) - unpacked = struct.unpack(">f", packed)[0] - verify(big == unpacked) - - # The same, but tack on a 1 bit so it rounds up to infinity. - big = (1 << 25) - 1 - big = math.ldexp(big, 127 - 24) - try: - packed = struct.pack(">f", big) - except OverflowError: - pass - else: - TestFailed("expected OverflowError") - -test_705836()