1. Pypy
  2. Untitled project
  3. pypy

Commits

Matti Picus  committed 2312717 Merge

merge default into branch

  • Participants
  • Parent commits 65ca8e4, 2ebf68f
  • Branches argsort-segfault

Comments (0)

Files changed (39)

File .hgtags

View file
  • Ignore whitespace
 d8ac7d23d3ec5f9a0fa1264972f74a010dbfd07f release-1.6
 ff4af8f318821f7f5ca998613a60fca09aa137da release-1.7
 07e08e9c885ca67d89bcc304e45a32346daea2fa release-2.0-beta-1
+9b623bc48b5950cf07184462a0e48f2c4df0d720 pypy-2.1-beta1-arm
+9b623bc48b5950cf07184462a0e48f2c4df0d720 pypy-2.1-beta1-arm
+ab0dd631c22015ed88e583d9fdd4c43eebf0be21 pypy-2.1-beta1-arm

File LICENSE

View file
  • Ignore whitespace
     Impara, Germany
     Change Maker, Sweden 
     University of California Berkeley, USA
+    Google Inc.
 
 The PyPy Logo as used by http://speed.pypy.org and others was created
 by Samuel Reis and is distributed on terms of Creative Commons Share Alike

File lib_pypy/_curses.py

View file
  • Ignore whitespace
 def _chtype(ch):
     return int(ffi.cast("chtype", ch))
 
+def _texttype(text):
+    if isinstance(text, str):
+        return text
+    elif isinstance(text, unicode):
+        return str(text)   # default encoding
+    else:
+        raise TypeError("str or unicode expected, got a '%s' object"
+                        % (type(text).__name__,))
+
 
 def _extract_yx(args):
     if len(args) >= 2:
 
     @_argspec(1, 1, 2)
     def addstr(self, y, x, text, attr=None):
+        text = _texttype(text)
         if attr is not None:
             attr_old = lib.getattrs(self._win)
             lib.wattrset(self._win, attr)
 
     @_argspec(2, 1, 2)
     def addnstr(self, y, x, text, n, attr=None):
+        text = _texttype(text)
         if attr is not None:
             attr_old = lib.getattrs(self._win)
             lib.wattrset(self._win, attr)
 
     @_argspec(1, 1, 2)
     def insstr(self, y, x, text, attr=None):
+        text = _texttype(text)
         if attr is not None:
             attr_old = lib.getattrs(self._win)
             lib.wattrset(self._win, attr)
 
     @_argspec(2, 1, 2)
     def insnstr(self, y, x, text, n, attr=None):
+        text = _texttype(text)
         if attr is not None:
             attr_old = lib.getattrs(self._win)
             lib.wattrset(self._win, attr)
 
 
 def putp(text):
+    text = _texttype(text)
     return _check_ERR(lib.putp(text), "putp")
 
 

File lib_pypy/_tkinter/__init__.py

View file
  • Ignore whitespace
+# _tkinter package -- low-level interface to libtk and libtcl.
+#
+# This is an internal module, applications should "import Tkinter" instead.
+#
+# This version is based on cffi, and is a translation of _tkinter.c
+# from CPython, version 2.7.4.
+
+class TclError(Exception):
+    pass
+
+from .tklib import tklib, tkffi
+from .app import TkApp
+
+TK_VERSION = tkffi.string(tklib.get_tk_version())
+TCL_VERSION = tkffi.string(tklib.get_tcl_version())
+
+READABLE = tklib.TCL_READABLE
+WRITABLE = tklib.TCL_WRITABLE
+EXCEPTION = tklib.TCL_EXCEPTION
+
+def create(screenName=None, baseName=None, className=None,
+           interactive=False, wantobjects=False, wantTk=True,
+           sync=False, use=None):
+    return TkApp(screenName, baseName, className,
+                 interactive, wantobjects, wantTk, sync, use)
+
+def _flatten(item):
+    def _flatten1(output, item, depth):
+        if depth > 1000:
+            raise ValueError("nesting too deep in _flatten")
+        if not isinstance(item, (list, tuple)):
+            raise TypeError("argument must be sequence")
+        # copy items to output tuple
+        for o in item:
+            if isinstance(o, (list, tuple)):
+                _flatten1(output, o, depth + 1)
+            elif o is not None:
+                output.append(o)
+
+    result = []
+    _flatten1(result, item, 0)
+    return tuple(result)
+    

File lib_pypy/_tkinter/app.py

View file
  • Ignore whitespace
