コード例 #1
0
CODE_FLAGS = dict(
    CO_OPTIMIZED   = 0x0001,
    CO_NEWLOCALS   = 0x0002,
    CO_VARARGS     = 0x0004,
    CO_VARKEYWORDS = 0x0008,
    CO_NESTED      = 0x0010,
    CO_GENERATOR   = 0x0020,
)
ALL_CODE_FLAGS = unrolling_iterable(CODE_FLAGS.items())

PyFunctionObjectStruct = lltype.ForwardReference()
PyFunctionObject = lltype.Ptr(PyFunctionObjectStruct)
PyFunctionObjectFields = PyObjectFields + \
    (("func_name", PyObject),)
cpython_struct("PyFunctionObject", PyFunctionObjectFields, PyFunctionObjectStruct)

PyCodeObjectStruct = lltype.ForwardReference()
PyCodeObject = lltype.Ptr(PyCodeObjectStruct)
PyCodeObjectFields = PyObjectFields + \
    (("co_name", PyObject),
     ("co_flags", rffi.INT),
     ("co_argcount", rffi.INT),
    )
cpython_struct("PyCodeObject", PyCodeObjectFields, PyCodeObjectStruct)

@bootstrap_function
def init_functionobject(space):
    make_typedescr(Function.typedef,
                   basestruct=PyFunctionObject.TO,
                   attach=function_attach,
コード例 #2
0
ファイル: cdatetime.py プロジェクト: sota/pypy-old
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.pyobject import PyObject, make_ref
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL, cpython_struct,
                                    PyObjectFields)
from pypy.module.cpyext.import_ import PyImport_Import
from pypy.module.cpyext.typeobject import PyTypeObjectPtr
from pypy.interpreter.error import OperationError
from rpython.tool.sourcetools import func_renamer

# API import function

PyDateTime_CAPI = cpython_struct('PyDateTime_CAPI', (
    ('DateType', PyTypeObjectPtr),
    ('DateTimeType', PyTypeObjectPtr),
    ('TimeType', PyTypeObjectPtr),
    ('DeltaType', PyTypeObjectPtr),
))


@cpython_api([], lltype.Ptr(PyDateTime_CAPI))
def _PyDateTime_Import(space):
    datetimeAPI = lltype.malloc(PyDateTime_CAPI,
                                flavor='raw',
                                track_allocation=False)

    w_datetime = PyImport_Import(space, space.wrap("datetime"))

    w_type = space.getattr(w_datetime, space.wrap("date"))
    datetimeAPI.c_DateType = rffi.cast(PyTypeObjectPtr,
                                       make_ref(space, w_type))
コード例 #3
0
from pypy.module.cpyext.api import cpython_api, generic_cpy_call, CANNOT_FAIL, CConfig, cpython_struct
from pypy.rpython.lltypesystem import rffi, lltype

PyInterpreterState = lltype.Ptr(cpython_struct("PyInterpreterState", ()))
PyThreadState = lltype.Ptr(cpython_struct("PyThreadState", [("interp", PyInterpreterState)]))


@cpython_api([], PyThreadState, error=CANNOT_FAIL)
def PyEval_SaveThread(space):
    """Release the global interpreter lock (if it has been created and thread
    support is enabled) and reset the thread state to NULL, returning the
    previous thread state (which is not NULL except in PyPy).  If the lock has been created,
    the current thread must have acquired it.  (This function is available even
    when thread support is disabled at compile time.)"""
    if rffi.aroundstate.before:
        rffi.aroundstate.before()
    return lltype.nullptr(PyThreadState.TO)


@cpython_api([PyThreadState], lltype.Void)
def PyEval_RestoreThread(space, tstate):
    """Acquire the global interpreter lock (if it has been created and thread
    support is enabled) and set the thread state to tstate, which must not be
    NULL.  If the lock has been created, the current thread must not have
    acquired it, otherwise deadlock ensues.  (This function is available even
    when thread support is disabled at compile time.)"""
    if rffi.aroundstate.after:
        rffi.aroundstate.after()


@cpython_api([], lltype.Void)
コード例 #4
0
##   objects.  The buffer is then supposed to be immutable.
##
## - _PyString_Resize() works only on not-yet-pypy'd strings, and returns a
##   similar object.
##
## - PyString_Size() doesn't need to force the object.
##
## - There could be an (expensive!) check in from_ref() that the buffer still
##   corresponds to the pypy gc-managed string.
##

PyStringObjectStruct = lltype.ForwardReference()
PyStringObject = lltype.Ptr(PyStringObjectStruct)
PyStringObjectFields = PyObjectFields + \
    (("buffer", rffi.CCHARP), ("size", Py_ssize_t))
cpython_struct("PyStringObject", PyStringObjectFields, PyStringObjectStruct)

@bootstrap_function
def init_stringobject(space):
    "Type description of PyStringObject"
    make_typedescr(space.w_str.instancetypedef,
                   basestruct=PyStringObject.TO,
                   attach=string_attach,
                   dealloc=string_dealloc,
                   realize=string_realize)

PyString_Check, PyString_CheckExact = build_type_checkers("String", "w_str")

