pypy / pypy / interpreter /

Full commit
Seo Sanghyeon 3fc3657 
Armin Rigo 064465c 
Armin Rigo 6a00154 

holger krekel 0e83ec0 
Armin Rigo 6a00154 

rxe 34ed06a 

Amaury Forgeot d… 93ae975 

rxe 34ed06a 
holger krekel a90000e 
rxe 34ed06a 

holger krekel a90000e 

Jean-Philippe St… c775f9d 
rxe 34ed06a 
Michael Hudson-D… 17af98e 
rxe 34ed06a 

Armin Rigo 6a00154 
rxe 34ed06a 
Armin Rigo 6a00154 

Seo Sanghyeon 3fc3657 
Samuele Pedroni 33dffa3 
Armin Rigo 88aa0d6 
Christian Tismer c222260 
Samuele Pedroni 29edf3e 
Christian Tismer c222260 

rxe 34ed06a 

Armin Rigo 6a00154 
Christian Tismer 0583ba2 

rxe 34ed06a 
Armin Rigo 7bedba2 
rxe 34ed06a 

holger krekel a90000e 
rxe 34ed06a 

Armin Rigo 6a00154 
rxe 34ed06a 

Anders Lehmann dda302c 
holger krekel a90000e 
rxe 34ed06a 
holger krekel a90000e 

Armin Rigo 6a00154 

Armin Rigo 7bedba2 
Michael Hudson-D… cfbddae 

Michael Hudson-D… ae8cc57 

Armin Rigo 7bedba2 
Armin Rigo 6a00154 

Armin Rigo 88aa0d6 
Armin Rigo 6a00154 

Armin Rigo 30c059b 

Armin Rigo 88aa0d6 
Amaury Forgeot d… cb9fc56 

Armin Rigo 88aa0d6 

rxe 8a70450 

Armin Rigo 88aa0d6 

Armin Rigo 6a00154 
Armin Rigo 88aa0d6 

Armin Rigo 6a00154 

rxe 34ed06a 

holger krekel a90000e 
rxe 34ed06a 
rxe 8a70450 
rxe 34ed06a 
holger krekel a90000e 
rxe 34ed06a 

Armin Rigo 88aa0d6 

from pypy.interpreter import error
from pypy.interpreter import baseobjspace, module, main
import sys
import code
import time

class Completer:
    """ Stolen mostly from CPython's """
    def __init__(self, space, w_globals): = space
        self.w_globals = w_globals

    def complete(self, text, state):
        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
                self.matches = self.global_matches(text)
            return self.matches[state]

        except IndexError:
            return None

    def global_matches(self, text):
        import keyword
        w_res =, "keys")
        namespace_keys =
        w_res =,
        builtin_keys =

        matches = []
        n = len(text)

        for l in [namespace_keys, builtin_keys, keyword.kwlist]:
            for word in l:
                if word[:n] == text and word != "__builtins__":

        return matches

    def attr_matches(self, text):
        import re
        m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
        if not m:

        expr, attr =, 3)
        s =
        w_obj = s.eval(expr, self.w_globals, self.w_globals)
        words = self.get_words(w_obj)

        w_clz = s.getattr(w_obj, s.wrap("__class__"))
        words += self.get_class_members(w_clz)

        matches = []
        n = len(attr)
        for word in words:
            if word[:n] == attr and word != "__builtins__":
                matches.append("%s.%s" % (expr, word))

        return matches

    def get_words(self, w_clz):
        s =
        w_dir_func = s.builtin.get("dir")
        w_res = s.call_function(w_dir_func, w_clz)
        return s.unwrap(w_res)

    def get_class_members(self, w_clz):
        s =
        words = self.get_words(w_clz)
            w_bases = s.getattr(w_clz, s.wrap("__bases__"))
            bases_w = s.fixedview(w_bases)

        except error.OperationError:
            return words

        for w_clz in bases_w:
            words += self.get_class_members(w_clz)

        return words

class PyPyConsole(code.InteractiveConsole):
    def __init__(self, objspace, verbose=0, completer=False):
        code.InteractiveConsole.__init__(self) = objspace
        self.verbose = verbose
        space =
        self.console_compiler_flags = 0

        mainmodule = main.ensure__main__(space)
        self.w_globals = mainmodule.w_dict
        space.setitem(self.w_globals, space.wrap('__builtins__'), space.builtin)
        if completer:

        # forbidden:
        #space.exec_("__pytrace__ = 0", self.w_globals, self.w_globals)
        space.setitem(self.w_globals, space.wrap('__pytrace__'),space.wrap(0))
        self.tracelevel = 0
        self.console_locals = {}

    def enable_command_line_completer(self):
            import readline
            # Keep here to save windoze tears
            readline.set_completer(Completer(, self.w_globals).complete)
            readline.parse_and_bind("tab: complete")

            except IOError:
                pass # guess it doesn't exit

            import atexit

    def interact(self, banner=None):
        #banner = "Python %s in pypy\n%s / %s" % (
        #    sys.version, self.__class__.__name__,
        w_sys =
        major, minor, micro, tag, rev ='pypy_version_info'))
        elapsed = time.time() -
        version = "%d.%d.%d" % (major, minor, micro)
        if tag != "final":
            version += "-%s%d" %(tag, rev)
        banner = "PyPy %s in %r on top of Python %s (startuptime: %.2f secs)" % (
            version,, sys.version.split()[0], elapsed)
        code.InteractiveConsole.interact(self, banner)

    def raw_input(self, prompt=""):
        # add a character to the PyPy prompt so that you know where you
        # are when you debug it with "python -i"
            return code.InteractiveConsole.raw_input(self, prompt[0] + prompt)
        except KeyboardInterrupt:
            # fires into an interpreter-level console
            banner = ("Python %s on %s\n" % (sys.version, sys.platform) +
                      "*** Entering interpreter-level console ***")
            local = self.console_locals
            # don't copy attributes that look like names that came
            # from self.w_globals (itself the main offender) as they
            # would then get copied back into the applevel namespace.
            local.update(dict([(k,v) for (k, v) in self.__dict__.iteritems()
                               if not k.startswith('w_')]))
            del local['locals']
            for w_name in
                local['w_' +] = (
          , w_name))
            code.interact(banner=banner, local=local)
            # copy back 'w_' names
            for name in local:
                if name.startswith('w_'):
            print '*** Leaving interpreter-level console ***'

    def runcode(self, code):
        raise NotImplementedError

    def runsource(self, source, ignored_filename="<input>", symbol="single"):
        # the following hacked file name is recognized specially by
        hacked_filename = '<inline>\n' + source
        compiler =

        # CPython 2.6 turns console input into unicode
        if isinstance(source, unicode):
            source = source.encode(sys.stdin.encoding)

        def doit():
            # compile the provided input
            code = compiler.compile_command(source, hacked_filename, symbol,
            if code is None:
                raise IncompleteInput
            self.console_compiler_flags |= compiler.getcodeflags(code)

            # execute it
                code.exec_code(, self.w_globals, self.w_globals)
                if self.tracelevel:

        # run doit() in an exception-catching box
            main.run_toplevel(, doit, verbose=self.verbose)
        except IncompleteInput:
            return 1
            return 0

    def settrace(self):
        if self.tracelevel:

    def checktrace(self):
        s =

        # Did we modify __pytrace__
        tracelevel = s.int_w(s.getitem(self.w_globals,

        if self.tracelevel > 0 and tracelevel == 0:
            print "Tracing disabled"

        if self.tracelevel == 0 and tracelevel > 0:
            print "Tracing enabled"

        self.tracelevel = tracelevel

class IncompleteInput(Exception):