+# The TkApp class.
+
+from .tklib import tklib, tkffi
+from . import TclError
+from .tclobj import TclObject, FromObj, AsObj, TypeCache
+
+import sys
+
+def varname_converter(input):
+    if isinstance(input, TclObject):
+        return input.string
+    return input
+
+
+def Tcl_AppInit(app):
+    if tklib.Tcl_Init(app.interp) == tklib.TCL_ERROR:
+        app.raiseTclError()
+    skip_tk_init = tklib.Tcl_GetVar(
+        app.interp, "_tkinter_skip_tk_init", tklib.TCL_GLOBAL_ONLY)
+    if skip_tk_init and tkffi.string(skip_tk_init) == "1":
+        return
+
+    if tklib.Tk_Init(app.interp) == tklib.TCL_ERROR:
+        app.raiseTclError()
+
+class _CommandData(object):
+    def __new__(cls, app, name, func):
+        self = object.__new__(cls)
+        self.app = app
+        self.name = name
+        self.func = func
+        handle = tkffi.new_handle(self)
+        app._commands[name] = handle  # To keep the command alive
+        return tkffi.cast("ClientData", handle)
+
+    @tkffi.callback("Tcl_CmdProc")
+    def PythonCmd(clientData, interp, argc, argv):
+        self = tkffi.from_handle(clientData)
+        assert self.app.interp == interp
+        try:
+            args = [tkffi.string(arg) for arg in argv[1:argc]]
+            result = self.func(*args)
+            obj = AsObj(result)
+            tklib.Tcl_SetObjResult(interp, obj)
+        except:
+            self.app.errorInCmd = True
+            self.app.exc_info = sys.exc_info()
+            return tklib.TCL_ERROR
+        else:
+            return tklib.TCL_OK
+
+    @tkffi.callback("Tcl_CmdDeleteProc")
+    def PythonCmdDelete(clientData):
+        self = tkffi.from_handle(clientData)
+        app = self.app
+        del app._commands[self.name]
+        return
+
+
+class TkApp(object):
+    def __new__(cls, screenName, baseName, className,
+                interactive, wantobjects, wantTk, sync, use):
+        if not wantobjects:
+            raise NotImplementedError("wantobjects=True only")
+        self = object.__new__(cls)
+        self.interp = tklib.Tcl_CreateInterp()
+        self._wantobjects = wantobjects
+        self.threaded = bool(tklib.Tcl_GetVar2Ex(
+            self.interp, "tcl_platform", "threaded",
+            tklib.TCL_GLOBAL_ONLY))
+        self.thread_id = tklib.Tcl_GetCurrentThread()
+        self.dispatching = False
+        self.quitMainLoop = False
+        self.errorInCmd = False
+
+        self._typeCache = TypeCache()
+        self._commands = {}
+
+        # Delete the 'exit' command, which can screw things up
+        tklib.Tcl_DeleteCommand(self.interp, "exit")
+
+        if screenName is not None:
+            tklib.Tcl_SetVar2(self.interp, "env", "DISPLAY", screenName,
+                              tklib.TCL_GLOBAL_ONLY)
+
+        if interactive:
+            tklib.Tcl_SetVar(self.interp, "tcl_interactive", "1",
+                             tklib.TCL_GLOBAL_ONLY)
+        else:
+            tklib.Tcl_SetVar(self.interp, "tcl_interactive", "0",
+                             tklib.TCL_GLOBAL_ONLY)
+
+        # This is used to get the application class for Tk 4.1 and up
+        argv0 = className.lower()
+        tklib.Tcl_SetVar(self.interp, "argv0", argv0,
+                         tklib.TCL_GLOBAL_ONLY)
+
+        if not wantTk:
+            tklib.Tcl_SetVar(self.interp, "_tkinter_skip_tk_init", "1",
+                             tklib.TCL_GLOBAL_ONLY)
+
+        # some initial arguments need to be in argv
+        if sync or use:
+            args = ""
+            if sync:
+                args += "-sync"
+            if use:
+                if sync:
+                    args += " "
+                args += "-use " + use
+
+            tklib.Tcl_SetVar(self.interp, "argv", args,
+                             tklib.TCL_GLOBAL_ONLY)
+
+        Tcl_AppInit(self)
+        # EnableEventHook()
+        return self
+
+    def __del__(self):
+        tklib.Tcl_DeleteInterp(self.interp)
+        # DisableEventHook()
+
+    def raiseTclError(self):
+        if self.errorInCmd:
+            self.errorInCmd = False
+            raise self.exc_info[0], self.exc_info[1], self.exc_info[2]
+        raise TclError(tkffi.string(tklib.Tcl_GetStringResult(self.interp)))
+
+    def wantobjects(self):
+        return self._wantobjects
+
+    def _check_tcl_appartment(self):
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            raise RuntimeError("Calling Tcl from different appartment")
+
+    def loadtk(self):
+        # We want to guard against calling Tk_Init() multiple times
+        err = tklib.Tcl_Eval(self.interp, "info exists     tk_version")
+        if err == tklib.TCL_ERROR:
+            self.raiseTclError()
+        tk_exists = tklib.Tcl_GetStringResult(self.interp)
+        if not tk_exists or tkffi.string(tk_exists) != "1":
+            err = tklib.Tk_Init(self.interp)
+            if err == tklib.TCL_ERROR:
+                self.raiseTclError()
+
+    def _var_invoke(self, func, *args, **kwargs):
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            # The current thread is not the interpreter thread.
+            # Marshal the call to the interpreter thread, then wait
+            # for completion.
+            raise NotImplementedError("Call from another thread")
+        return func(*args, **kwargs)
+
+    def _getvar(self, name1, name2=None, global_only=False):
+        name1 = varname_converter(name1)
+        if not name2:
+            name2 = tkffi.NULL
+        flags=tklib.TCL_LEAVE_ERR_MSG
+        if global_only:
+            flags |= tklib.TCL_GLOBAL_ONLY
+        res = tklib.Tcl_GetVar2Ex(self.interp, name1, name2, flags)
+        if not res:
+            self.raiseTclError()
+        assert self._wantobjects
+        return FromObj(self, res)
+
+    def _setvar(self, name1, value, global_only=False):
+        name1 = varname_converter(name1)
+        newval = AsObj(value)
+        flags=tklib.TCL_LEAVE_ERR_MSG
+        if global_only:
+            flags |= tklib.TCL_GLOBAL_ONLY
+        res = tklib.Tcl_SetVar2Ex(self.interp, name1, tkffi.NULL,
+                                  newval, flags)
+        if not res:
+            self.raiseTclError()
+
+    def _unsetvar(self, name1, name2=None, global_only=False):
+        name1 = varname_converter(name1)
+        if not name2:
+            name2 = tkffi.NULL
+        flags=tklib.TCL_LEAVE_ERR_MSG
+        if global_only:
+            flags |= tklib.TCL_GLOBAL_ONLY
+        res = tklib.Tcl_UnsetVar2(self.interp, name1, name2, flags)
+        if res == tklib.TCL_ERROR:
+            self.raiseTclError()
+
+    def getvar(self, name1, name2=None):
+        return self._var_invoke(self._getvar, name1, name2)
+
+    def globalgetvar(self, name1, name2=None):
+        return self._var_invoke(self._getvar, name1, name2, global_only=True)
+
+    def setvar(self, name1, value):
+        return self._var_invoke(self._setvar, name1, value)
+
+    def globalsetvar(self, name1, value):
+        return self._var_invoke(self._setvar, name1, value, global_only=True)
+
+    def unsetvar(self, name1, name2=None):
+        return self._var_invoke(self._unsetvar, name1, name2)
+
+    def globalunsetvar(self, name1, name2=None):
+        return self._var_invoke(self._unsetvar, name1, name2, global_only=True)
+
+    # COMMANDS
+
+    def createcommand(self, cmdName, func):
+        if not callable(func):
+            raise TypeError("command not callable")
+
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            raise NotImplementedError("Call from another thread")
+
+        clientData = _CommandData(self, cmdName, func)
+
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            raise NotImplementedError("Call from another thread")
+
+        res = tklib.Tcl_CreateCommand(
+            self.interp, cmdName, _CommandData.PythonCmd,
+            clientData, _CommandData.PythonCmdDelete)
+        if not res:
+            raise TclError("can't create Tcl command")
+
+    def deletecommand(self, cmdName):
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            raise NotImplementedError("Call from another thread")
+
+        res = tklib.Tcl_DeleteCommand(self.interp, cmdName)
+        if res == -1:
+            raise TclError("can't delete Tcl command")
+
+    def call(self, *args):
+        flags = tklib.TCL_EVAL_DIRECT | tklib.TCL_EVAL_GLOBAL
+
+        # If args is a single tuple, replace with contents of tuple
+        if len(args) == 1 and isinstance(args[0], tuple):
+            args = args[0]
+
+        if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
+            # We cannot call the command directly. Instead, we must
+            # marshal the parameters to the interpreter thread.
+            raise NotImplementedError("Call from another thread")
+
+        objects = tkffi.new("Tcl_Obj*[]", len(args))
+        argc = len(args)
+        try:
+            for i, arg in enumerate(args):
+                if arg is None:
+                    argc = i
+                    break
+                obj = AsObj(arg)
+                tklib.Tcl_IncrRefCount(obj)
+                objects[i] = obj
+
+            res = tklib.Tcl_EvalObjv(self.interp, argc, objects, flags)
+            if res == tklib.TCL_ERROR:
+                self.raiseTclError()
+            else:
+                result = self._callResult()
+        finally:
+            for obj in objects:
+                if obj:
+                    tklib.Tcl_DecrRefCount(obj)
+        return result
+
+    def _callResult(self):
+        assert self._wantobjects
+        value = tklib.Tcl_GetObjResult(self.interp)
+        # Not sure whether the IncrRef is necessary, but something
+        # may overwrite the interpreter result while we are
+        # converting it.
+        tklib.Tcl_IncrRefCount(value)
+        res = FromObj(self, value)
+        tklib.Tcl_DecrRefCount(value)
+        return res
+
+    def eval(self, script):
+        self._check_tcl_appartment()
+        res = tklib.Tcl_Eval(self.interp, script)
+        if res == tklib.TCL_ERROR:
+            self.raiseTclError()
+        return tkffi.string(tklib.Tcl_GetStringResult(self.interp))
+
+    def evalfile(self, filename):
+        self._check_tcl_appartment()
+        res = tklib.Tcl_EvalFile(self.interp, filename)
+        if res == tklib.TCL_ERROR:
+            self.raiseTclError()
+        return tkffi.string(tklib.Tcl_GetStringResult(self.interp))
+
+    def split(self, arg):
+        if isinstance(arg, tuple):
+            return self._splitObj(arg)
+        else:
+            return self._split(arg)
+
+    def splitlist(self, arg):
+        if isinstance(arg, tuple):
+            return arg
+        if isinstance(arg, unicode):
+            arg = arg.encode('utf8')
+
+        argc = tkffi.new("int*")
+        argv = tkffi.new("char***")
+        res = tklib.Tcl_SplitList(self.interp, arg, argc, argv)
+        if res == tklib.TCL_ERROR:
+            self.raiseTclError()
+
+        result = tuple(tkffi.string(argv[0][i])
+                       for i in range(argc[0]))
+        tklib.Tcl_Free(argv[0])
+        return result
+
+    def _splitObj(self, arg):
+        if isinstance(arg, tuple):
+            size = len(arg)
+            # Recursively invoke SplitObj for all tuple items.
+            # If this does not return a new object, no action is
+            # needed.
+            result = None
+            newelems = (self._splitObj(elem) for elem in arg)
+            for elem, newelem in zip(arg, newelems):
+                if elem is not newelem:
+                    return newelems
+        elif isinstance(arg, str):
+            argc = tkffi.new("int*")
+            argv = tkffi.new("char***")
+            res = tklib.Tcl_SplitList(tkffi.NULL, arg, argc, argv)
+            if res == tklib.TCL_ERROR:
+                return arg
+            tklib.Tcl_Free(argv[0])
+            if argc[0] > 1:
+                return self._split(arg)
+        return arg
+
+    def _split(self, arg):
+        argc = tkffi.new("int*")
+        argv = tkffi.new("char***")
+        res = tklib.Tcl_SplitList(tkffi.NULL, arg, argc, argv)
+        if res == tklib.TCL_ERROR:
+            # Not a list.
+            # Could be a quoted string containing funnies, e.g. {"}.
+            # Return the string itself.
+            return arg
+
+        try:
+            if argc[0] == 0:
+                return ""
+            elif argc[0] == 1:
+                return argv[0][0]
+            else:
+                return (self._split(argv[0][i])
+                        for i in range(argc[0]))
+        finally:
+            tklib.Tcl_Free(argv[0])
+
+    def getboolean(self, s):
+        if isinstance(s, int):
+            return s
+        v = tkffi.new("int*")
+        res = tklib.Tcl_GetBoolean(self.interp, s, v)
+        if res == tklib.TCL_ERROR:
+            self.raiseTclError()
+
+    def mainloop(self, threshold):
+        self._check_tcl_appartment()
+        self.dispatching = True
+        while (tklib.Tk_GetNumMainWindows() > threshold and
+               not self.quitMainLoop and not self.errorInCmd):
+
+            if self.threaded:
+                result = tklib.Tcl_DoOneEvent(0)
+            else:
+                raise NotImplementedError("TCL configured without threads")
+
+            if result < 0:
+                break
+        self.dispatching = False
+        self.quitMainLoop = False
+        if self.errorInCmd:
+            self.errorInCmd = False
+            raise self.exc_info[0], self.exc_info[1], self.exc_info[2]
+
+    def quit(self):
+        self.quitMainLoop = True