def new_empty_str(space, length):
    """
    Allocatse a PyStringObject and its buffer, but without a corresponding
コード例 #5
0
ファイル: intobject.py プロジェクト: cimarieta/usp
    bootstrap_function,
    PyObject,
    PyObjectFields,
    CONST_STRING,
    CANNOT_FAIL,
    Py_ssize_t,
)
from pypy.module.cpyext.pyobject import make_typedescr, track_reference, from_ref
from rpython.rlib.rarithmetic import r_uint, intmask, LONG_TEST, r_ulonglong
from pypy.objspace.std.intobject import W_IntObject
import sys

PyIntObjectStruct = lltype.ForwardReference()
PyIntObject = lltype.Ptr(PyIntObjectStruct)
PyIntObjectFields = PyObjectFields + (("ob_ival", rffi.LONG),)
cpython_struct("PyIntObject", PyIntObjectFields, PyIntObjectStruct)


@bootstrap_function
def init_intobject(space):
    "Type description of PyIntObject"
    make_typedescr(space.w_int.layout.typedef, basestruct=PyIntObject.TO, attach=int_attach, realize=int_realize)


def int_attach(space, py_obj, w_obj):
    """
    Fills a newly allocated PyIntObject with the given int object. The
    value must not be modified.
    """
    py_int = rffi.cast(PyIntObject, py_obj)
    py_int.c_ob_ival = space.int_w(w_obj)
コード例 #6
0
ファイル: complexobject.py プロジェクト: abhinavthomas/pypy
from rpython.rtyper.lltypesystem import lltype, rffi
from pypy.module.cpyext.api import (
    cpython_api, cpython_struct, PyObject, build_type_checkers)
from pypy.module.cpyext.floatobject import PyFloat_AsDouble
from pypy.objspace.std.complexobject import W_ComplexObject
from pypy.interpreter.error import OperationError

PyComplex_Check, PyComplex_CheckExact = build_type_checkers("Complex")

Py_complex_t = lltype.ForwardReference()
Py_complex_ptr = lltype.Ptr(Py_complex_t)
Py_complex_fields = (("real", rffi.DOUBLE), ("imag", rffi.DOUBLE))
cpython_struct("Py_complex", Py_complex_fields, Py_complex_t)


@cpython_api([lltype.Float, lltype.Float], PyObject)
def PyComplex_FromDoubles(space, real, imag):
    return space.newcomplex(real, imag)


@cpython_api([PyObject], lltype.Float, error=-1)
def PyComplex_RealAsDouble(space, w_obj):
    if space.isinstance_w(w_obj, space.w_complex):
        assert isinstance(w_obj, W_ComplexObject)
        return w_obj.realval
    else:
        return space.float_w(w_obj)


@cpython_api([PyObject], lltype.Float, error=-1)
def PyComplex_ImagAsDouble(space, w_obj):
コード例 #7
0
ファイル: typeobject.py プロジェクト: mozillazg/pypy
WARN_ABOUT_MISSING_SLOT_FUNCTIONS = False

PyType_Check, PyType_CheckExact = build_type_checkers("Type", "w_type")

PyHeapTypeObjectStruct = lltype.ForwardReference()
PyHeapTypeObject = lltype.Ptr(PyHeapTypeObjectStruct)
PyHeapTypeObjectFields = (
    ("ht_type", PyTypeObject),
    ("ht_name", PyObject),
    ("as_number", PyNumberMethods),
    ("as_mapping", PyMappingMethods),
    ("as_sequence", PySequenceMethods),
    ("as_buffer", PyBufferProcs),
    )
cpython_struct("PyHeapTypeObject", PyHeapTypeObjectFields, PyHeapTypeObjectStruct,
               level=2)

class W_GetSetPropertyEx(GetSetProperty):
    def __init__(self, getset, w_type):
        self.getset = getset
        self.name = rffi.charp2str(getset.c_name)
        self.w_type = w_type
        doc = set = get = None
        if doc:
            doc = rffi.charp2str(getset.c_doc)
        if getset.c_get:
            get = GettersAndSetters.getter.im_func
        if getset.c_set:
            set = GettersAndSetters.setter.im_func
        GetSetProperty.__init__(self, get, set, None, doc,
                                cls=None, use_closure=True,
コード例 #8
0
WARN_ABOUT_MISSING_SLOT_FUNCTIONS = False

PyType_Check, PyType_CheckExact = build_type_checkers("Type", "w_type")

PyHeapTypeObjectStruct = lltype.ForwardReference()
PyHeapTypeObject = lltype.Ptr(PyHeapTypeObjectStruct)
PyHeapTypeObjectFields = (
    ("ht_type", PyTypeObject),
    ("ht_name", PyObject),
    ("as_number", PyNumberMethods),
    ("as_mapping", PyMappingMethods),
    ("as_sequence", PySequenceMethods),
    ("as_buffer", PyBufferProcs),
    )
cpython_struct("PyHeapTypeObject", PyHeapTypeObjectFields, PyHeapTypeObjectStruct,
               level=2)

class W_GetSetPropertyEx(GetSetProperty):
    def __init__(self, getset, w_type):
        self.getset = getset
        self.name = rffi.charp2str(getset.c_name)
        self.w_type = w_type
        doc = set = get = None
        if doc:
            doc = rffi.charp2str(getset.c_doc)
        if getset.c_get:
            get = GettersAndSetters.getter.im_func
        if getset.c_set:
            set = GettersAndSetters.setter.im_func
        GetSetProperty.__init__(self, get, set, None, doc,
                                cls=None, use_closure=True,
コード例 #9
0
from pypy.rpython.lltypesystem import lltype, rffi
from pypy.module.cpyext.api import (cpython_api, cpython_struct, PyObject,
                                    build_type_checkers)
from pypy.module.cpyext.floatobject import PyFloat_AsDouble
from pypy.objspace.std.complexobject import W_ComplexObject
from pypy.interpreter.error import OperationError

PyComplex_Check, PyComplex_CheckExact = build_type_checkers("Complex")

Py_complex_t = lltype.ForwardReference()
Py_complex_ptr = lltype.Ptr(Py_complex_t)
Py_complex_fields = (("real", rffi.DOUBLE), ("imag", rffi.DOUBLE))
cpython_struct("Py_complex", Py_complex_fields, Py_complex_t)


@cpython_api([lltype.Float, lltype.Float], PyObject)
def PyComplex_FromDoubles(space, real, imag):
    return space.newcomplex(real, imag)


@cpython_api([PyObject], lltype.Float, error=-1)
def PyComplex_RealAsDouble(space, w_obj):
    if space.is_true(space.isinstance(w_obj, space.w_complex)):
        assert isinstance(w_obj, W_ComplexObject)
        return w_obj.realval
    else:
        return space.float_w(w_obj)


@cpython_api([PyObject], lltype.Float, error=-1)
def PyComplex_ImagAsDouble(space, w_obj):
コード例 #10
0
ファイル: cdatetime.py プロジェクト: mozillazg/pypy
# API import function

PyDateTime_CAPI = cpython_struct(
    'PyDateTime_CAPI',
    (('DateType', PyTypeObjectPtr),
     ('DateTimeType', PyTypeObjectPtr),
     ('TimeType', PyTypeObjectPtr),
     ('DeltaType', PyTypeObjectPtr),
     ('TZInfoType', PyTypeObjectPtr),

     ('Date_FromDate', lltype.Ptr(lltype.FuncType(
         [rffi.INT_real, rffi.INT_real, rffi.INT_real, PyTypeObjectPtr],
         PyObject))),
     ('Time_FromTime', lltype.Ptr(lltype.FuncType(
         [rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
          PyObject, PyTypeObjectPtr],
         PyObject))),
     ('DateTime_FromDateAndTime', lltype.Ptr(lltype.FuncType(
         [rffi.INT_real, rffi.INT_real, rffi.INT_real,
          rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
          PyObject, PyTypeObjectPtr],
         PyObject))),
     ('Delta_FromDelta', lltype.Ptr(lltype.FuncType(
         [rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
          PyTypeObjectPtr],
         PyObject))),
     ))

@cpython_api([], lltype.Ptr(PyDateTime_CAPI))
def _PyDateTime_Import(space):
コード例 #11
0
PyDateTime_CAPI = cpython_struct('PyDateTime_CAPI', (
    ('DateType', PyTypeObjectPtr),
    ('DateTimeType', PyTypeObjectPtr),
    ('TimeType', PyTypeObjectPtr),
    ('DeltaType', PyTypeObjectPtr),
    ('TZInfoType', PyTypeObjectPtr),
    ('Date_FromDate',
     lltype.Ptr(
         lltype.FuncType(
             [rffi.INT_real, rffi.INT_real, rffi.INT_real, PyTypeObjectPtr],
             PyObject))),
    ('Time_FromTime',
     lltype.Ptr(
         lltype.FuncType([
             rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
             PyObject, PyTypeObjectPtr
         ], PyObject))),
    ('DateTime_FromDateAndTime',
     lltype.Ptr(
         lltype.FuncType([
             rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
             rffi.INT_real, rffi.INT_real, rffi.INT_real, PyObject,
             PyTypeObjectPtr
         ], PyObject))),
    ('Delta_FromDelta',
     lltype.Ptr(
         lltype.FuncType([
             rffi.INT_real, rffi.INT_real, rffi.INT_real, rffi.INT_real,
             PyTypeObjectPtr
         ], PyObject))),
))
コード例 #12
0
from pypy.module.cpyext.floatobject import PyFloat_AsDouble
from pypy.objspace.std.complexobject import W_ComplexObject
from pypy.interpreter.error import oefmt

PyComplex_Check, PyComplex_CheckExact = build_type_checkers("Complex")

Py_complex_t = rffi.CStruct('Py_complex_t', ('real', rffi.DOUBLE),
                            ('imag', rffi.DOUBLE),
                            hints={'size': 2 * rffi.sizeof(rffi.DOUBLE)})
Py_complex_ptr = lltype.Ptr(Py_complex_t)

PyComplexObjectStruct = lltype.ForwardReference()
PyComplexObject = lltype.Ptr(PyComplexObjectStruct)
PyComplexObjectFields = PyObjectFields + \
    (("cval", Py_complex_t),)
cpython_struct("PyComplexObject", PyComplexObjectFields, PyComplexObjectStruct)


@bootstrap_function
def init_complexobject(space):
    "Type description of PyComplexObject"
    make_typedescr(space.w_complex.layout.typedef,
                   basestruct=PyComplexObject.TO,
                   attach=complex_attach,
                   realize=complex_realize)


def complex_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PyComplexObject with the given complex object. The
    value must not be modified.
コード例 #13
0
ファイル: eval.py プロジェクト: gorakhargosh/pypy
from pypy.interpreter.error import OperationError
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (
    cpython_api, CANNOT_FAIL, CONST_STRING, FILEP, fread, feof, Py_ssize_tP,
    cpython_struct)
from pypy.module.cpyext.pyobject import PyObject, borrow_from
from pypy.module.cpyext.pyerrors import PyErr_SetFromErrno
from pypy.module.__builtin__ import compiling

PyCompilerFlags = cpython_struct(
    "PyCompilerFlags", ())
PyCompilerFlagsPtr = lltype.Ptr(PyCompilerFlags)

@cpython_api([PyObject, PyObject, PyObject], PyObject)
def PyEval_CallObjectWithKeywords(space, w_obj, w_arg, w_kwds):
    return space.call(w_obj, w_arg, w_kwds)

@cpython_api([], PyObject)
def PyEval_GetBuiltins(space):
    """Return a dictionary of the builtins in the current execution
    frame, or the interpreter of the thread state if no frame is
    currently executing."""
    caller = space.getexecutioncontext().gettopframe_nohidden()
    if caller is not None:
        w_globals = caller.w_globals
        w_builtins = space.getitem(w_globals, space.wrap('__builtins__'))
        if not space.isinstance_w(w_builtins, space.w_dict):
            w_builtins = w_builtins.getdict(space)
    else:
        w_builtins = space.builtin.getdict(space)
    return borrow_from(None, w_builtins)
コード例 #14
0
    cpython_api, cpython_struct, bootstrap_function, build_type_checkers,
    CANNOT_FAIL, Py_ssize_t, Py_ssize_tP, PyObjectFields, slot_function)
from pypy.module.cpyext.pyobject import (
    decref, PyObject, make_ref, make_typedescr)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.interpreter.error import OperationError
from pypy.objspace.std.sliceobject import W_SliceObject

# Slice objects directly expose their members as PyObject.
# Don't change them!

PySliceObjectStruct = lltype.ForwardReference()
PySliceObject = lltype.Ptr(PySliceObjectStruct)
PySliceObjectFields = PyObjectFields + \
    (("start", PyObject), ("step", PyObject), ("stop", PyObject), )
cpython_struct("PySliceObject", PySliceObjectFields, PySliceObjectStruct)

@bootstrap_function
def init_sliceobject(space):
    "Type description of PySliceObject"
    make_typedescr(W_SliceObject.typedef,
                   basestruct=PySliceObject.TO,
                   attach=slice_attach,
                   dealloc=slice_dealloc)

def slice_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PySliceObject with the given slice object. The
    fields must not be modified.
    """
    py_slice = rffi.cast(PySliceObject, py_obj)