File lib_pypy/_tkinter/tclobj.py

View file
  • Ignore whitespace
+# TclObject, conversions with Python objects
+
+from .tklib import tklib, tkffi
+
+class TypeCache(object):
+    def __init__(self):
+        self.BooleanType = tklib.Tcl_GetObjType("boolean")
+        self.ByteArrayType = tklib.Tcl_GetObjType("bytearray")
+        self.DoubleType = tklib.Tcl_GetObjType("double")
+        self.IntType = tklib.Tcl_GetObjType("int")
+        self.ListType = tklib.Tcl_GetObjType("list")
+        self.ProcBodyType = tklib.Tcl_GetObjType("procbody")
+        self.StringType = tklib.Tcl_GetObjType("string")
+        
+
+def FromObj(app, value):
+    """Convert a TclObj pointer into a Python object."""
+    typeCache = app._typeCache
+    if not value.typePtr:
+        buf = tkffi.buffer(value.bytes, value.length)
+        result = buf[:]
+        # If the result contains any bytes with the top bit set, it's
+        # UTF-8 and we should decode it to Unicode.
+        try:
+            result.decode('ascii')
+        except UnicodeDecodeError:
+            result = result.decode('utf8')
+        return result
+
+    elif value.typePtr == typeCache.BooleanType:
+        return result
+    elif value.typePtr == typeCache.ByteArrayType:
+        return result
+    elif value.typePtr == typeCache.DoubleType:
+        return value.internalRep.doubleValue
+    elif value.typePtr == typeCache.IntType:
+        return value.internalRep.longValue
+    elif value.typePtr == typeCache.ListType:
+        size = tkffi.new('int*')
+        status = tklib.Tcl_ListObjLength(app.interp, value, size)
+        if status == tklib.TCL_ERROR:
+            app.raiseTclError()
+        result = []
+        tcl_elem = tkffi.new("Tcl_Obj**")
+        for i in range(size[0]):
+            status = tklib.Tcl_ListObjIndex(app.interp,
+                                            value, i, tcl_elem)
+            if status == tklib.TCL_ERROR:
+                app.raiseTclError()
+            result.append(FromObj(app, tcl_elem[0]))
+        return tuple(result)
+    elif value.typePtr == typeCache.ProcBodyType:
+        return result
+    elif value.typePtr == typeCache.StringType:
+        buf = tklib.Tcl_GetUnicode(value)
+        length = tklib.Tcl_GetCharLength(value)
+        buf = tkffi.buffer(tkffi.cast("char*", buf), length*2)[:]
+        return buf.decode('utf-16')
+
+    return TclObject(value)
+
+def AsObj(value):
+    if isinstance(value, str):
+        return tklib.Tcl_NewStringObj(value, len(value))
+    elif isinstance(value, bool):
+        return tklib.Tcl_NewBooleanObj(value)
+    elif isinstance(value, int):
+        return tklib.Tcl_NewLongObj(value)
+    elif isinstance(value, float):
+        return tklib.Tcl_NewDoubleObj(value)
+    elif isinstance(value, tuple):
+        argv = tkffi.new("Tcl_Obj*[]", len(value))
+        for i in range(len(value)):
+            argv[i] = AsObj(value[i])
+        return tklib.Tcl_NewListObj(len(value), argv)
+    elif isinstance(value, unicode):
+        encoded = value.encode('utf-16')[2:]
+        buf = tkffi.new("char[]", encoded)
+        inbuf = tkffi.cast("Tcl_UniChar*", buf)
+        return tklib.Tcl_NewUnicodeObj(buf, len(encoded)/2)
+    elif isinstance(value, TclObject):
+        tklib.Tcl_IncrRefCount(value._value)
+        return value._value
+    else:
+        return AsObj(str(value))
+
+class TclObject(object):
+    def __new__(cls, value):
+        self = object.__new__(cls)
+        tklib.Tcl_IncrRefCount(value)
+        self._value = value
+        self._string = None
+        return self
+
+    def __del__(self):
+        tklib.Tcl_DecrRefCount(self._value)
+
+    def __str__(self):
+        if self._string and isinstance(self._string, str):
+            return self._string
+        return tkffi.string(tklib.Tcl_GetString(self._value))
+
+    @property
+    def string(self):
+        if self._string is None:
+            length = tkffi.new("int*")
+            s = tklib.Tcl_GetStringFromObj(self._value, length)
+            value = tkffi.buffer(s, length[0])[:]
+            try:
+                value.decode('ascii')
+            except UnicodeDecodeError:
+                value = value.decode('utf8')
+            self._string = value
+        return self._string

File lib_pypy/_tkinter/tklib.py

View file
  • Ignore whitespace
+# C bindings with libtcl and libtk.
+
+from cffi import FFI
+
+tkffi = FFI()
+
+tkffi.cdef("""
+char *get_tk_version();
+char *get_tcl_version();
+#define TCL_READABLE ...
+#define TCL_WRITABLE ...
+#define TCL_EXCEPTION ...
+#define TCL_ERROR ...
+#define TCL_OK ...
+
+#define TCL_LEAVE_ERR_MSG ...
+#define TCL_GLOBAL_ONLY ...
+#define TCL_EVAL_DIRECT ...
+#define TCL_EVAL_GLOBAL ...
+
+typedef unsigned short Tcl_UniChar;
+typedef ... Tcl_Interp;
+typedef ...* Tcl_ThreadId;
+typedef ...* Tcl_Command;
+
+typedef struct Tcl_ObjType {
+    char *name;
+    ...;
+} Tcl_ObjType;
+typedef struct Tcl_Obj {
+    char *bytes;
+    int length;
+    Tcl_ObjType *typePtr;
+    union {			/* The internal representation: */
+	long longValue;		/*   - an long integer value. */
+	double doubleValue;	/*   - a double-precision floating value. */
+	struct {		/*   - internal rep as two pointers. */
+	    void *ptr1;
+	    void *ptr2;
+	} twoPtrValue;
+    } internalRep;
+    ...;
+} Tcl_Obj;
+
+Tcl_Interp *Tcl_CreateInterp();
+void Tcl_DeleteInterp(Tcl_Interp* interp);
+int Tcl_Init(Tcl_Interp* interp);
+int Tk_Init(Tcl_Interp* interp);
+
+void Tcl_Free(char* ptr);
+
+const char *Tcl_SetVar(Tcl_Interp* interp, const char* varName, const char* newValue, int flags);
+const char *Tcl_SetVar2(Tcl_Interp* interp, const char* name1, const char* name2, const char* newValue, int flags);
+const char *Tcl_GetVar(Tcl_Interp* interp, const char* varName, int flags);
+Tcl_Obj *Tcl_SetVar2Ex(Tcl_Interp* interp, const char* name1, const char* name2, Tcl_Obj* newValuePtr, int flags);
+Tcl_Obj *Tcl_GetVar2Ex(Tcl_Interp* interp, const char* name1, const char* name2, int flags);
+int Tcl_UnsetVar2(Tcl_Interp* interp, const char* name1, const char* name2, int flags);
+const Tcl_ObjType *Tcl_GetObjType(const char* typeName);
+
+Tcl_Obj *Tcl_NewStringObj(const char* bytes, int length);
+Tcl_Obj *Tcl_NewUnicodeObj(const Tcl_UniChar* unicode, int numChars);
+Tcl_Obj *Tcl_NewLongObj(long longValue);
+Tcl_Obj *Tcl_NewBooleanObj(int boolValue);
+Tcl_Obj *Tcl_NewDoubleObj(double doubleValue);
+
+void Tcl_IncrRefCount(Tcl_Obj* objPtr);
+void Tcl_DecrRefCount(Tcl_Obj* objPtr);
+
+int Tcl_GetBoolean(Tcl_Interp* interp, const char* src, int* boolPtr);
+char *Tcl_GetString(Tcl_Obj* objPtr);
+char *Tcl_GetStringFromObj(Tcl_Obj* objPtr, int* lengthPtr);
+
+Tcl_UniChar *Tcl_GetUnicode(Tcl_Obj* objPtr);
+int Tcl_GetCharLength(Tcl_Obj* objPtr);
+
+Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj* const objv[]);
+int Tcl_ListObjLength(Tcl_Interp* interp, Tcl_Obj* listPtr, int* intPtr);
+int Tcl_ListObjIndex(Tcl_Interp* interp, Tcl_Obj* listPtr, int index, Tcl_Obj** objPtrPtr);
+int Tcl_SplitList(Tcl_Interp* interp, char* list, int* argcPtr, const char*** argvPtr);
+
+int Tcl_Eval(Tcl_Interp* interp, const char* script);
+int Tcl_EvalFile(Tcl_Interp* interp, const char* filename);
+int Tcl_EvalObjv(Tcl_Interp* interp, int objc, Tcl_Obj** objv, int flags);
+Tcl_Obj *Tcl_GetObjResult(Tcl_Interp* interp);
+const char *Tcl_GetStringResult(Tcl_Interp* interp);
+void Tcl_SetObjResult(Tcl_Interp* interp, Tcl_Obj* objPtr);
+
+typedef void* ClientData;
+typedef int Tcl_CmdProc(
+        ClientData clientData,
+        Tcl_Interp *interp,
+        int argc,
+        const char *argv[]);
+typedef void Tcl_CmdDeleteProc(
+        ClientData clientData);
+Tcl_Command Tcl_CreateCommand(Tcl_Interp* interp, const char* cmdName, Tcl_CmdProc proc, ClientData clientData, Tcl_CmdDeleteProc deleteProc);
+int Tcl_DeleteCommand(Tcl_Interp* interp, const char* cmdName);
+
+Tcl_ThreadId Tcl_GetCurrentThread();
+int Tcl_DoOneEvent(int flags);
+
+int Tk_GetNumMainWindows();
+""")
+
+tklib = tkffi.verify("""
+#include <tcl.h>
+#include <tk.h>
+
+char *get_tk_version() { return TK_VERSION; }
+char *get_tcl_version() { return TCL_VERSION; }
+""",
+include_dirs=['/usr/include/tcl'],
+libraries=['tcl', 'tk'],
+)

File lib_pypy/cffi/api.py

View file
  • Ignore whitespace
     backend = ffi._backend
     try:
         if '.' not in name and '/' not in name:
-            raise OSError
+            raise OSError("library not found: %r" % (name,))
         backendlib = backend.load_library(name, flags)
     except OSError:
         import ctypes.util
         path = ctypes.util.find_library(name)
         if path is None:
-            raise OSError("library not found: %r" % (name,))
+            raise     # propagate the original OSError
         backendlib = backend.load_library(path, flags)
     copied_enums = []
     #

File pypy/interpreter/baseobjspace.py

  • Ignore whitespace
File contents unchanged.

File pypy/interpreter/mixedmodule.py

  • Ignore whitespace
File contents unchanged.

File pypy/module/_cffi_backend/ctypefunc.py

View file
  • Ignore whitespace
                "with verify() (see pypy/module/_cffi_backend/ctypefunc.py "
                "for details)"))
 
-        if USE_C_LIBFFI_MSVC and is_result_type:
-            # MSVC returns small structures in registers.  Pretend int32 or
-            # int64 return type.  This is needed as a workaround for what
-            # is really a bug of libffi_msvc seen as an independent library
-            # (ctypes has a similar workaround).
-            if ctype.size <= 4:
-                return clibffi.ffi_type_sint32
-            if ctype.size <= 8:
-                return clibffi.ffi_type_sint64
-
         # walk the fields, expanding arrays into repetitions; first,
         # only count how many flattened fields there are
         nflat = 0
                                "a struct with a zero-length array"))
             nflat += flat
 
+        if USE_C_LIBFFI_MSVC and is_result_type:
+            # MSVC returns small structures in registers.  Pretend int32 or
+            # int64 return type.  This is needed as a workaround for what
+            # is really a bug of libffi_msvc seen as an independent library
+            # (ctypes has a similar workaround).
+            if ctype.size <= 4:
+                return clibffi.ffi_type_sint32
+            if ctype.size <= 8:
+                return clibffi.ffi_type_sint64
+
         # allocate an array of (nflat + 1) ffi_types
         elements = self.fb_alloc(rffi.sizeof(FFI_TYPE_P) * (nflat + 1))
         elements = rffi.cast(FFI_TYPE_PP, elements)

File pypy/module/imp/importing.py

  • Ignore whitespace
File contents unchanged.

File pypy/module/imp/test/test_app.py

View file
  • Ignore whitespace
                 except KeyError:
                     pass
             rmtree(dir_name, True)
+
+    def test_builtin_reimport(self):
+        # from https://bugs.pypy.org/issue1514
+        skip("fix me")
+        import sys, marshal
+
+        old = marshal.loads
+        marshal.loads = 42
+
+        # save, re-import, restore.
+        saved = sys.modules.pop('marshal')
+        __import__('marshal')
+        sys.modules['marshal'] = saved
+
+        assert marshal.loads == 42
+        import marshal
+        assert marshal.loads == 42
+        marshal.loads = old
+
+    def test_builtin_reimport_mess(self):
+        # taken from https://bugs.pypy.org/issue1514, with extra cases
+        # that show a difference with CPython: we can get on CPython
+        # several module objects for the same built-in module :-(
+        skip("several built-in module objects: not supported by pypy")
+        import sys, marshal
+
+        old = marshal.loads
+        marshal.loads = 42
+
+        # save, re-import, restore.
+        saved = sys.modules.pop('marshal')
+        marshal2 = __import__('marshal')
+        assert marshal2 is not marshal
+        assert marshal2.loads is old
+        assert marshal2 is sys.modules['marshal']
+        assert marshal is saved
+        assert marshal.loads == 42
+
+        import marshal
+        assert marshal.loads is old
+
+        sys.modules['marshal'] = saved
+        import marshal
+        assert marshal.loads == 42
+
+        marshal.loads = old

File pypy/module/imp/test/test_import.py

View file
  • Ignore whitespace
         assert sys.path is oldpath
         assert 'setdefaultencoding' in dir(sys)
 
+    def test_reload_builtin_doesnt_clear(self):
+        import sys
+        sys.foobar = "baz"
+        reload(sys)
+        assert sys.foobar == "baz"
+
+    def test_reimport_builtin_simple_case_1(self):
+        import sys, time
+        del time.tzset
+        del sys.modules['time']
+        import time
+        assert hasattr(time, 'tzset')
+
+    def test_reimport_builtin_simple_case_2(self):
+        skip("fix me")
+        import sys, time
+        time.foo = "bar"
+        del sys.modules['time']
+        import time
+        assert not hasattr(time, 'foo')
+
+    def test_reimport_builtin(self):
+        skip("fix me")
+        import sys, time
+        oldpath = sys.path
+        time.tzset = "<test_reimport_builtin removed this>"
+
+        del sys.modules['time']
+        import time as time1
+        assert sys.modules['time'] is time1
+
+        assert time.tzset == "<test_reimport_builtin removed this>"
+
+        reload(time1)   # don't leave a broken time.tzset behind
+        import time
+        assert time.tzset != "<test_reimport_builtin removed this>"
+
     def test_reload_infinite(self):
         import infinite_reload
 

File pypy/module/micronumpy/interp_dtype.py

View file
  • Ignore whitespace
             return space.wrap('=')
         return space.wrap(nonnative_byteorder_prefix)
 