コード例 #15
0
from pypy.module.cpyext.buffer import CBuffer
from pypy.module.array.interp_array import ArrayBuffer
from pypy.objspace.std.bufferobject import W_Buffer

PyBufferObjectStruct = lltype.ForwardReference()
PyBufferObject = lltype.Ptr(PyBufferObjectStruct)
PyBufferObjectFields = PyObjectFields + (
    ("b_base", PyObject),
    ("b_ptr", rffi.VOIDP),
    ("b_size", Py_ssize_t),
    ("b_offset", Py_ssize_t),
    ("b_readonly", rffi.INT),
    ("b_hash", rffi.LONG),
)

cpython_struct("PyBufferObject", PyBufferObjectFields, PyBufferObjectStruct)


@bootstrap_function
def init_bufferobject(space):
    "Type description of PyBufferObject"
    make_typedescr(space.w_buffer.layout.typedef,
                   basestruct=PyBufferObject.TO,
                   attach=buffer_attach,
                   dealloc=buffer_dealloc,
                   realize=buffer_realize)


def buffer_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PyBufferObject with the given buffer object.
コード例 #16
0
ファイル: unicodeobject.py プロジェクト: mozillazg/pypy
from pypy.module.cpyext.bytesobject import PyString_Check
from pypy.module.sys.interp_encoding import setdefaultencoding
from pypy.module._codecs.interp_codecs import CodecState
from pypy.objspace.std import unicodeobject
from rpython.rlib import rstring, runicode
from rpython.tool.sourcetools import func_renamer
import sys

## See comment in bytesobject.py.

PyUnicodeObjectStruct = lltype.ForwardReference()
PyUnicodeObject = lltype.Ptr(PyUnicodeObjectStruct)
PyUnicodeObjectFields = (PyObjectFields +
    (("str", rffi.CWCHARP), ("length", Py_ssize_t),
     ("hash", rffi.LONG), ("defenc", PyObject)))
cpython_struct("PyUnicodeObject", PyUnicodeObjectFields, PyUnicodeObjectStruct)

@bootstrap_function
def init_unicodeobject(space):
    make_typedescr(space.w_unicode.layout.typedef,
                   basestruct=PyUnicodeObject.TO,
                   attach=unicode_attach,
                   dealloc=unicode_dealloc,
                   realize=unicode_realize)

# Buffer for the default encoding (used by PyUnicde_GetDefaultEncoding)
DEFAULT_ENCODING_SIZE = 100
default_encoding = lltype.malloc(rffi.CCHARP.TO, DEFAULT_ENCODING_SIZE,
                                 flavor='raw', zero=True)

PyUnicode_Check, PyUnicode_CheckExact = build_type_checkers("Unicode", "w_unicode")
コード例 #17
0
ファイル: modsupport.py プロジェクト: Qointum/pypy
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import cpython_api, cpython_struct, \
        METH_STATIC, METH_CLASS, METH_COEXIST, CANNOT_FAIL, CONST_STRING
from pypy.module.cpyext.pyobject import PyObject, borrow_from
from pypy.interpreter.module import Module
from pypy.module.cpyext.methodobject import (
    W_PyCFunctionObject, PyCFunction_NewEx, PyDescr_NewMethod,
    PyMethodDef, PyDescr_NewClassMethod, PyStaticMethod_New)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.module.cpyext.state import State
from pypy.interpreter.error import OperationError

PyModuleDef_BaseStruct = cpython_struct(
    'PyModuleDef_Base',
    [])

PyModuleDefStruct = cpython_struct(
    'PyModuleDef',
    [('m_base', PyModuleDef_BaseStruct),
     ('m_name', rffi.CCHARP),
     ('m_doc', rffi.CCHARP),
     ('m_methods', lltype.Ptr(PyMethodDef)),
     ], level=2)
PyModuleDef = lltype.Ptr(PyModuleDefStruct)

@cpython_api([PyModuleDef, rffi.INT_real], PyObject)
def PyModule_Create2(space, module, api_version):
    """Create a new module object, given the definition in module, assuming the
    API version module_api_version.  If that version does not match the version
    of the running interpreter, a RuntimeWarning is emitted.
    
コード例 #18
0
from pypy.interpreter.error import oefmt
from pypy.interpreter.astcompiler import consts
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.rarithmetic import widen
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL, CONST_STRING,
                                    FILEP, fread, feof, Py_ssize_tP,
                                    cpython_struct)
from pypy.module.cpyext.pyobject import PyObject
from pypy.module.cpyext.pyerrors import PyErr_SetFromErrno
from pypy.module.cpyext.funcobject import PyCodeObject
from pypy.module.cpyext.frameobject import PyFrameObject
from pypy.module.__builtin__ import compiling

PyCompilerFlags = cpython_struct("PyCompilerFlags", (("cf_flags", rffi.INT), ))
PyCompilerFlagsPtr = lltype.Ptr(PyCompilerFlags)

PyCF_MASK = (consts.CO_FUTURE_DIVISION | consts.CO_FUTURE_ABSOLUTE_IMPORT
             | consts.CO_FUTURE_WITH_STATEMENT
             | consts.CO_FUTURE_PRINT_FUNCTION
             | consts.CO_FUTURE_UNICODE_LITERALS)


@cpython_api([PyObject, PyObject, PyObject], PyObject)
def PyEval_CallObjectWithKeywords(space, w_obj, w_arg, w_kwds):
    return space.call(w_obj, w_arg, w_kwds)


@cpython_api([], PyObject, result_borrowed=True)
def PyEval_GetBuiltins(space):
    """Return a dictionary of the builtins in the current execution
コード例 #19
0
ファイル: bytearrayobject.py プロジェクト: mozillazg/pypy
# the bytes are mapped to ints in [0, 256).
# Bytes are not characters; they may be used to encode characters.
# The only way to go between bytes and str/unicode is via encoding
# and decoding.
# For the convenience of C programmers, the bytes type is considered
# to contain a char pointer, not an unsigned char pointer.