+    def descr_get_str(self, space):
+        size = self.get_size()
+        basic = self.kind
+        if basic == UNICODELTR:
+            size >>= 2
+            endian = byteorder_prefix
+        elif size <= 1:
+            endian = '|'  # ignore
+        elif self.native:
+            endian = byteorder_prefix
+        else:
+            endian = nonnative_byteorder_prefix
+
+        return space.wrap("%s%s%s" % (endian, basic, size))
+
     def descr_get_alignment(self, space):
         return space.wrap(self.itemtype.alignment)
 
     char = interp_attrproperty("char", cls=W_Dtype),
     type = interp_attrproperty_w("w_box_type", cls=W_Dtype),
     byteorder = GetSetProperty(W_Dtype.descr_get_byteorder),
+    str = GetSetProperty(W_Dtype.descr_get_str),
     itemsize = GetSetProperty(W_Dtype.descr_get_itemsize),
     alignment = GetSetProperty(W_Dtype.descr_get_alignment),
     shape = GetSetProperty(W_Dtype.descr_get_shape),
             alternate_constructors=[space.w_float,
                                     space.gettypefor(interp_boxes.W_NumberBox),
                                    ],
-            aliases=["float"],
+            aliases=["float", "double"],
         )
         self.w_complex64dtype = W_ComplexDtype(
             types.Complex64(),
             char='S',
             w_box_type = space.gettypefor(interp_boxes.W_StringBox),
             alternate_constructors=[space.w_str],
+            aliases=["str"],
         )
         self.w_unicodedtype = W_Dtype(
-            types.UnicodeType(1),
+            types.UnicodeType(0),
             num=19,
             kind=UNICODELTR,
             name='unicode',

File pypy/module/micronumpy/interp_numarray.py

View file
  • Ignore whitespace
         addr = self.implementation.get_storage_as_int(space)
         # will explode if it can't
         w_d = space.newdict()
-        space.setitem_str(w_d, 'data', space.newtuple([space.wrap(addr),
-                                                       space.w_False]))
+        space.setitem_str(w_d, 'data',
+                          space.newtuple([space.wrap(addr), space.w_False]))
+        space.setitem_str(w_d, 'shape', self.descr_get_shape(space))
+        space.setitem_str(w_d, 'typestr', self.get_dtype().descr_get_str(space))
+        if self.implementation.order == 'C':
+            # Array is contiguous, no strides in the interface.
+            strides = space.w_None
+        else:
+            strides = self.descr_get_strides(space)
+        space.setitem_str(w_d, 'strides', strides)
         return w_d
 
     w_pypy_data = None

File pypy/module/micronumpy/test/test_dtypes.py

View file
  • Ignore whitespace
         assert dtype('=i8').byteorder == '='
         assert dtype(byteorder + 'i8').byteorder == '='
 
+    def test_dtype_str(self):
+        from numpypy import dtype
+        byteorder = self.native_prefix
+        assert dtype('i8').str == byteorder + 'i8'
+        assert dtype('<i8').str == '<i8'
+        assert dtype('>i8').str == '>i8'
+        assert dtype('int8').str == '|i1'
+        assert dtype('float').str == byteorder + 'f8'
+        # strange
+        assert dtype('string').str == '|S0'
+        assert dtype('unicode').str == byteorder + 'U0'
+        # assert dtype(('string', 7)).str == '|S7'
+        # assert dtype(('unicode', 7)).str == '<U7'
+
     def test_intp(self):
         from numpypy import dtype
         assert dtype('p') == dtype('intp')

File pypy/module/micronumpy/test/test_numarray.py

View file
  • Ignore whitespace
         a = array([1, 2, 3])
         i = a.__array_interface__
         assert isinstance(i['data'][0], int)
+        assert i['shape'] == (3,)
+        assert i['strides'] == None  # Because array is in C order
+        assert i['typestr'] == a.dtype.str
         a = a[::2]
         i = a.__array_interface__
         assert isinstance(i['data'][0], int)

File pypy/module/sys/__init__.py

View file
  • Ignore whitespace
         'flags'                 : 'app.null_sysflags',
     }
 
-    def setbuiltinmodule(self, w_module, name):
-        w_name = self.space.wrap(name)
-        w_modules = self.get('modules')
-        self.space.setitem(w_modules, w_name, w_module)
-
     def startup(self, space):
         if space.config.translating and not we_are_translated():
             # don't get the filesystemencoding at translation time

File pypy/module/sys/app.py

View file
  • Ignore whitespace
     try:
         # first try to print the exception's class name
         stderr = sys.stderr
-        stderr.write(getattr(exctype, '__name__', exctype))
+        stderr.write(str(getattr(exctype, '__name__', exctype)))
         # then attempt to get the str() of the exception
         try:
             s = str(value)
         except:
             s = '<failure of str() on the exception instance>'
-        # then print it, and don't worry too much about the extra space
-        # between the exception class and the ':'
+        # then print it
         if s:
             stderr.write(': %s\n' % (s,))
         else:

File pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py

View file
  • Ignore whitespace
 
 class TestBitfield:
     def check(self, source, expected_ofs_y, expected_align, expected_size):
+        # NOTE: 'expected_*' is the numbers expected from GCC.
+        # The numbers expected from MSVC are not explicitly written
+        # in this file, and will just be taken from the compiler.
         ffi = FFI()
         ffi.cdef("struct s1 { %s };" % source)
         ctype = ffi.typeof("struct s1")
         # verify the information with gcc
-        if sys.platform != "win32":
-            ffi1 = FFI()
-            ffi1.cdef("""
-                static const int Gofs_y, Galign, Gsize;
-                struct s1 *try_with_value(int fieldnum, long long value);
-            """)
-            fnames = [name for name, cfield in ctype.fields
-                           if name and cfield.bitsize > 0]
-            setters = ['case %d: s.%s = value; break;' % iname
-                       for iname in enumerate(fnames)]
-            lib = ffi1.verify("""
-                struct s1 { %s };
-                struct sa { char a; struct s1 b; };
-                #define Gofs_y  offsetof(struct s1, y)
-                #define Galign  offsetof(struct sa, b)
-                #define Gsize   sizeof(struct s1)
-                struct s1 *try_with_value(int fieldnum, long long value)
-                {
-                    static struct s1 s;
-                    memset(&s, 0, sizeof(s));
-                    switch (fieldnum) { %s }
-                    return &s;
-                }
-            """ % (source, ' '.join(setters)))
-            assert lib.Gofs_y == expected_ofs_y
-            assert lib.Galign == expected_align
-            assert lib.Gsize  == expected_size
+        ffi1 = FFI()
+        ffi1.cdef("""
+            static const int Gofs_y, Galign, Gsize;
+            struct s1 *try_with_value(int fieldnum, long long value);
+        """)
+        fnames = [name for name, cfield in ctype.fields
+                       if name and cfield.bitsize > 0]
+        setters = ['case %d: s.%s = value; break;' % iname
+                   for iname in enumerate(fnames)]
+        lib = ffi1.verify("""
+            struct s1 { %s };
+            struct sa { char a; struct s1 b; };
+            #define Gofs_y  offsetof(struct s1, y)
+            #define Galign  offsetof(struct sa, b)
+            #define Gsize   sizeof(struct s1)
+            struct s1 *try_with_value(int fieldnum, long long value)
+            {
+                static struct s1 s;
+                memset(&s, 0, sizeof(s));
+                switch (fieldnum) { %s }
+                return &s;
+            }
+        """ % (source, ' '.join(setters)))
+        if sys.platform == 'win32':
+            expected_ofs_y = lib.Gofs_y
+            expected_align = lib.Galign
+            expected_size  = lib.Gsize
         else:
-            lib = None
-            fnames = None
+            assert (lib.Gofs_y, lib.Galign, lib.Gsize) == (
+                expected_ofs_y, expected_align, expected_size)
         # the real test follows
         assert ffi.offsetof("struct s1", "y") == expected_ofs_y
         assert ffi.alignof("struct s1") == expected_align
         setattr(s, name, value)
         assert getattr(s, name) == value
         raw1 = ffi.buffer(s)[:]
-        if lib is not None:
-            t = lib.try_with_value(fnames.index(name), value)
-            raw2 = ffi.buffer(t, len(raw1))[:]
-            assert raw1 == raw2
+        t = lib.try_with_value(fnames.index(name), value)
+        raw2 = ffi.buffer(t, len(raw1))[:]
+        assert raw1 == raw2
 
     def test_bitfield_basic(self):
         self.check("int a; int b:9; int c:20; int y;", 8, 4, 12)
         L = FFI().alignof("long long")
         self.check("char y; int :0;", 0, 1, 4)
         self.check("char x; int :0; char y;", 4, 1, 5)