# Expose data as a rw cchar* only through PyByteArray_AsString
# Under this strategy the pointer could loose its synchronization with
# the underlying space.w_bytearray if PyByteArray_Resize is called, so
# hopefully the use of the pointer is short-lived

PyByteArrayObjectStruct = lltype.ForwardReference()
PyByteArrayObject = lltype.Ptr(PyByteArrayObjectStruct)
PyByteArrayObjectFields = PyVarObjectFields
cpython_struct("PyByteArrayObject", PyByteArrayObjectFields, PyByteArrayObjectStruct)

PyByteArray_Check, PyByteArray_CheckExact = build_type_checkers("ByteArray", "w_bytearray")

#_______________________________________________________________________

@cpython_api([PyObject], PyObject, result_is_ll=True)
def PyByteArray_FromObject(space, w_obj):
    """Return a new bytearray object from any object, o, that implements the
    buffer protocol.

    XXX expand about the buffer protocol, at least somewhere"""
    w_buffer = space.call_function(space.w_bytearray, w_obj)
    return make_ref(space, w_buffer)

@cpython_api([CONST_STRING, Py_ssize_t], PyObject, result_is_ll=True)
コード例 #20
0
from pypy.module.cpyext.api import (cpython_api, generic_cpy_call, CANNOT_FAIL,
                                    CConfig, cpython_struct)
from pypy.module.cpyext.pyobject import PyObject, Py_DecRef, make_ref, from_ref
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib import rthread

PyInterpreterStateStruct = lltype.ForwardReference()
PyInterpreterState = lltype.Ptr(PyInterpreterStateStruct)
cpython_struct("PyInterpreterState", [('next', PyInterpreterState)],
               PyInterpreterStateStruct)
PyThreadState = lltype.Ptr(
    cpython_struct("PyThreadState", [
        ('interp', PyInterpreterState),
        ('dict', PyObject),
    ]))


class NoThreads(Exception):
    pass


@cpython_api([], PyThreadState, error=CANNOT_FAIL, gil="release")
def PyEval_SaveThread(space):
    """Release the global interpreter lock (if it has been created and thread
    support is enabled) and reset the thread state to NULL, returning the
    previous thread state.  If the lock has been created,
    the current thread must have acquired it.  (This function is available even
    when thread support is disabled at compile time.)"""
    state = space.fromcache(InterpreterState)
    tstate = state.swap_thread_state(space, lltype.nullptr(PyThreadState.TO))
    return tstate
コード例 #21
0
from pypy.module.cpyext.api import bootstrap_function, slot_function
from pypy.module.cpyext.pyobject import make_typedescr
from pypy.module.exceptions.interp_exceptions import W_RuntimeWarning
from pypy.module.exceptions.interp_exceptions import W_StopIteration
from pypy.module.cpyext.pyobject import (PyObject, PyObjectP, make_ref,
                                         from_ref, decref,
                                         get_w_obj_and_decref)
from pypy.module.cpyext.state import State
from pypy.module.cpyext.import_ import PyImport_Import
from rpython.rlib import rposix, jit

PyStopIterationObjectStruct = lltype.ForwardReference()
PyStopIterationObject = lltype.Ptr(PyStopIterationObjectStruct)
PyStopIterationObjectFields = PyObjectFields + \
    (("value", PyObject), )
cpython_struct("PyStopIterationObject", PyStopIterationObjectFields,
               PyStopIterationObjectStruct)


@bootstrap_function
def init_stopiterationobject(space):
    "Type description of PyStopIterationObject"
    make_typedescr(W_StopIteration.typedef,
                   basestruct=PyStopIterationObject.TO,
                   attach=stopiteration_attach,
                   dealloc=stopiteration_dealloc)


def stopiteration_attach(space, py_obj, w_obj, w_userdata=None):
    py_stopiteration = rffi.cast(PyStopIterationObject, py_obj)
    assert isinstance(w_obj, W_StopIteration)
    # note: assumes that w_value is read-only; changes on one side won't
コード例 #22
0
ファイル: sliceobject.py プロジェクト: Qointum/pypy
    cpython_api, cpython_struct, bootstrap_function, build_type_checkers,
    CANNOT_FAIL, Py_ssize_t, Py_ssize_tP, PyObjectFields)
from pypy.module.cpyext.pyobject import (
    Py_DecRef, PyObject, make_ref, make_typedescr)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.interpreter.error import OperationError
from pypy.objspace.std.sliceobject import W_SliceObject

# Slice objects directly expose their members as PyObject.
# Don't change them!

PySliceObjectStruct = lltype.ForwardReference()
PySliceObject = lltype.Ptr(PySliceObjectStruct)
PySliceObjectFields = PyObjectFields + \
    (("start", PyObject), ("step", PyObject), ("stop", PyObject), )
cpython_struct("PySliceObject", PySliceObjectFields, PySliceObjectStruct)

@bootstrap_function
def init_sliceobject(space):
    "Type description of PySliceObject"
    make_typedescr(W_SliceObject.typedef,
                   basestruct=PySliceObject.TO,
                   attach=slice_attach,
                   dealloc=slice_dealloc)

def slice_attach(space, py_obj, w_obj):
    """
    Fills a newly allocated PySliceObject with the given slice object. The
    fields must not be modified.
    """
    py_slice = rffi.cast(PySliceObject, py_obj)
コード例 #23
0
ファイル: pytraceback.py プロジェクト: abhinavthomas/pypy
from pypy.module.cpyext.frameobject import PyFrameObject
from rpython.rlib.unroll import unrolling_iterable
from pypy.interpreter.error import OperationError
from pypy.interpreter.pytraceback import PyTraceback
from pypy.interpreter import pycode


PyTracebackObjectStruct = lltype.ForwardReference()
PyTracebackObject = lltype.Ptr(PyTracebackObjectStruct)
PyTracebackObjectFields = PyObjectFields + (
    ("tb_next", PyTracebackObject),
    ("tb_frame", PyFrameObject),
    ("tb_lasti", rffi.INT),
    ("tb_lineno", rffi.INT),
)
cpython_struct("PyTracebackObject", PyTracebackObjectFields, PyTracebackObjectStruct)

@bootstrap_function
def init_traceback(space):
    make_typedescr(PyTraceback.typedef,
                   basestruct=PyTracebackObject.TO,
                   attach=traceback_attach,
                   dealloc=traceback_dealloc)


def traceback_attach(space, py_obj, w_obj):
    py_traceback = rffi.cast(PyTracebackObject, py_obj)
    traceback = space.interp_w(PyTraceback, w_obj)
    if traceback.next is None:
        w_next_traceback = None
    else:
コード例 #24
0
ファイル: frameobject.py プロジェクト: zielmicha/pypy
                                         make_typedescr, get_typedescr)
from pypy.module.cpyext.state import State
from pypy.module.cpyext.pystate import PyThreadState
from pypy.module.cpyext.funcobject import PyCodeObject
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.pycode import PyCode
from pypy.interpreter.pytraceback import PyTraceback

PyFrameObjectStruct = lltype.ForwardReference()
PyFrameObject = lltype.Ptr(PyFrameObjectStruct)
PyFrameObjectFields = (PyObjectFields + (
    ("f_code", PyCodeObject),
    ("f_globals", PyObject),
    ("f_lineno", rffi.INT),
))
cpython_struct("PyFrameObject", PyFrameObjectFields, PyFrameObjectStruct)


@bootstrap_function
def init_frameobject(space):
    make_typedescr(PyFrame.typedef,
                   basestruct=PyFrameObject.TO,
                   attach=frame_attach,
                   dealloc=frame_dealloc,
                   realize=frame_realize)


def frame_attach(space, py_obj, w_obj):
    "Fills a newly allocated PyFrameObject with a frame object"
    frame = space.interp_w(PyFrame, w_obj)
    py_frame = rffi.cast(PyFrameObject, py_obj)
コード例 #25
0
ファイル: typeobjectdefs.py プロジェクト: mozillazg/pypy
wrapperfunc = P(FT([PyO, PyO, rffi.VOIDP], PyO))
wrapperfunc_kwds = P(FT([PyO, PyO, rffi.VOIDP, PyO], PyO))