+        self.check("char x; int :0; int :0; char y;", 4, 1, 5)
         self.check("char x; long long :0; char y;", L, 1, L + 1)
         self.check("short x, y; int :0; int :0;", 2, 2, 4)
         self.check("char x; int :0; short b:1; char y;", 5, 2, 6)
+        self.check("int a:1; int :0; int b:1; char y;", 5, 4, 8)
 
     def test_error_cases(self):
         ffi = FFI()

File pypy/module/thread/test/test_fork.py

View file
  • Ignore whitespace
                 if pid == 0:
                     os._exit(0)
                 else:
-                    self.timeout_killer(pid, 5)
+                    self.timeout_killer(pid, 10)
                     exitcode = os.waitpid(pid, 0)[1]
                     assert exitcode == 0 # if 9, process was killed by timer!
             finally:
                 thread.start_new_thread(lambda: None, ())
                 os._exit(0)
             else:
-                self.timeout_killer(pid, 5)
+                self.timeout_killer(pid, 10)
                 exitcode = os.waitpid(pid, 0)[1]
                 assert exitcode == 0 # if 9, process was killed by timer!
 
                 signal.signal(signal.SIGUSR1, signal.SIG_IGN)
                 os._exit(42)
             else:
-                self.timeout_killer(pid, 5)
+                self.timeout_killer(pid, 10)
                 exitcode = os.waitpid(pid, 0)[1]
                 feedback.append(exitcode)
 

File rpython/jit/backend/arm/assembler.py

View file
  • Ignore whitespace
         tmpreg = r.lr
         mc.gen_load_int(r.ip.value, self.cpu.pos_exc_value())
         if excvalloc is not None: # store
-            assert excvalloc.is_reg()
+            assert excvalloc.is_core_reg()
             self.load_reg(mc, excvalloc, r.ip)
         if on_frame:
             # store exc_value in JITFRAME
             self.store_reg(mc, r.ip, r.fp, ofs, helper=tmpreg)
         if exctploc is not None:
             # store pos_exception in exctploc
-            assert exctploc.is_reg()
+            assert exctploc.is_core_reg()
             mc.gen_load_int(r.ip.value, self.cpu.pos_exception())
             self.load_reg(mc, exctploc, r.ip, helper=tmpreg)
 
         tmpreg = r.lr # use lr as a second temporary reg
         mc.gen_load_int(r.ip.value, self.cpu.pos_exc_value())
         if excvalloc is not None:
-            assert excvalloc.is_reg()
+            assert excvalloc.is_core_reg()
             self.store_reg(mc, excvalloc, r.ip)
         else:
             assert exctploc is not r.fp
     # regalloc support
     def load(self, loc, value):
         """load an immediate value into a register"""
-        assert (loc.is_reg() and value.is_imm()
+        assert (loc.is_core_reg() and value.is_imm()
                     or loc.is_vfp_reg() and value.is_imm_float())
         if value.is_imm():
             self.mc.gen_load_int(loc.value, value.getint())
     def load_reg(self, mc, target, base, ofs=0, cond=c.AL, helper=r.ip):
         if target.is_vfp_reg():
             return self._load_vfp_reg(mc, target, base, ofs, cond, helper)
-        elif target.is_reg():
+        elif target.is_core_reg():
             return self._load_core_reg(mc, target, base, ofs, cond, helper)
 
     def _load_vfp_reg(self, mc, target, base, ofs, cond=c.AL, helper=r.ip):
     def _mov_imm_to_loc(self, prev_loc, loc, cond=c.AL):
         if loc.type == FLOAT:
             raise AssertionError("invalid target for move from imm value")
-        if loc.is_reg():
+        if loc.is_core_reg():
             new_loc = loc
         elif loc.is_stack() or loc.is_raw_sp():
             new_loc = r.lr
     def _mov_reg_to_loc(self, prev_loc, loc, cond=c.AL):
         if loc.is_imm():
             raise AssertionError("mov reg to imm doesn't make sense")
-        if loc.is_reg():
+        if loc.is_core_reg():
             self.mc.MOV_rr(loc.value, prev_loc.value, cond=cond)
         elif loc.is_stack() and loc.type != FLOAT:
             # spill a core register
         helper = None
         offset = prev_loc.value
         tmp = None
-        if loc.is_reg():
+        if loc.is_core_reg():
             assert prev_loc.type != FLOAT, 'trying to load from an \
                 incompatible location into a core register'
             # unspill a core register
         """Moves a value from a previous location to some other location"""
         if prev_loc.is_imm():
             return self._mov_imm_to_loc(prev_loc, loc, cond)
-        elif prev_loc.is_reg():
+        elif prev_loc.is_core_reg():
             self._mov_reg_to_loc(prev_loc, loc, cond)
         elif prev_loc.is_stack():
             self._mov_stack_to_loc(prev_loc, loc, cond)
                 scratch_reg = r.vfp_ip
             self.regalloc_mov(loc, scratch_reg, cond)
             self.regalloc_push(scratch_reg, cond)
-        elif loc.is_reg():
+        elif loc.is_core_reg():
             self.mc.PUSH([loc.value], cond=cond)
         elif loc.is_vfp_reg():
             self.mc.VPUSH([loc.value], cond=cond)
                 scratch_reg = r.vfp_ip
             self.regalloc_pop(scratch_reg)
             self.regalloc_mov(scratch_reg, loc)
-        elif loc.is_reg():
+        elif loc.is_core_reg():
             self.mc.POP([loc.value], cond=cond)
         elif loc.is_vfp_reg():
             self.mc.VPOP([loc.value], cond=cond)
 
         # lengthloc is the length of the array, which we must not modify!
         assert lengthloc is not r.r0 and lengthloc is not r.r1
-        if lengthloc.is_reg():
+        if lengthloc.is_core_reg():
             varsizeloc = lengthloc
         else:
             assert lengthloc.is_stack()

File rpython/jit/backend/arm/callbuilder.py

View file
  • Ignore whitespace
         if self.fnloc.is_stack():
             self.asm.mov_loc_loc(self.fnloc, r.ip)
             self.fnloc = r.ip
-        assert self.fnloc.is_reg()
+        assert self.fnloc.is_core_reg()
         self.mc.BLX(self.fnloc.value)
 
     def restore_stack_pointer(self):
             return [], []
         if self.resloc.is_vfp_reg():
             return [r.r0, r.r1], []
-        assert self.resloc.is_reg()
+        assert self.resloc.is_core_reg()
         return [r.r0], []
 
     def load_result(self):
         if resloc.is_vfp_reg():
             # move result to the allocated register
             self.asm.mov_to_vfp_loc(r.r0, r.r1, resloc)
-        elif resloc.is_reg():
+        elif resloc.is_core_reg():
             # move result to the allocated register
             if resloc is not r.r0:
                 self.asm.mov_loc_loc(r.r0, resloc)
     def load_result(self):
         resloc = self.resloc
         # ensure the result is wellformed and stored in the correct location
-        if resloc is not None and resloc.is_reg():
+        if resloc is not None and resloc.is_core_reg():
             self._ensure_result_bit_extension(resloc,
                                                   self.ressize, self.ressign)
 
             return [], []
         if self.resloc.is_vfp_reg():
             return [], [r.d0]
-        assert self.resloc.is_reg()
+        assert self.resloc.is_core_reg()
         return [r.r0], []
 
 

File rpython/jit/backend/arm/helper/assembler.py

View file
  • Ignore whitespace
         assert guard is not None
         l0 = arglocs[0]
         l1 = arglocs[1]
-        assert l0.is_reg()
+        assert l0.is_core_reg()
 
         if l1.is_imm():
             self.mc.CMP_ri(l0.value, imm=l1.getint(), cond=fcond)

File rpython/jit/backend/arm/locations.py

View file
  • Ignore whitespace
     def is_raw_sp(self):
         return False
 
-    def is_reg(self):
+    def is_core_reg(self):
         return False
 
     def is_vfp_reg(self):
     def __repr__(self):
         return 'r%d' % self.value
 
-    def is_reg(self):
+    def is_core_reg(self):
         return True
 
     def as_key(self):
     def __repr__(self):
         return 'vfp%d' % self.value
 
-    def is_reg(self):
+    def is_core_reg(self):
         return False
 
     def is_vfp_reg(self):

File rpython/jit/backend/arm/opassembler.py

View file
  • Ignore whitespace
         l1 = arglocs[1]
         failargs = arglocs[2:]
 
-        if l0.is_reg():
+        if l0.is_core_reg():
             if l1.is_imm():
                 self.mc.CMP_ri(l0.value, l1.getint())
             else:
             # case GCFLAG_CARDS_SET: emit a few instructions to do
             # directly the card flag setting
             loc_index = arglocs[1]
-            assert loc_index.is_reg()
+            assert loc_index.is_core_reg()
             # must save the register loc_index before it is mutated
             mc.PUSH([loc_index.value])
             tmp1 = loc_index
 
     def emit_op_setarrayitem_gc(self, op, arglocs, regalloc, fcond):
         value_loc, base_loc, ofs_loc, scale, ofs = arglocs
-        assert ofs_loc.is_reg()
+        assert ofs_loc.is_core_reg()
         if scale.value > 0:
             self.mc.LSL_ri(r.ip.value, ofs_loc.value, scale.value)
             ofs_loc = r.ip
             # vstr only supports imm offsets
             # so if the ofset is too large we add it to the base and use an
             # offset of 0
-            if ofs_loc.is_reg():
+            if ofs_loc.is_core_reg():
                 tmploc, save = self.get_tmp_reg([value_loc, base_loc, ofs_loc])
                 assert not save
                 self.mc.ADD_rr(tmploc.value, base_loc.value, ofs_loc.value)
 
     def emit_op_raw_store(self, op, arglocs, regalloc, fcond):
         value_loc, base_loc, ofs_loc, scale, ofs = arglocs
-        assert ofs_loc.is_reg()
+        assert ofs_loc.is_core_reg()
         self._write_to_mem(value_loc, base_loc, ofs_loc, scale, fcond)
         return fcond
 
     def emit_op_getarrayitem_gc(self, op, arglocs, regalloc, fcond):
         res_loc, base_loc, ofs_loc, scale, ofs = arglocs
-        assert ofs_loc.is_reg()
+        assert ofs_loc.is_core_reg()
         signed = op.getdescr().is_item_signed()
 
         # scale the offset as required
             # vldr only supports imm offsets
             # if the offset is in a register we add it to the base and use a
             # tmp reg
-            if ofs_loc.is_reg():
+            if ofs_loc.is_core_reg():
                 tmploc, save = self.get_tmp_reg([base_loc, ofs_loc])
                 assert not save
                 self.mc.ADD_rr(tmploc.value, base_loc.value, ofs_loc.value)
 
     def emit_op_raw_load(self, op, arglocs, regalloc, fcond):
         res_loc, base_loc, ofs_loc, scale, ofs = arglocs
-        assert ofs_loc.is_reg()
+        assert ofs_loc.is_core_reg()
         # no base offset
         assert ofs.value == 0
         signed = op.getdescr().is_item_signed()
             bytes_box = TempBox()
             bytes_loc = regalloc.rm.force_allocate_reg(bytes_box, forbidden_vars)
             scale = self._get_unicode_item_scale()
-            if not length_loc.is_reg():
+            if not length_loc.is_core_reg():
                 self.regalloc_mov(length_loc, bytes_loc)
                 length_loc = bytes_loc
-            assert length_loc.is_reg()
+            assert length_loc.is_core_reg()
             self.mc.MOV_ri(r.ip.value, 1 << scale)
             self.mc.MUL(bytes_loc.value, r.ip.value, length_loc.value)
             length_box = bytes_box
 
    # result = base_loc  + (scaled_loc << scale) + static_offset
     def _gen_address(self, result, base_loc, scaled_loc, scale=0, static_offset=0):
-        assert scaled_loc.is_reg()
-        assert base_loc.is_reg()
+        assert scaled_loc.is_core_reg()
+        assert base_loc.is_core_reg()
         assert check_imm_arg(scale)
         assert check_imm_arg(static_offset)
         if scale > 0:
     def emit_op_cast_float_to_int(self, op, arglocs, regalloc, fcond):
         arg, res = arglocs
         assert arg.is_vfp_reg()
-        assert res.is_reg()
+        assert res.is_core_reg()
         self.mc.VCVT_float_to_int(r.vfp_ip.value, arg.value)
         self.mc.VMOV_rc(res.value, r.ip.value, r.vfp_ip.value)
         return fcond
     def emit_op_cast_int_to_float(self, op, arglocs, regalloc, fcond):
         arg, res = arglocs
         assert res.is_vfp_reg()
-        assert arg.is_reg()
+        assert arg.is_core_reg()
         self.mc.MOV_ri(r.ip.value, 0)
         self.mc.VMOV_cr(res.value, arg.value, r.ip.value)
         self.mc.VCVT_int_to_float(res.value, res.value)
         loc = arglocs[0]
         res = arglocs[1]
         assert loc.is_vfp_reg()
-        assert res.is_reg()
+        assert res.is_core_reg()
         self.mc.VMOV_rc(res.value, r.ip.value, loc.value)
         return fcond
 
     def emit_op_cast_float_to_singlefloat(self, op, arglocs, regalloc, fcond):
         arg, res = arglocs
         assert arg.is_vfp_reg()
-        assert res.is_reg()
+        assert res.is_core_reg()
         self.mc.VCVT_f64_f32(r.vfp_ip.value, arg.value)
         self.mc.VMOV_rc(res.value, r.ip.value, r.vfp_ip.value)
         return fcond
     def emit_op_cast_singlefloat_to_float(self, op, arglocs, regalloc, fcond):
         arg, res = arglocs
         assert res.is_vfp_reg()
-        assert arg.is_reg()
+        assert arg.is_core_reg()
         self.mc.MOV_ri(r.ip.value, 0)
         self.mc.VMOV_cr(res.value, arg.value, r.ip.value)
         self.mc.VCVT_f32_f64(res.value, res.value)

File rpython/jit/backend/arm/regalloc.py

View file
  • Ignore whitespace
                 loc = r.fp
             arg = inputargs[i]
             i += 1
-            if loc.is_reg():
+            if loc.is_core_reg():
                 self.rm.reg_bindings[arg] = loc
                 used[loc] = None
             elif loc.is_vfp_reg():
         # note: we need to make a copy of inputargs because possibly_free_vars
         # is also used on op args, which is a non-resizable list
         self.possibly_free_vars(list(inputargs))
+        self.fm.finish_binding()
+        self._check_invariants()
 
     def get_gcmap(self, forbidden_regs=[], noregs=False):
         frame_depth = self.fm.get_frame_depth()
                 continue
             if box.type == REF and self.rm.is_still_alive(box):
                 assert not noregs
-                assert loc.is_reg()
+                assert loc.is_core_reg()
                 val = loc.value
                 gcmap[val // WORD // 8] |= r_uint(1) << (val % (WORD * 8))
         for box, loc in self.fm.bindings.iteritems():
             assert isinstance(arg, Box)
             loc = self.loc(arg)
             arglocs[i] = loc
-            if loc.is_reg():
+            if loc.is_core_reg() or loc.is_vfp_reg():
                 self.frame_manager.mark_as_free(arg)
         #
         descr._arm_arglocs = arglocs

File rpython/jit/backend/arm/test/test_jump.py

View file
  • Ignore whitespace
                 else:
                     newvalue = 'value-vfp-%d' % i
                 regs2[loc.value] = newvalue
-            elif loc.is_reg():
+            elif loc.is_core_reg():
                 regs1[loc.value] = 'value-int-%d' % i
             elif loc.is_stack():
                 stack[loc.position] = 'value-width%d-%d' % (loc.width, i)
                 assert loc.width == expected_width*WORD
             if loc.is_vfp_reg():
                 return regs2[loc.value]
-            elif loc.is_reg():
+            elif loc.is_core_reg():
                 return regs1[loc.value]
             elif loc.is_stack():
                 got = stack[loc.position]
         def write(loc, newvalue):
             if loc.is_vfp_reg():
                 regs2[loc.value] = newvalue
-            elif loc.is_reg():
+            elif loc.is_core_reg():
                 regs1[loc.value] = newvalue
             elif loc.is_stack():
                 if loc.width > WORD:
         for op in assembler.ops:
             if op[0] == 'mov':
                 src, dst = op[1:]
-                assert src.is_reg() or src.is_vfp_reg() or src.is_stack() or src.is_imm_float() or src.is_imm()
-                assert dst.is_reg() or dst.is_vfp_reg() or dst.is_stack()
+                assert src.is_core_reg() or src.is_vfp_reg() or src.is_stack() or src.is_imm_float() or src.is_imm()
+                assert dst.is_core_reg() or dst.is_vfp_reg() or dst.is_stack()
                 assert not (src.is_stack() and dst.is_stack())
                 write(dst, read(src))
             elif op[0] == 'push':
                 src, = op[1:]
-                assert src.is_reg() or src.is_vfp_reg() or src.is_stack()
+                assert src.is_core_reg() or src.is_vfp_reg() or src.is_stack()
                 extrapushes.append(read(src))
             elif op[0] == 'pop':
                 dst, = op[1:]
-                assert dst.is_reg() or dst.is_vfp_reg() or dst.is_stack()
+                assert dst.is_core_reg() or dst.is_vfp_reg() or dst.is_stack()
                 write(dst, extrapushes.pop())
             else:
                 assert 0, "unknown op: %r" % (op,)

File rpython/jit/backend/arm/test/test_runner.py

View file
  • Ignore whitespace
 from rpython.jit.codewriter.effectinfo import EffectInfo
 from rpython.jit.metainterp.history import JitCellToken, TargetToken
 from rpython.jit.backend.arm.detect import detect_arch_version
+from rpython.jit.codewriter import longlong
 
 
 CPU = getcpuclass()
         l1 = ('debug_print', preambletoken.repr_of_descr() + ':1')
         l2 = ('debug_print', targettoken.repr_of_descr() + ':9')
         assert ('jit-backend-counts', [l0, l1, l2]) in dlog
+
+
+    def test_label_float_in_reg_and_on_stack(self):
+        targettoken = TargetToken()
+        ops = """
+        [i0, f3]
+        i2 = same_as(i0)    # but forced to be in a register
+        force_spill(i2)
+        force_spill(f3)
+        f4 = float_add(f3, 5.0)
+        label(f3, f4, descr=targettoken)
+        force_spill(f3)
+        f5 = same_as(f3)    # but forced to be in a register
+        finish(f5)
+        """
+        faildescr = BasicFailDescr(2)
+        loop = parse(ops, self.cpu, namespace=locals())
+        looptoken = JitCellToken()
+        info = self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
+        ops2 = """
+        [i0, f1]
+        i1 = same_as(i0)
+        f2 = same_as(f1)
+        f3 = float_add(f1, 10.0)
+        force_spill(f3)
+        force_spill(i1)
+        f4 = float_add(f3, f1)
+        jump(f3, f4, descr=targettoken)
+        """
+        loop2 = parse(ops2, self.cpu, namespace=locals())
+        looptoken2 = JitCellToken()
+        info = self.cpu.compile_loop(loop2.inputargs, loop2.operations, looptoken2)
+
+        deadframe = self.cpu.execute_token(looptoken, -9, longlong.getfloatstorage(-13.5))
+        res = longlong.getrealfloat(self.cpu.get_float_value(deadframe, 0))
+        assert res == -13.5
+        #
+        deadframe = self.cpu.execute_token(looptoken2, -9, longlong.getfloatstorage(-13.5))
+        res = longlong.getrealfloat(self.cpu.get_float_value(deadframe, 0))
+        assert res == -3.5

File rpython/jit/backend/llsupport/assembler.py

View file
  • Ignore whitespace
             input_i += 1
             if arg.type == REF:
                 loc = fail_locs[i]
-                if loc.is_reg():
+                if loc.is_core_reg():
                     val = self.cpu.all_reg_indexes[loc.value]
                 else:
                     val = loc.get_position() + self.cpu.JITFRAME_FIXED_SIZE

File rpython/jit/backend/llsupport/test/zrpy_gc_boehm_test.py

View file
  • Ignore whitespace
 import weakref
 from rpython.rlib.jit import JitDriver, dont_look_inside
 from rpython.jit.backend.llsupport.test.zrpy_gc_test import run, get_entry, compile
-from rpython.jit.backend.llsupport.test.ztranslation_test import fix_annotator_for_vrawbuffer
 
 class X(object):
     def __init__(self, x=0):
     g._dont_inline_ = True
     return g
 
-def compile_boehm_test(monkeypatch):
-    fix_annotator_for_vrawbuffer(monkeypatch)
+def compile_boehm_test():
     myjitdriver = JitDriver(greens = [], reds = ['n', 'x'])
     @dont_look_inside
     def see(lst, n):

File rpython/jit/backend/llsupport/test/ztranslation_test.py

View file
  • Ignore whitespace
 from rpython.jit.codewriter.policy import StopAtXPolicy
 
 
-def fix_annotator_for_vrawbuffer(monkeypatch):
-    from rpython.rlib.nonconst import NonConstant
-    from rpython.jit.metainterp.optimizeopt.virtualize import VRawBufferValue
-    from rpython.jit.metainterp import warmspot
-
-    def my_hook_for_tests(cpu):
-        # this is needed so that the annotator can see it
-        if NonConstant(False):
-            v = VRawBufferValue(cpu, None, -1, None, None)
-    monkeypatch.setattr(warmspot, 'hook_for_tests', my_hook_for_tests)
-
-
 class TranslationTest(CCompiledMixin):
     CPUClass = getcpuclass()
 
-    def test_stuff_translates(self, monkeypatch):
-        fix_annotator_for_vrawbuffer(monkeypatch)
+    def test_stuff_translates(self):
         # this is a basic test that tries to hit a number of features and their
         # translation:
         # - jitting of loops and bridges
 class TranslationTestCallAssembler(CCompiledMixin):
     CPUClass = getcpuclass()
 
-    def test_direct_assembler_call_translates(self, monkeypatch):
+    def test_direct_assembler_call_translates(self):
         """Test CALL_ASSEMBLER and the recursion limit"""
         from rpython.rlib.rstackovf import StackOverflow
-        fix_annotator_for_vrawbuffer(monkeypatch)
 
         class Thing(object):
             def __init__(self, val):
 class TranslationTestJITStats(CCompiledMixin):
     CPUClass = getcpuclass()
 
-    def test_jit_get_stats(self, monkeypatch):
-        fix_annotator_for_vrawbuffer(monkeypatch)
+    def test_jit_get_stats(self):
         driver = JitDriver(greens = [], reds = ['i'])
 
         def f():
 class TranslationRemoveTypePtrTest(CCompiledMixin):
     CPUClass = getcpuclass()
 
-    def test_external_exception_handling_translates(self, monkeypatch):
-        fix_annotator_for_vrawbuffer(monkeypatch)
+    def test_external_exception_handling_translates(self):
         jitdriver = JitDriver(greens = [], reds = ['n', 'total'])
 
         class ImDone(Exception):

File rpython/jit/backend/x86/assembler.py

View file
  • Ignore whitespace
         frame in jf_guard_exc
         """
         if excvalloc is not None:
-            assert excvalloc.is_reg()
+            assert excvalloc.is_core_reg()
             mc.MOV(excvalloc, heap(self.cpu.pos_exc_value()))
         elif tmploc is not None: # if both are None, just ignore
             ofs = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
             mc.MOV(tmploc, heap(self.cpu.pos_exc_value()))
             mc.MOV(RawEbpLoc(ofs), tmploc)
         if exctploc is not None:
-            assert exctploc.is_reg()
+            assert exctploc.is_core_reg()
             mc.MOV(exctploc, heap(self.cpu.pos_exception()))
 
         mc.MOV(heap(self.cpu.pos_exception()), imm0)

File rpython/jit/backend/x86/regalloc.py

View file
  • Ignore whitespace
         else:
             return self.xrm.make_sure_var_in_reg(var, forbidden_vars)
 
-    def _frame_bindings(self, locs, inputargs):
-        bindings = {}
-        i = 0
-        for loc in locs:
-            if loc is None:
-                continue
-            arg = inputargs[i]
-            i += 1
-            if not isinstance(loc, RegLoc):
-                bindings[arg] = loc
-        return bindings
-
     def _update_bindings(self, locs, inputargs):
         # XXX this should probably go to llsupport/regalloc.py
         used = {}

File rpython/jit/backend/x86/regloc.py

View file
  • Ignore whitespace
     def is_stack(self):
         return False
 
-    def is_reg(self):
+    def is_core_reg(self):
         return False
 
     def get_position(self):
     def is_float(self):
         return self.is_xmm
 
-    def is_reg(self):
+    def is_core_reg(self):
         return True
 
 class ImmediateAssemblerLocation(AssemblerLocation):

File rpython/jit/metainterp/optimizeopt/virtualize.py

View file
  • Ignore whitespace
     _attrs_ = ('keybox', 'source_op', '_cached_vinfo')
     box = None
     level = optimizer.LEVEL_NONNULL
+    is_about_raw = False
     _cached_vinfo = None
 
     def __init__(self, keybox, source_op=None):
 
<