readbufferproc = P(FT([PyO, Py_ssize_t, rffi.VOIDPP], Py_ssize_t))
writebufferproc = P(FT([PyO, Py_ssize_t, rffi.VOIDPP], Py_ssize_t))
segcountproc = P(FT([PyO, Py_ssize_tP], Py_ssize_t))
charbufferproc = P(FT([PyO, Py_ssize_t, rffi.CCHARPP], Py_ssize_t))
getbufferproc = P(FT([PyO, Py_bufferP, rffi.INT_real], rffi.INT_real))
releasebufferproc = rffi.VOIDP


PyGetSetDef = cpython_struct("PyGetSetDef", (
    ("name", rffi.CCHARP),
    ("get", getter),
    ("set", setter),
    ("doc", rffi.CCHARP),
    ("closure", rffi.VOIDP),
))

PyNumberMethods = cpython_struct("PyNumberMethods", (
    ("nb_add", binaryfunc),
    ("nb_subtract", binaryfunc),
    ("nb_multiply", binaryfunc),
    ("nb_divide", binaryfunc),
    ("nb_remainder", binaryfunc),
    ("nb_divmod", binaryfunc),
    ("nb_power", ternaryfunc),
    ("nb_negative", unaryfunc),
    ("nb_positive", unaryfunc),
    ("nb_absolute", unaryfunc),
コード例 #26
0
ファイル: eval.py プロジェクト: abhinavthomas/pypy
from pypy.interpreter.error import OperationError
from pypy.interpreter.astcompiler import consts
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (
    cpython_api, CANNOT_FAIL, CONST_STRING, FILEP, fread, feof, Py_ssize_tP,
    cpython_struct, is_valid_fp)
from pypy.module.cpyext.pyobject import PyObject
from pypy.module.cpyext.pyerrors import PyErr_SetFromErrno
from pypy.module.cpyext.funcobject import PyCodeObject
from pypy.module.__builtin__ import compiling

PyCompilerFlags = cpython_struct(
    "PyCompilerFlags", (("cf_flags", rffi.INT),))
PyCompilerFlagsPtr = lltype.Ptr(PyCompilerFlags)

PyCF_MASK = (consts.CO_FUTURE_DIVISION | 
             consts.CO_FUTURE_ABSOLUTE_IMPORT |
             consts.CO_FUTURE_WITH_STATEMENT |
             consts.CO_FUTURE_PRINT_FUNCTION |
             consts.CO_FUTURE_UNICODE_LITERALS)

@cpython_api([PyObject, PyObject, PyObject], PyObject)
def PyEval_CallObjectWithKeywords(space, w_obj, w_arg, w_kwds):
    return space.call(w_obj, w_arg, w_kwds)

@cpython_api([], PyObject, result_borrowed=True)
def PyEval_GetBuiltins(space):
    """Return a dictionary of the builtins in the current execution
    frame, or the interpreter of the thread state if no frame is
    currently executing."""
    caller = space.getexecutioncontext().gettopframe_nohidden()
コード例 #27
0
ファイル: pystate.py プロジェクト: Qointum/pypy
from pypy.module.cpyext.api import (
    cpython_api, generic_cpy_call, CANNOT_FAIL, CConfig, cpython_struct)
from pypy.module.cpyext.pyobject import PyObject, Py_DecRef, make_ref, from_ref
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib import rthread

PyInterpreterStateStruct = lltype.ForwardReference()
PyInterpreterState = lltype.Ptr(PyInterpreterStateStruct)
cpython_struct(
    "PyInterpreterState",
    [('next', PyInterpreterState)],
    PyInterpreterStateStruct)
PyThreadState = lltype.Ptr(cpython_struct(
    "PyThreadState",
    [('interp', PyInterpreterState),
     ('dict', PyObject),
     ]))

class NoThreads(Exception):
    pass

@cpython_api([], PyThreadState, error=CANNOT_FAIL, gil="release")
def PyEval_SaveThread(space):
    """Release the global interpreter lock (if it has been created and thread
    support is enabled) and reset the thread state to NULL, returning the
    previous thread state.  If the lock has been created,
    the current thread must have acquired it.  (This function is available even
    when thread support is disabled at compile time.)"""
    state = space.fromcache(InterpreterState)
    tstate = state.swap_thread_state(
        space, lltype.nullptr(PyThreadState.TO))
コード例 #28
0
ファイル: typeobjectdefs.py プロジェクト: njues/Sypy
wrapperfunc = P(FT([PyO, PyO, rffi.VOIDP], PyO))
wrapperfunc_kwds = P(FT([PyO, PyO, rffi.VOIDP, PyO], PyO))

readbufferproc = P(FT([PyO, Py_ssize_t, rffi.VOIDPP], Py_ssize_t))
writebufferproc = P(FT([PyO, Py_ssize_t, rffi.VOIDPP], Py_ssize_t))
segcountproc = P(FT([PyO, Py_ssize_tP], Py_ssize_t))
charbufferproc = P(FT([PyO, Py_ssize_t, rffi.CCHARPP], Py_ssize_t))
## We don't support new buffer interface for now
getbufferproc = rffi.VOIDP
releasebufferproc = rffi.VOIDP

PyGetSetDef = cpython_struct("PyGetSetDef", (
    ("name", rffi.CCHARP),
    ("get", getter),
    ("set", setter),
    ("doc", rffi.CCHARP),
    ("closure", rffi.VOIDP),
))

PyNumberMethods = cpython_struct("PyNumberMethods", (
    ("nb_add", binaryfunc),
    ("nb_subtract", binaryfunc),
    ("nb_multiply", binaryfunc),
    ("nb_divide", binaryfunc),
    ("nb_remainder", binaryfunc),
    ("nb_divmod", binaryfunc),
    ("nb_power", ternaryfunc),
    ("nb_negative", unaryfunc),
    ("nb_positive", unaryfunc),
    ("nb_absolute", unaryfunc),
コード例 #29
0
ファイル: methodobject.py プロジェクト: cimarieta/usp
    PyObject,
    PyObjectFields,
    bootstrap_function,
    build_type_checkers,
    cpython_api,
    cpython_struct,
    generic_cpy_call,
)
from pypy.module.cpyext.pyobject import Py_DecRef, from_ref, make_ref, make_typedescr

PyCFunction_typedef = rffi.COpaquePtr(typedef="PyCFunction")
PyCFunction = lltype.Ptr(lltype.FuncType([PyObject, PyObject], PyObject))
PyCFunctionKwArgs = lltype.Ptr(lltype.FuncType([PyObject, PyObject, PyObject], PyObject))

PyMethodDef = cpython_struct(
    "PyMethodDef",
    [("ml_name", rffi.CCHARP), ("ml_meth", PyCFunction_typedef), ("ml_flags", rffi.INT_real), ("ml_doc", rffi.CCHARP)],
)

PyCFunctionObjectStruct = cpython_struct(
    "PyCFunctionObject",
    PyObjectFields + (("m_ml", lltype.Ptr(PyMethodDef)), ("m_self", PyObject), ("m_module", PyObject)),
)
PyCFunctionObject = lltype.Ptr(PyCFunctionObjectStruct)


@bootstrap_function
def init_methodobject(space):
    make_typedescr(
        W_PyCFunctionObject.typedef, basestruct=PyCFunctionObject.TO, attach=cfunction_attach, dealloc=cfunction_dealloc
    )
コード例 #30
0
## PyBytes_AsString / PyString_AsString
## PyBytes_AS_STRING / PyString_AS_STRING
## PyBytes_AsStringAndSize / PyString_AsStringAndSize
## PyBytes_Size / PyString_Size
## PyBytes_Resize / PyString_Resize
## _PyBytes_Resize / _PyString_Resize (raises if called with a forced object)
##
## - There could be an (expensive!) check in from_ref() that the buffer still
##   corresponds to the pypy gc-managed string,
##

PyBytesObjectStruct = lltype.ForwardReference()
PyBytesObject = lltype.Ptr(PyBytesObjectStruct)
PyBytesObjectFields = PyVarObjectFields + \
    (("ob_shash", rffi.LONG), ("ob_sstate", rffi.INT), ("ob_sval", rffi.CArray(lltype.Char)))
cpython_struct("PyBytesObject", PyBytesObjectFields, PyBytesObjectStruct)


@bootstrap_function
def init_bytesobject(space):
    "Type description of PyBytesObject"
    make_typedescr(space.w_bytes.layout.typedef,
                   basestruct=PyBytesObject.TO,
                   attach=bytes_attach,
                   dealloc=bytes_dealloc,
                   realize=bytes_realize)


PyBytes_Check, PyBytes_CheckExact = build_type_checkers_flags(
    "Bytes", "w_bytes")
コード例 #31
0
ファイル: cdatetime.py プロジェクト: Debug-Orz/Sypy
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.module.cpyext.pyobject import PyObject, make_ref
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL, cpython_struct,
    PyObjectFields)
from pypy.module.cpyext.import_ import PyImport_Import
from pypy.module.cpyext.typeobject import PyTypeObjectPtr
from pypy.interpreter.error import OperationError
from pypy.tool.sourcetools import func_renamer

# API import function

PyDateTime_CAPI = cpython_struct(
    'PyDateTime_CAPI',
    (('DateType', PyTypeObjectPtr),
     ('DateTimeType', PyTypeObjectPtr),
     ('TimeType', PyTypeObjectPtr),
     ('DeltaType', PyTypeObjectPtr),
     ))

@cpython_api([], lltype.Ptr(PyDateTime_CAPI))
def _PyDateTime_Import(space):
    datetimeAPI = lltype.malloc(PyDateTime_CAPI, flavor='raw',
                                track_allocation=False)

    w_datetime = PyImport_Import(space, space.wrap("datetime"))

    w_type = space.getattr(w_datetime, space.wrap("date"))
    datetimeAPI.c_DateType = rffi.cast(
        PyTypeObjectPtr, make_ref(space, w_type))

    w_type = space.getattr(w_datetime, space.wrap("datetime"))
コード例 #32
0
## These two PyPy classes implement getitem() by returning a freshly
## constructed W_IntObject or W_FloatObject.  This is not compatible
## with PyTuple_GetItem, which returns a borrowed reference.
##
## So we use this more advanced (but also likely faster) solution:
## tuple_attach makes a real PyTupleObject with an array of N
## 'PyObject *', which are created immediately and own a reference.
## Then the macro PyTuple_GET_ITEM can be implemented like CPython.
##

PyTupleObjectStruct = lltype.ForwardReference()
PyTupleObject = lltype.Ptr(PyTupleObjectStruct)
ObjectItems = rffi.CArray(PyObject)
PyTupleObjectFields = PyVarObjectFields + \
    (("ob_item", ObjectItems),)
cpython_struct("PyTupleObject", PyTupleObjectFields, PyTupleObjectStruct)

@bootstrap_function
def init_stringobject(space):
    "Type description of PyTupleObject"
    make_typedescr(space.w_tuple.layout.typedef,
                   basestruct=PyTupleObject.TO,
                   attach=tuple_attach,
                   dealloc=tuple_dealloc,
                   realize=tuple_realize)

PyTuple_Check, PyTuple_CheckExact = build_type_checkers("Tuple")

def tuple_check_ref(space, ref):
    w_type = from_ref(space, rffi.cast(PyObject, ref.c_ob_type))
    return (w_type is space.w_tuple or
コード例 #33
0
from pypy.interpreter.error import OperationError
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL, CONST_STRING,
                                    FILEP, fread, feof, Py_ssize_tP,
                                    cpython_struct)
from pypy.module.cpyext.pyobject import PyObject, borrow_from
from pypy.module.cpyext.pyerrors import PyErr_SetFromErrno
from pypy.module.__builtin__ import compiling

PyCompilerFlags = cpython_struct("PyCompilerFlags", ())
PyCompilerFlagsPtr = lltype.Ptr(PyCompilerFlags)


@cpython_api([PyObject, PyObject, PyObject], PyObject)
def PyEval_CallObjectWithKeywords(space, w_obj, w_arg, w_kwds):
    return space.call(w_obj, w_arg, w_kwds)


@cpython_api([], PyObject)
def PyEval_GetBuiltins(space):
    """Return a dictionary of the builtins in the current execution
    frame, or the interpreter of the thread state if no frame is
    currently executing."""
    caller = space.getexecutioncontext().gettopframe_nohidden()
    if caller is not None:
        w_globals = caller.w_globals
        w_builtins = space.getitem(w_globals, space.wrap('__builtins__'))
        if not space.isinstance_w(w_builtins, space.w_dict):
            w_builtins = w_builtins.getdict(space)
    else:
        w_builtins = space.builtin.getdict(space)
コード例 #34
0
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (PyObjectFields, bootstrap_function,
                                    cpython_struct, CANNOT_FAIL, cpython_api,
                                    PyObject, build_type_checkers,
                                    CONST_STRING)
from pypy.module.cpyext.pyobject import (make_typedescr, track_reference,
                                         from_ref)
from pypy.interpreter.error import OperationError
from rpython.rlib.rstruct import runpack
from pypy.objspace.std.floatobject import W_FloatObject

PyFloatObjectStruct = lltype.ForwardReference()
PyFloatObject = lltype.Ptr(PyFloatObjectStruct)
PyFloatObjectFields = PyObjectFields + \
    (("ob_fval", rffi.DOUBLE),)
cpython_struct("PyFloatObject", PyFloatObjectFields, PyFloatObjectStruct)


@bootstrap_function
def init_floatobject(space):
    "Type description of PyFloatObject"
    make_typedescr(space.w_float.layout.typedef,
                   basestruct=PyFloatObject.TO,
                   attach=float_attach,
                   realize=float_realize)


def float_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PyFloatObject with the given float object. The
    value must not be modified.
コード例 #35
0
ファイル: pystate.py プロジェクト: purepython/pypy
from pypy.module.cpyext.api import (cpython_api, generic_cpy_call, CANNOT_FAIL,
                                    CConfig, cpython_struct)
from pypy.rpython.lltypesystem import rffi, lltype

PyInterpreterStateStruct = lltype.ForwardReference()
PyInterpreterState = lltype.Ptr(PyInterpreterStateStruct)
cpython_struct("PyInterpreterState", [('next', PyInterpreterState)],
               PyInterpreterStateStruct)
PyThreadState = lltype.Ptr(
    cpython_struct("PyThreadState", [('interp', PyInterpreterState)]))


@cpython_api([], PyThreadState, error=CANNOT_FAIL)
def PyEval_SaveThread(space):
    """Release the global interpreter lock (if it has been created and thread
    support is enabled) and reset the thread state to NULL, returning the
    previous thread state (which is not NULL except in PyPy).  If the lock has been created,
    the current thread must have acquired it.  (This function is available even
    when thread support is disabled at compile time.)"""
    if rffi.aroundstate.before:
        rffi.aroundstate.before()
    return lltype.nullptr(PyThreadState.TO)


@cpython_api([PyThreadState], lltype.Void)
def PyEval_RestoreThread(space, tstate):
    """Acquire the global interpreter lock (if it has been created and thread
    support is enabled) and set the thread state to tstate, which must not be
    NULL.  If the lock has been created, the current thread must not have
    acquired it, otherwise deadlock ensues.  (This function is available even
    when thread support is disabled at compile time.)"""
コード例 #36
0
ファイル: methodobject.py プロジェクト: charred/pypy
from pypy.module.cpyext.api import (
    CONST_STRING, METH_CLASS, METH_COEXIST, METH_KEYWORDS, METH_NOARGS, METH_O,
    METH_STATIC, METH_VARARGS, PyObject, PyObjectFields, bootstrap_function,
    build_type_checkers, cpython_api, cpython_struct, generic_cpy_call)
from pypy.module.cpyext.pyobject import (
    Py_DecRef, from_ref, make_ref, make_typedescr)

PyCFunction_typedef = rffi.COpaquePtr(typedef='PyCFunction')
PyCFunction = lltype.Ptr(lltype.FuncType([PyObject, PyObject], PyObject))
PyCFunctionKwArgs = lltype.Ptr(lltype.FuncType([PyObject, PyObject, PyObject],
                                               PyObject))

PyMethodDef = cpython_struct(
    'PyMethodDef',
    [('ml_name', rffi.CCHARP),
     ('ml_meth', PyCFunction_typedef),
     ('ml_flags', rffi.INT_real),
     ('ml_doc', rffi.CCHARP),
     ])

PyCFunctionObjectStruct = cpython_struct(
    'PyCFunctionObject',
    PyObjectFields + (
     ('m_ml', lltype.Ptr(PyMethodDef)),
     ('m_self', PyObject),
     ('m_module', PyObject),
     ))
PyCFunctionObject = lltype.Ptr(PyCFunctionObjectStruct)

@bootstrap_function
def init_methodobject(space):
コード例 #37
0
ファイル: bufferobject.py プロジェクト: Debug-Orz/Sypy
from pypy.interpreter.error import OperationError
from pypy.module.array.interp_array import ArrayBuffer


PyBufferObjectStruct = lltype.ForwardReference()
PyBufferObject = lltype.Ptr(PyBufferObjectStruct)
PyBufferObjectFields = PyObjectFields + (
    ("b_base", PyObject),
    ("b_ptr", rffi.VOIDP),
    ("b_size", Py_ssize_t),
    ("b_offset", Py_ssize_t),
    ("b_readonly", rffi.INT),
    ("b_hash", rffi.LONG),
    )

cpython_struct("PyBufferObject", PyBufferObjectFields, PyBufferObjectStruct)

@bootstrap_function
def init_bufferobject(space):
    "Type description of PyBufferObject"
    make_typedescr(space.gettypefor(Buffer).instancetypedef,
                   basestruct=PyBufferObject.TO,
                   attach=buffer_attach,
                   dealloc=buffer_dealloc,
                   realize=buffer_realize)

def buffer_attach(space, py_obj, w_obj):
    """
    Fills a newly allocated PyBufferObject with the given (str) buffer object.
    """
    py_buf = rffi.cast(PyBufferObject, py_obj)
コード例 #38
0
ファイル: methodobject.py プロジェクト: sota/pypy-old
                                    METH_KEYWORDS, METH_NOARGS, METH_O,
                                    METH_STATIC, METH_VARARGS, PyObject,
                                    PyObjectFields, bootstrap_function,
                                    build_type_checkers, cpython_api,
                                    cpython_struct, generic_cpy_call)
from pypy.module.cpyext.pyobject import (Py_DecRef, from_ref, make_ref,
                                         make_typedescr)

PyCFunction_typedef = rffi.COpaquePtr(typedef='PyCFunction')
PyCFunction = lltype.Ptr(lltype.FuncType([PyObject, PyObject], PyObject))
PyCFunctionKwArgs = lltype.Ptr(
    lltype.FuncType([PyObject, PyObject, PyObject], PyObject))

PyMethodDef = cpython_struct('PyMethodDef', [
    ('ml_name', rffi.CCHARP),
    ('ml_meth', PyCFunction_typedef),
    ('ml_flags', rffi.INT_real),
    ('ml_doc', rffi.CCHARP),
])

PyCFunctionObjectStruct = cpython_struct(
    'PyCFunctionObject', PyObjectFields + (
        ('m_ml', lltype.Ptr(PyMethodDef)),
        ('m_self', PyObject),
        ('m_module', PyObject),
    ))
PyCFunctionObject = lltype.Ptr(PyCFunctionObjectStruct)


@bootstrap_function
def init_methodobject(space):
    make_typedescr(W_PyCFunctionObject.typedef,
コード例 #39
0
ファイル: memoryobject.py プロジェクト: fhalde/pypy
                                         from_ref, make_typedescr,
                                         get_typedescr, track_reference)
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rarithmetic import widen
from pypy.objspace.std.memoryobject import W_MemoryView
from pypy.module.cpyext.object import _dealloc
from pypy.module.cpyext.import_ import PyImport_Import

PyMemoryView_Check, PyMemoryView_CheckExact = build_type_checkers("MemoryView")

PyMemoryViewObjectStruct = lltype.ForwardReference()
PyMemoryViewObject = lltype.Ptr(PyMemoryViewObjectStruct)
PyMemoryViewObjectFields = PyObjectFields + \
    (("view", Py_buffer),)
cpython_struct("PyMemoryViewObject",
               PyMemoryViewObjectFields,
               PyMemoryViewObjectStruct,
               level=2)


@bootstrap_function
def init_memoryobject(space):
    "Type description of PyDictObject"
    make_typedescr(
        W_MemoryView.typedef,
        basestruct=PyMemoryViewObject.TO,
        attach=memory_attach,
        dealloc=memory_dealloc,
        realize=memory_realize,
    )

コード例 #40
0
from pypy.module.cpyext.api import (cpython_api, CANNOT_FAIL,
                                    build_type_checkers_flags, Py_ssize_t,
                                    Py_ssize_tP, CONST_STRING, PyObjectFields,
                                    cpython_struct, bootstrap_function,
                                    slot_function)
from pypy.module.cpyext.pyobject import (PyObject, PyObjectP, as_pyobj,
                                         make_typedescr, track_reference,
                                         create_ref, from_ref, decref, incref)
from pypy.module.cpyext.object import _dealloc
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall

PyDictObjectStruct = lltype.ForwardReference()
PyDictObject = lltype.Ptr(PyDictObjectStruct)
PyDictObjectFields = PyObjectFields + \
    (("_tmpkeys", PyObject),)
cpython_struct("PyDictObject", PyDictObjectFields, PyDictObjectStruct)


@bootstrap_function
def init_dictobject(space):
    "Type description of PyDictObject"
    make_typedescr(space.w_dict.layout.typedef,
                   basestruct=PyDictObject.TO,
                   attach=dict_attach,
                   dealloc=dict_dealloc,
                   realize=dict_realize)


def dict_attach(space, py_obj, w_obj, w_userdata=None):
    """
    Fills a newly allocated PyDictObject with the given dict object.
コード例 #41
0
ファイル: typeobject.py プロジェクト: devopsmi/pypy
    __delete__ = interp2app(GetSetProperty.descr_property_del),
    __name__ = interp_attrproperty('name', cls=GetSetProperty,
        wrapfn="newtext_or_none"),
    __objclass__ = GetSetProperty(GetSetProperty.descr_get_objclass),
    __doc__ = interp_attrproperty('doc', cls=GetSetProperty,
        wrapfn="newtext_or_none"),
    )
assert not W_MemberDescr.typedef.acceptable_as_base_class  # no __new__

PyDescrObject = lltype.ForwardReference()
PyDescrObjectPtr = lltype.Ptr(PyDescrObject)
PyDescrObjectFields = PyObjectFields + (
    ("d_type", PyTypeObjectPtr),
    ("d_name", PyObject),
    )
cpython_struct("PyDescrObject", PyDescrObjectFields,
               PyDescrObject)

PyMemberDescrObjectStruct = lltype.ForwardReference()
PyMemberDescrObject = lltype.Ptr(PyMemberDescrObjectStruct)
PyMemberDescrObjectFields = PyDescrObjectFields + (
    ("d_member", lltype.Ptr(PyMemberDef)),
    )
cpython_struct("PyMemberDescrObject", PyMemberDescrObjectFields,
               PyMemberDescrObjectStruct, level=2)

PyGetSetDescrObjectStruct = lltype.ForwardReference()
PyGetSetDescrObject = lltype.Ptr(PyGetSetDescrObjectStruct)
PyGetSetDescrObjectFields = PyDescrObjectFields + (
    ("d_getset", lltype.Ptr(PyGetSetDef)),
    )
cpython_struct("PyGetSetDescrObject", PyGetSetDescrObjectFields,
コード例 #42
0
ファイル: unicodeobject.py プロジェクト: purepython/pypy
                                         make_ref, from_ref, track_reference,
                                         make_typedescr, get_typedescr)
from pypy.module.cpyext.stringobject import PyString_Check
from pypy.module.sys.interp_encoding import setdefaultencoding
from pypy.objspace.std import unicodeobject, unicodetype
from pypy.rlib import runicode
from pypy.tool.sourcetools import func_renamer
import sys

## See comment in stringobject.py.

PyUnicodeObjectStruct = lltype.ForwardReference()
PyUnicodeObject = lltype.Ptr(PyUnicodeObjectStruct)
PyUnicodeObjectFields = (PyObjectFields + (("buffer", rffi.CWCHARP),
                                           ("size", Py_ssize_t)))
cpython_struct("PyUnicodeObject", PyUnicodeObjectFields, PyUnicodeObjectStruct)


@bootstrap_function
def init_unicodeobject(space):
    make_typedescr(space.w_unicode.instancetypedef,
                   basestruct=PyUnicodeObject.TO,
                   attach=unicode_attach,
                   dealloc=unicode_dealloc,
                   realize=unicode_realize)


# Buffer for the default encoding (used by PyUnicde_GetDefaultEncoding)
DEFAULT_ENCODING_SIZE = 100
default_encoding = lltype.malloc(rffi.CCHARP.TO,
                                 DEFAULT_ENCODING_SIZE,
コード例 #43
0
ファイル: frameobject.py プロジェクト: gorakhargosh/pypy
    make_typedescr, get_typedescr)
from pypy.module.cpyext.state import State
from pypy.module.cpyext.pystate import PyThreadState
from pypy.module.cpyext.funcobject import PyCodeObject
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.pycode import PyCode
from pypy.interpreter.pytraceback import PyTraceback

PyFrameObjectStruct = lltype.ForwardReference()
PyFrameObject = lltype.Ptr(PyFrameObjectStruct)
PyFrameObjectFields = (PyObjectFields +
    (("f_code", PyCodeObject),
     ("f_globals", PyObject),
     ("f_lineno", rffi.INT),
     ))
cpython_struct("PyFrameObject", PyFrameObjectFields, PyFrameObjectStruct)

@bootstrap_function
def init_frameobject(space):
    make_typedescr(PyFrame.typedef,
                   basestruct=PyFrameObject.TO,
                   attach=frame_attach,
                   dealloc=frame_dealloc,
                   realize=frame_realize)

def frame_attach(space, py_obj, w_obj):
    "Fills a newly allocated PyFrameObject with a frame object"
    frame = space.interp_w(PyFrame, w_obj)
    py_frame = rffi.cast(PyFrameObject, py_obj)
    py_frame.c_f_code = rffi.cast(PyCodeObject, make_ref(space, frame.pycode))
    py_frame.c_f_globals = make_ref(space, frame.w_globals)
コード例 #44
0
ファイル: tupleobject.py プロジェクト: mozillazg/pypy
## These two PyPy classes implement getitem() by returning a freshly
## constructed W_IntObject or W_FloatObject.  This is not compatible
## with PyTuple_GetItem, which returns a borrowed reference.
##
## So we use this more advanced (but also likely faster) solution:
## tuple_attach makes a real PyTupleObject with an array of N
## 'PyObject *', which are created immediately and own a reference.
## Then the macro PyTuple_GET_ITEM can be implemented like CPython.
##

PyTupleObjectStruct = lltype.ForwardReference()
PyTupleObject = lltype.Ptr(PyTupleObjectStruct)
ObjectItems = rffi.CArray(PyObject)
PyTupleObjectFields = PyVarObjectFields + \
    (("ob_item", ObjectItems),)
cpython_struct("PyTupleObject", PyTupleObjectFields, PyTupleObjectStruct)

@bootstrap_function
def init_stringobject(space):
    "Type description of PyTupleObject"
    make_typedescr(space.w_tuple.layout.typedef,
                   basestruct=PyTupleObject.TO,
                   attach=tuple_attach,
                   dealloc=tuple_dealloc,
                   realize=tuple_realize)

PyTuple_Check, PyTuple_CheckExact = build_type_checkers("Tuple")

def tuple_check_ref(space, ref):
    w_type = from_ref(space, rffi.cast(PyObject, ref.c_ob_type))
    return (w_type is space.w_tuple or
コード例 #45
0
from pypy.module.cpyext.pyobject import (PyObject, make_ref, from_ref, decref,
                                         make_typedescr)
from pypy.module.cpyext.frameobject import PyFrameObject
from pypy.interpreter.error import OperationError
from pypy.interpreter.pytraceback import PyTraceback
from pypy.interpreter import pycode

PyTracebackObjectStruct = lltype.ForwardReference()
PyTracebackObject = lltype.Ptr(PyTracebackObjectStruct)
PyTracebackObjectFields = PyObjectFields + (
    ("tb_next", PyTracebackObject),
    ("tb_frame", PyFrameObject),
    ("tb_lasti", rffi.INT),
    ("tb_lineno", rffi.INT),
)
cpython_struct("PyTracebackObject", PyTracebackObjectFields,
               PyTracebackObjectStruct)


@bootstrap_function
def init_traceback(space):
    make_typedescr(PyTraceback.typedef,
                   basestruct=PyTracebackObject.TO,
                   attach=traceback_attach,
                   dealloc=traceback_dealloc)


def traceback_attach(space, py_obj, w_obj, w_userdata=None):
    py_traceback = rffi.cast(PyTracebackObject, py_obj)
    traceback = space.interp_w(PyTraceback, w_obj)
    if traceback.next is None:
        w_next_traceback = None
コード例 #46
0
CODE_FLAGS = dict(
    CO_OPTIMIZED=0x0001,
    CO_NEWLOCALS=0x0002,
    CO_VARARGS=0x0004,
    CO_VARKEYWORDS=0x0008,
    CO_NESTED=0x0010,
    CO_GENERATOR=0x0020,
)
ALL_CODE_FLAGS = unrolling_iterable(CODE_FLAGS.items())

PyFunctionObjectStruct = lltype.ForwardReference()
PyFunctionObject = lltype.Ptr(PyFunctionObjectStruct)
PyFunctionObjectFields = PyObjectFields + \
    (("func_name", PyObject),)
cpython_struct("PyFunctionObject", PyFunctionObjectFields,
               PyFunctionObjectStruct)

PyCodeObjectStruct = lltype.ForwardReference()
PyCodeObject = lltype.Ptr(PyCodeObjectStruct)
PyCodeObjectFields = PyObjectFields + \
    (("co_name", PyObject),
     ("co_filename", PyObject),
     ("co_flags", rffi.INT),
     ("co_argcount", rffi.INT),
    )
cpython_struct("PyCodeObject", PyCodeObjectFields, PyCodeObjectStruct)


@bootstrap_function
def init_functionobject(space):
    make_typedescr(Function.typedef,
コード例 #47
0
ファイル: modsupport.py プロジェクト: Qointum/pypy
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import cpython_api, cpython_struct, \
        METH_STATIC, METH_CLASS, METH_COEXIST, CANNOT_FAIL, CONST_STRING
from pypy.module.cpyext.pyobject import PyObject, borrow_from
from pypy.interpreter.module import Module
from pypy.module.cpyext.methodobject import (W_PyCFunctionObject,
                                             PyCFunction_NewEx,
                                             PyDescr_NewMethod, PyMethodDef,
                                             PyDescr_NewClassMethod,
                                             PyStaticMethod_New)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.module.cpyext.state import State
from pypy.interpreter.error import OperationError

PyModuleDef_BaseStruct = cpython_struct('PyModuleDef_Base', [])

PyModuleDefStruct = cpython_struct('PyModuleDef', [
    ('m_base', PyModuleDef_BaseStruct),
    ('m_name', rffi.CCHARP),
    ('m_doc', rffi.CCHARP),
    ('m_methods', lltype.Ptr(PyMethodDef)),
],
                                   level=2)
PyModuleDef = lltype.Ptr(PyModuleDefStruct)


@cpython_api([PyModuleDef, rffi.INT_real], PyObject)
def PyModule_Create2(space, module, api_version):
    """Create a new module object, given the definition in module, assuming the
    API version module_api_version.  If that version does not match the version
    of the running interpreter, a RuntimeWarning is emitted.