[pypy-svn] r25767 - in pypy/dist/pypy/rpython/rctypes: . test
arigo at codespeak.net
arigo at codespeak.net
Thu Apr 13 09:03:01 CEST 2006
Author: arigo
Date: Thu Apr 13 09:02:58 2006
New Revision: 25767
Removed:
pypy/dist/pypy/rpython/rctypes/interface.py
Modified:
pypy/dist/pypy/rpython/rctypes/__init__.py
pypy/dist/pypy/rpython/rctypes/ctypes_platform.py
pypy/dist/pypy/rpython/rctypes/implementation.py
pypy/dist/pypy/rpython/rctypes/test/_rctypes_test.c (contents, props changed)
pypy/dist/pypy/rpython/rctypes/test/test_rarray.py
pypy/dist/pypy/rpython/rctypes/test/test_rchar_p.py
pypy/dist/pypy/rpython/rctypes/test/test_rctypes.py
pypy/dist/pypy/rpython/rctypes/test/test_rfunc.py
pypy/dist/pypy/rpython/rctypes/test/test_rpointer.py
pypy/dist/pypy/rpython/rctypes/test/test_rprimitive.py
Log:
Reorganized the rctypes modules to match our coding style.
Modified: pypy/dist/pypy/rpython/rctypes/__init__.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/__init__.py (original)
+++ pypy/dist/pypy/rpython/rctypes/__init__.py Thu Apr 13 09:02:58 2006
@@ -1 +1 @@
-from pypy.rpython.rctypes.interface import *
+#empty
Modified: pypy/dist/pypy/rpython/rctypes/ctypes_platform.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/ctypes_platform.py (original)
+++ pypy/dist/pypy/rpython/rctypes/ctypes_platform.py Thu Apr 13 09:02:58 2006
@@ -238,19 +238,19 @@
opts, args = getopt.gnu_getopt(sys.argv[1:], 'h:')
if not args:
print >> sys.stderr, doc
- sys.exit(2)
- assert len(args) % 2 == 1
- headers = []
- for opt, value in opts:
- if opt == '-h':
- headers.append('#include <%s>' % (value,))
- name = args[0]
- fields = []
- for i in range(1, len(args), 2):
- ctype = getattr(ctypes, args[i+1])
- fields.append((args[i], ctype))
+ else:
+ assert len(args) % 2 == 1
+ headers = []
+ for opt, value in opts:
+ if opt == '-h':
+ headers.append('#include <%s>' % (value,))
+ name = args[0]
+ fields = []
+ for i in range(1, len(args), 2):
+ ctype = getattr(ctypes, args[i+1])
+ fields.append((args[i], ctype))
- S = getstruct(name, '\n'.join(headers), fields)
+ S = getstruct(name, '\n'.join(headers), fields)
- for key, value in S._fields_:
- print key, value
+ for key, value in S._fields_:
+ print key, value
Modified: pypy/dist/pypy/rpython/rctypes/implementation.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/implementation.py (original)
+++ pypy/dist/pypy/rpython/rctypes/implementation.py Thu Apr 13 09:02:58 2006
@@ -1,464 +1,21 @@
-"""
-The rctypes implementaion is contained here.
-"""
-
-import sys
-import ctypes
-from ctypes import *
-from ctypes import _FUNCFLAG_CDECL
-if sys.platform == "win32":
- from ctypes import _FUNCFLAG_STDCALL
-from pypy.annotation.model import SomeInteger, SomeCTypesObject, \
- SomeString, SomeFloat, SomeBuiltin
-from pypy.rpython.lltypesystem.lltype import Signed, SignedLongLong, \
- Unsigned, UnsignedLongLong, Char, Float, Ptr, \
- GcStruct, Struct, \
- Void
-from pypy.rpython.rmodel import Repr, IntegerRepr, inputconst
-from pypy.rpython.error import TyperError
-from pypy.rpython import extregistry
-from pypy.annotation.pairtype import pairtype
-from pypy.rpython import rint
-
# Importing for side effect of registering types with extregistry
-import pypy.rpython.rctypes.rarray
import pypy.rpython.rctypes.rprimitive
import pypy.rpython.rctypes.rpointer
+import pypy.rpython.rctypes.rarray
import pypy.rpython.rctypes.rfunc
import pypy.rpython.rctypes.rchar_p
-# ctypes_annotation_list contains various attributes that
-# are used by the pypy annotation.
-
-ctypes_annotation_list = [
-# (c_char, Char, None),
-# (c_byte, Signed, None),
-# (c_ubyte, Unsigned, None),
-# (c_short, Signed, None),
-# (c_ushort, Unsigned, None),
-# (c_int, Signed, None),
-# (c_uint, Unsigned, None),
-# (c_long, Signed, None),
-# (c_ulong, Unsigned, None),
-# (c_longlong, SignedLongLong, None),
-# (c_ulonglong, UnsignedLongLong, None),
-# (c_float, Float, None),
-# (c_double, Float, None),
-# (c_char_p, None,
-# staticmethod(lambda ll_type, arg_name:"RPyString_AsString(%s)" % arg_name)),
-# (POINTER(c_char), None,
-# staticmethod(lambda ll_type, arg_name:"RPyString_AsString(%s)" % arg_name)),
-]
-
-def create_ctypes_annotations():
- """
- create_ctypes_annotation creates a map between
- ctypes, annotation types and low level types.
- For convenience, an existing map from low level types to
- annotation types is used ('ll_to_annotation_map').
- """
-
- from pypy.annotation.model import ll_to_annotation_map
- for the_type, ll_type, wrap_arg in ctypes_annotation_list:
- the_type.annotator_type = ll_to_annotation_map.get(ll_type)
- the_type.ll_type = ll_type
- if wrap_arg is not None:
- the_type.wrap_arg = wrap_arg
- the_type.default_memorystate = SomeCTypesObject.OWNSMEMORY
- the_type.external_function_result_memorystate = SomeCTypesObject.MEMORYALIAS
- else:
- # !!!! attention !!!!
- # the basic c_types need some annotation information
- # at the moment that are exactly the types that have
- # no 'wrap_arg'. This might change in the future
- #the_type.compute_result_annotation = classmethod(lambda cls, s_arg:SomeCTypesObject(cls))
- def do_register(the_type):
- extregistry.register_value(the_type,
- compute_result_annotation=lambda s_arg: SomeCTypesObject(the_type))
- # XXX we need to register the correct repr for each primitive
- extregistry.register_type(the_type,
- get_repr=lambda rtyper, s_primitive: rint.signed_repr)
- do_register(the_type)
- the_type.default_memorystate = SomeCTypesObject.NOMEMORY
-
-create_ctypes_annotations()
-
-
-class FunctionPointerTranslation(object):
-
- def compute_result_annotation(self, *args_s):
- """
- Answer the annotation of the external function's result
- """
- # Take 3, Check whether we can get away with the cheap
- # precomputed solution and if not it, use a special
- # attribute with the memory state
- try:
- return self.restype.annotator_type
- except AttributeError:
- return SomeCTypesObject(
- self.restype,
- self.restype.external_function_result_memorystate )
- # Take 2, looks like we need another level of indirection
- # That's to complicated
- #o#return self.restype.compute_external_function_result_annotator_type()
- # TODO: Check whether the function returns a pointer
- # an correct the memory state appropriately
- try:
- return self.restype.annotator_type
- except AttributeError:
- return SomeCTypesObject(self.restype)
-
- def __hash__(self):
- return id(self)
-
- def specialize(self, hop):
- return hop.llops.gencapicall(
- self.__name__,
- hop.args_v,
- resulttype = self.restype.ll_type,
- _callable=None,
- convert_params = self.convert_params )
-
- def convert_params(self, backend, param_info_list):
- assert "c" == backend.lower()
- assert self.argtypes is not None
- answer = []
- for ctype_type, (ll_type, arg_name) in zip(self.argtypes, param_info_list):
- if ll_type == ctype_type.ll_type:
- answer.append(arg_name)
- else:
- answer.append(ctype_type.wrap_arg(ll_type, arg_name))
- return answer
-#
-#class CtypesBasicTypeInstantiationTranslation( FunctionPointerTranslation ):
-#
-# compute_result_annotation = classmethod(
-# FunctionPointerTranslation.compute_result_annotation)
-#
-
-class RStructureMeta(type(Structure)):
- def __new__(mta,name,bases,clsdict):
- _fields = clsdict.get('_fields_',None)
- _adict = {}
- ll_types = []
- if _fields is not None:
- for attr, atype in _fields:
- _adict[attr] = atype
- ll_types.append( ( attr, atype.ll_type ) )
- clsdict['_fields_def_'] = _adict
- # ll_type is just the C-level data part of the structure
- clsdict[ "ll_type" ] = Struct( "C-Data_%s" % name, *ll_types )
- #d#print "_fields_def_ s:", _adict
-
- return super(RStructureMeta,mta).__new__(mta, name, bases, clsdict)
-
-
-class RStructure(Structure):
-
- __metaclass__ = RStructureMeta
-
- default_memorystate = SomeCTypesObject.OWNSMEMORY
- external_function_result_memorystate = default_memorystate
-
- def compute_annotation(cls):
- return SomeCTypesObject(cls)
- compute_annotation = classmethod(compute_annotation)
-
- def specialize( cls, highLevelOperation ):
- ctypesStructureType = highLevelOperation.r_result.lowleveltype
- return highLevelOperation.llops.genop(
- "malloc", [ inputconst( Void, ctypesStructureType ) ],
- highLevelOperation.r_result )
- if False:
- def specialize( cls, highLevelOperation ):
- ctypesStructureType = highLevelOperation.r_result.lowleveltype
- answer = highLevelOperation.llops.genop(
- "malloc", [ inputconst( Void, ctypesStructureType ) ],
- highLevelOperation.r_result )
- import pdb
- pdb.set_trace()
- return answer
- specialize = classmethod(specialize)
-
- def compute_result_annotation(cls, *args_s):
- """
- Answer the result annotation of calling 'cls'.
- """
- return SomeCTypesObject(cls,SomeCTypesObject.OWNSMEMORY)
- compute_result_annotation = classmethod(compute_result_annotation)
-
- def createLowLevelRepresentation( rtyper, annotationObject ):
- """
- Answer the correspondending low level object.
- """
- if annotationObject.memorystate == annotationObject.OWNSMEMORY:
- return CtypesMemoryOwningStructureRepresentation(
- rtyper, annotationObject )
- elif annotationObject.memorystate == annotationObject.MEMORYALIAS:
- return CtypesMemoryAliasStructureRepresentation(
- rtyper, annotationObject )
- else:
- raise TyperError( "Unkown memory state in %r" % annotationObject )
- createLowLevelRepresentation = staticmethod( createLowLevelRepresentation )
-
-
-class RByrefObj(object):
-
- default_memorystate = SomeCTypesObject.MEMORYALIAS
-
- def __init__(self):
- self.__name__ = 'RByrefObj'
-
- def compute_result_annotation(cls, s_arg):
- """
- Answer the result annotation of calling 'byref'.
- """
- return SomeCTypesObject(POINTER(s_arg.knowntype))
-
- compute_result_annotation = classmethod(compute_result_annotation)
-
- def __call__(self,obj):
- return byref(obj)
-
-RByref = RByrefObj()
+# Register the correspondance between SomeCTypesObject and the get_repr()
+# functions attached to the extregistry to create CTypesReprs
-def RPOINTER(cls):
- answer = POINTER(cls)
-
- def compute_result_annotation(cls, s_arg):
- """
- Answer the result annotation of calling 'cls'.
- """
- assert answer is cls
- try:
- memorystate = s_arg.memorystate
- except AttributeError:
- memorystate = None
- return SomeCTypesObject(cls, memorystate)
- answer.compute_result_annotation = classmethod(compute_result_annotation)
-
- def createLowLevelRepresentation( rtyper, annotationObject ):
- """
- Create a lowlevel representation for the pointer.
- """
- if annotationObject.memorystate == annotationObject.OWNSMEMORY:
- return CtypesMemoryOwningPointerRepresentation( rtyper, annotationObject )
- elif annotationObject.memorystate == annotationObject.MEMORYALIAS:
- return CtypesMemoryAliasPointerRepresentation( rtyper, annotationObject )
- else:
- raise TyperError( "Unkown memory state in %r" % annotationObject )
- answer.createLowLevelRepresentation = staticmethod(
- createLowLevelRepresentation )
-
- def specialize( cls, highLevelOperation ):
- #d#print "specialize:", cls, highLevelOperation
- ctypesStructureType = highLevelOperation.r_result.lowleveltype
- answer = highLevelOperation.llops.genop(
- "malloc", [ inputconst( Void, ctypesStructureType ) ],
- highLevelOperation.r_result )
- #d#import pdb
- #d#pdb.set_trace()
- if True:
- highLevelOperation.llops.genop(
- "setfield",
- [ answer,
- inputconst( Void, "contents" ),
- highLevelOperation.inputarg( highLevelOperation.args_r[ 0 ], 0 ) ] )
- #t#highLevelOperation.inputarg( highLevelOperation.args_r[ 0 ], 0 ) ],
- #t#highLevelOperation.r_result )
- return answer
- answer.specialize = classmethod( specialize )
-
- # We specialcased accessing pointers be getting their contents attribute
- # because we can't use the memory state from 'cls'.
- # So the obvious way to do it is obsolete (#o#).
- answer._fields_def_ = {"contents": cls}
- #d#print "p _fields_def_:", answer._fields_def_
-
- # XXX Think about that twice and think about obsoleting
- # the obsoletion above
- answer.default_memorystate = None
- answer.external_function_result_memorystate = SomeCTypesObject.MEMORYALIAS
-
- # Add a low level type attribute, which is only used for computing the
- # result of an external function. In other words this is just the non
- # gc case
- try:
- answer.ll_type = Ptr(
- Struct(
- 'CtypesMemoryAliasPointer_%s' % answer.__name__,
- ( "contents", answer._type_.ll_type ) ) )
- except TypeError:
- pass
- return answer
-
-
-# class RCDLL(CDLL):
-# """
-# This is the restricted version of ctypes' CDLL class.
-# """
-#
-# class _CdeclFuncPtr(FunctionPointerTranslation, CDLL._CdeclFuncPtr):
-# """
-# A simple extension of ctypes function pointers that
-# implements a simple interface to the anotator.
-# """
-# _flags_ = _FUNCFLAG_CDECL
-#
-#
-#
-# if sys.platform == "win32":
-# class RWinDLL(WinDLL):
-# """
-# This is the restricted version of ctypes' WINDLL class
-# """
-#
-# class _StdcallFuncPtr(FunctionPointerTranslation, WinDLL._StdcallFuncPtr):
-# """
-# A simple extension of ctypes function pointers that
-# implements a simple interface to the anotator.
-# """
-# _flags_ = _FUNCFLAG_STDCALL
-
-# def RARRAY(typ,length):
-# answer = ARRAY(typ,length)
-# def compute_result_annotation(cls, *arg_s):
-# """
-# Answer the result annotation of calling 'cls'.
-# """
-# assert answer is cls
-# return SomeCTypesObject(cls, SomeCTypesObject.OWNSMEMORY)
-# answer.compute_result_annotation = classmethod(compute_result_annotation)
-# return answer
-
-class AbstractCtypesRepresentation( Repr ):
- """
- The abstract base class of all ctypes low level representations.
- """
-
-class AbstractCtypesStructureRepresentation( AbstractCtypesRepresentation ):
- """
- The abstract base class of ctypes structures' low level representation.
- """
-
- def generateCDataAccess( self, variable, lowLevelOperations ):
- """
- Answer the C level data sub structure.
- """
- inputargs = [ variable, inputconst( Void, "c_data" ) ]
- return lowLevelOperations.genop(
- "getsubstruct",
- inputargs,
- Ptr( self.c_data_lowleveltype ) )
-
- def rtype_setattr( self, highLevelOperation ):
- c_data = self.generateCDataAccess(
- highLevelOperation.inputarg( self, 0 ),
- highLevelOperation.llops )
- inputargs = highLevelOperation.inputargs(
- *highLevelOperation.args_r[ :3 ] )
- inputargs[ 0 ] = c_data
- print "inputargs:", inputargs
- print "r_result:", highLevelOperation.r_result
- highLevelOperation.genop( "setfield", inputargs )
-
- def rtype_getattr( self, highLevelOperation ):
- c_data = self.generateCDataAccess(
- highLevelOperation.inputarg( self, 0 ),
- highLevelOperation.llops )
- inputargs = highLevelOperation.inputargs(
- *highLevelOperation.args_r[ :3 ] )
- inputargs[ 0 ] = c_data
- return highLevelOperation.genop(
- "getfield",
- inputargs,
- highLevelOperation.r_result )
-
-
-class CtypesMemoryOwningStructureRepresentation( AbstractCtypesStructureRepresentation ):
- """
- The lowlevel representation of a rctypes structure that owns its memory.
- """
-
- def __init__( self, rtyper, annotationObject ):
- # XXX This .ll_type may not work for pointers or structures
- # containing structures
- fields = [ ( name, ctypesType.ll_type )
- for name, ctypesType in annotationObject.knowntype._fields_ ]
- name = annotationObject.knowntype.__name__
- #o#self.c_data_lowleveltype = Struct( "C-Data_%s" % name, *fields )
- self.c_data_lowleveltype = annotationObject.knowntype.ll_type
- self.lowleveltype = Ptr(
- GcStruct(
- "CtypesStructure_%s" % name,
- ( "c_data", self.c_data_lowleveltype ) ) )
-
-
-class CtypesMemoryAliasStructureRepresentation( AbstractCtypesStructureRepresentation ):
- """
- The lowlevel representation of a rctypes structure that is an alias to
- someone else's memory.
- """
-
-
-class AbstractCtypesPointerRepresentation( AbstractCtypesRepresentation ):
- """
- The abstract base class of all rctypes low level representations
- of a pointer.
- """
-
-
-class CtypesMemoryOwningPointerRepresentation( AbstractCtypesPointerRepresentation ):
- """
- The lowlevel representation of a cytpes pointer that points
- to memory owned by rcyptes.
- """
-
- def __init__( self, rtyper, annotationObject ):
- self.lowleveltype = Ptr(
- GcStruct(
- 'CtypesMemoryOwningPointer_%s' % annotationObject.knowntype.__name__,
- ( "contents",
- rtyper.getrepr(
- annotationObject.knowntype._type_.compute_annotation()
- ).lowleveltype ) ) )
-
- def rtype_getattr( self, highLevelOperation ):
- inputargs = [
- highLevelOperation.inputarg( highLevelOperation.args_r[ 0 ], 0 ),
- inputconst( Void, "contents" ) ]
- return highLevelOperation.genop(
- "getfield", inputargs, highLevelOperation.r_result )
-
-
-class CtypesMemoryAliasPointerRepresentation( AbstractCtypesPointerRepresentation ):
- """
- The lowlevel representation of a cytpes pointer that points
- to memory owned by an external library.
- """
-
- def __init__( self, rtyper, annotationObject ):
- self.lowleveltype = annotationObject.knowntype.ll_type
+from pypy.annotation.model import SomeCTypesObject
+from pypy.rpython import extregistry
-
class __extend__( SomeCTypesObject ):
def rtyper_makerepr( self, rtyper ):
- if extregistry.is_registered_type(self.knowntype):
- entry = extregistry.lookup_type(self.knowntype)
- return entry.get_repr(rtyper, self)
- return self.knowntype.createLowLevelRepresentation( rtyper, self )
-
+ entry = extregistry.lookup_type(self.knowntype)
+ return entry.get_repr(rtyper, self)
+
def rtyper_makekey( self ):
return self.__class__, self.knowntype, self.memorystate
-
-
-class __extend__( pairtype( CtypesMemoryOwningPointerRepresentation, IntegerRepr ) ):
- def rtype_getitem( ( self, integer ), highLevelOperation ):
- print "rtype_getitem:", integer
- return highLevelOperation.genop(
- "getfield",
- "contents",
- highLevelOperation.r_result )
-
Modified: pypy/dist/pypy/rpython/rctypes/test/_rctypes_test.c
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/_rctypes_test.c (original)
+++ pypy/dist/pypy/rpython/rctypes/test/_rctypes_test.c Thu Apr 13 09:02:58 2006
@@ -1,52 +1,52 @@
-/* simple test, currently only for structures */
-#include <Python.h>
-#ifdef MS_WIN32
-#include <windows.h>
-#endif
-#if defined(MS_WIN32) || defined(__CYGWIN__)
-#define EXPORT(x) __declspec(dllexport) x
-#else
-#define EXPORT(x) x
-#endif
-
-PyMethodDef module_methods[] = {
- { NULL, NULL, 0, NULL},
-};
-
-
-typedef struct tagpoint {
- int x;
- int y;
-} point;
-
-EXPORT(int) _testfunc_byval(point in, point *pout)
-{
- if (pout)
- {
- pout->x = in.x;
- pout->y = in.y;
- }
- return in.x + in.y;
-}
-
-EXPORT(int) _testfunc_struct(point in)
-{
- return in.x + in.y;
-}
-
-EXPORT(point) _testfunc_struct_id(point in)
-{
- return in;
-}
-
-EXPORT(point*) _testfunc_struct_pointer_id( point* pin )
-{
- return pin;
-}
-
-DL_EXPORT(void)
-init_rctypes_test(void)
-{
- Py_InitModule("_rctypes_test", module_methods);
-}
-
+/* simple test, currently only for structures */
+#include <Python.h>
+#ifdef MS_WIN32
+#include <windows.h>
+#endif
+#if defined(MS_WIN32) || defined(__CYGWIN__)
+#define EXPORT(x) __declspec(dllexport) x
+#else
+#define EXPORT(x) x
+#endif
+
+PyMethodDef module_methods[] = {
+ { NULL, NULL, 0, NULL},
+};
+
+
+typedef struct tagpoint {
+ int x;
+ int y;
+} point;
+
+EXPORT(int) _testfunc_byval(point in, point *pout)
+{
+ if (pout)
+ {
+ pout->x = in.x;
+ pout->y = in.y;
+ }
+ return in.x + in.y;
+}
+
+EXPORT(int) _testfunc_struct(point in)
+{
+ return in.x + in.y;
+}
+
+EXPORT(point) _testfunc_struct_id(point in)
+{
+ return in;
+}
+
+EXPORT(point*) _testfunc_struct_pointer_id( point* pin )
+{
+ return pin;
+}
+
+DL_EXPORT(void)
+init_rctypes_test(void)
+{
+ Py_InitModule("_rctypes_test", module_methods);
+}
+
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rarray.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rarray.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rarray.py Thu Apr 13 09:02:58 2006
@@ -3,6 +3,7 @@
"""
import py.test
+import pypy.rpython.rctypes.implementation
from pypy.annotation.annrpython import RPythonAnnotator
from pypy.translator.translator import TranslationContext
from pypy import conftest
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rchar_p.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rchar_p.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rchar_p.py Thu Apr 13 09:02:58 2006
@@ -3,6 +3,7 @@
"""
import py.test
+import pypy.rpython.rctypes.implementation
from pypy.annotation.annrpython import RPythonAnnotator
from pypy.translator.translator import TranslationContext
from pypy.translator.c.test.test_genc import compile
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rctypes.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rctypes.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rctypes.py Thu Apr 13 09:02:58 2006
@@ -1,54 +1,29 @@
"""
-Test the rctypes implementation.
+Test external function calls using the custom extension module _rctypes_test.c.
"""
-import py.test
+import py
from pypy.annotation.annrpython import RPythonAnnotator
from pypy.translator.translator import TranslationContext
from pypy.translator.c.test.test_genc import compile, compile_db
-#o#from pypy.translator.c import compile
from pypy.translator.tool.cbuild import compile_c_module
from pypy.annotation.model import SomeCTypesObject, SomeObject
from pypy import conftest
import sys
from pypy.rpython.test.test_llinterp import interpret
-thisdir = py.magic.autopath().dirpath()
+thisdir = py.path.local(__file__).dirpath()
-def compile(fn, argtypes, view=conftest.option.view):
- from pypy.translator.c.database import LowLevelDatabase
- from pypy.rpython.lltypesystem.lltype import pyobjectptr
- t = TranslationContext()
- a = t.buildannotator()
- a.build_types(fn, argtypes)
- t.buildrtyper().specialize()
- if view:
- t.view()
- #t#backend_optimizations(t)
- db = LowLevelDatabase(t)
- entrypoint = db.get(pyobjectptr(fn))
- db.complete()
- module = compile_db(db)
- compiled_fn = getattr(module, entrypoint)
- def checking_fn(*args, **kwds):
- res = compiled_fn(*args, **kwds)
- mallocs, frees = module.malloc_counters()
- assert mallocs == frees
- return res
- return checking_fn
-
try:
import ctypes
except ImportError:
py.test.skip("this test needs ctypes installed")
-#py.test.skip("these tests are broken while the ctypes primitive types are ported to use the extregistry")
+from ctypes import cdll
+from ctypes import POINTER, Structure, c_int
-from pypy.rpython.rctypes import cdll, c_char_p, c_int, c_char, \
- c_char, c_byte, c_ubyte, c_short, c_ushort, c_uint,\
- c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double, \
- POINTER, Structure, byref, ARRAY
+# __________ compile and load our local test C file __________
# LoadLibrary is deprecated in ctypes, this should be removed at some point
if "load" in dir(cdll):
@@ -56,29 +31,6 @@
else:
cdll_load = cdll.LoadLibrary
-if sys.platform == 'win32':
- mylib = cdll_load('msvcrt.dll')
-elif sys.platform == 'linux2':
- mylib = cdll_load('libc.so.6')
-elif sys.platform == 'darwin':
- mylib = cdll.c
-else:
- py.test.skip("don't know how to load the c lib for %s" %
- sys.platform)
-
-atoi = mylib.atoi
-atoi.restype = c_int
-atoi.argtypes = [c_char_p]
-atoi.argtypes = [POINTER(c_char)]
-
-def o_atoi(a):
- return atoi(a)
-
-class tagpoint(Structure):
- _fields_ = [("x", c_int),
- ("y", c_int)]
-
-# compile and load our local test C file
# XXX the built module and intermediate files should go to /tmp/usession-*,
# see pypy.tool.udir
compile_c_module([thisdir.join("_rctypes_test.c")], "_rctypes_test")
@@ -88,387 +40,31 @@
else:
_rctypes_test = cdll_load(str(thisdir.join("_rctypes_test.so")))
+# struct tagpoint
+class tagpoint(Structure):
+ _fields_ = [("x", c_int),
+ ("y", c_int)]
+
# _testfunc_byval
testfunc_byval = _rctypes_test._testfunc_byval
testfunc_byval.restype = c_int
testfunc_byval.argtypes = [tagpoint,POINTER(tagpoint)]
-def py_testfunc_byval(inpoint):
- opoint = tagpoint()
- res = testfunc_byval(inpoint,byref(opoint))
-
- return res, opoint
-
# _test_struct
testfunc_struct = _rctypes_test._testfunc_struct
testfunc_struct.restype = c_int
testfunc_struct.argtypes = [tagpoint]
-def py_testfunc_struct(inpoint):
- return testfunc_struct(inpoint)
-
# _test_struct_id
testfunc_struct_id = _rctypes_test._testfunc_struct_id
testfunc_struct_id.restype = tagpoint
testfunc_struct_id.argtypes = [tagpoint]
-def py_testfunc_struct_id(inpoint):
- return testfunc_struct_id(inpoint)
-
-
-oppoint_type = POINTER(tagpoint)
-
# _test_struct_id_pointer
+tagpointptr = POINTER(tagpoint)
testfunc_struct_pointer_id = _rctypes_test._testfunc_struct_pointer_id
-testfunc_struct_pointer_id.restype = oppoint_type
-testfunc_struct_pointer_id.argtypes = [oppoint_type]
-
-def py_testfunc_struct_pointer_id(inpoint):
- return testfunc_struct_pointer_id(inpoint)
+testfunc_struct_pointer_id.restype = tagpointptr
+testfunc_struct_pointer_id.argtypes = [tagpointptr]
-def py_create_point():
- p = tagpoint()
- p.x = 10
- p.y = 20
- return p.x + p.y
-
-def py_testfunc_POINTER(inpoint):
- point = tagpoint()
- oppoint = oppoint_type(point)
- res = testfunc_byval(inpoint,oppoint)
- return res, oppoint
-
-def py_testfunc_POINTER_dereference(inpoint):
- point = tagpoint()
- oppoint = oppoint_type(point)
- res = testfunc_byval(inpoint,oppoint)
- return res, oppoint.contents, oppoint[0]
-
-def py_test_mixed_memory_state( randomboolean ):
- if randomboolean:
- return tagpoint()
- else:
- return oppoint_type(tagpoint()).contents
-
-def py_test_simple_cint():
- return c_int(10)
-
-def py_test_simple_ctypes():
- return (
- c_char('a'),
- c_byte(1),
- c_ubyte(1),
- c_short(1),
- c_ushort(1),
- c_int(1),
- c_uint(1),
- c_long(1),
- c_ulong(1),
- c_longlong(1),
- c_ulonglong(1),
- c_float(1.0),
- c_double(1.0)
- )
-
-def py_test_simple_ctypes_non_const():
- a = 10
- return c_float( a + 10 )
-
-c_int_10 = ARRAY(c_int,10)
-c_int_p_test = POINTER(c_int)
-
-def py_test_annotate_array():
- return c_int_10()
-
-def py_test_annotate_array_content():
- my_array = c_int_10()
- my_array[0] = c_int(1)
- my_array[1] = 2
-
- return my_array[0]
-
-def py_test_annotate_pointer_content():
- # Never run this function!
- # See test_annotate_pointer_access_as_array_or_whatever
- # for the weird reasons why this gets annotated
- my_pointer = c_int_p_test(10)
- my_pointer[0] = c_int(1)
- my_pointer[1] = 2
-
- return my_pointer[0]
-
-def py_test_annotate_array_slice_content():
- my_array = c_int_10()
- #f#my_array[0:7] = c_int(1) * 7
- my_array[0:5] = range(5)
-
- return my_array[0:5]
-
-def py_test_annotate_array_content_variable_index():
- my_array = c_int_10()
- my_array[2] = 2
- sum = 0
- for idx in range(10):
- sum += my_array[idx]
-
- return sum
-
-def py_test_annotate_array_content_index_error_on_positive_index():
- my_array = c_int_10()
- return my_array[10]
-
-def py_test_annotate_array_content_index_error_on_negative_index():
- my_array = c_int_10()
- return my_array[-11]
-
-def py_test_specialize_struct():
- p = tagpoint()
- p.x = 1
- p.y = 2
- return p.x
-
-def _py_test_compile_struct( p, x, y ):
- p.x = x
- p.y = y
- return p
-
-def py_test_compile_struct( x, y ):
- return _py_test_compile_struct( tagpoint(), x, y ).x
-
-def py_test_compile_pointer( x, y ):
- return _py_test_compile_pointer( oppoint_type( tagpoint() ), x, y ).x
-
-def _py_test_compile_pointer( p, x, y ):
- s = p.contents
- s.x = x
- s.y = y
- return s
-
-class Test_rctypes:
-
- def test_simple(self):
- res = o_atoi('42')
- assert res == 42
-
- def test_annotate_simple(self):
- a = RPythonAnnotator()
- s = a.build_types(o_atoi, [str])
- # result should be an integer
- assert s.knowntype == int
-
- def x_test_specialize_simple(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(o_atoi, [str])
- # result should be an integer
- assert s.knowntype == int
- t.buildrtyper().specialize()
-
- if conftest.option.view:
- a.translator.view()
-
- def x_test_compile_simple(self):
- fn = compile(o_atoi, [str])
- res = fn("42")
- assert res == 42
-
-
-class Test_structure:
-
- def test_simple_as_extension_module(self):
- # Full path names follow because of strange behavior in the presence
- # of an __init__.py in this test directory. When there is an
- # __init__.py then the full path names appear in sys.modules
- import pypy.rpython.rctypes.test._rctypes_test as t0
- import pypy.rpython.rctypes.test._rctypes_test as t1
- assert t1 is t0
- assert "pypy.rpython.rctypes.test._rctypes_test" in sys.modules
-
- def test_simple(self):
- if sys.platform == "win32":
- dll = cdll_load("_rctypes_test.pyd")
- else:
- dll = cdll_load(str(thisdir.join("_rctypes_test.so")))
- in_point = tagpoint()
- in_point.x = 42
- in_point.y = 17
- out_point = tagpoint()
- assert in_point.x + in_point.y == dll._testfunc_byval(in_point, byref(out_point))
- assert out_point.x == 42
- assert out_point.y == 17
-
- def test_structure(self):
- in_point = tagpoint()
- in_point.x = 10
- in_point.y = 20
- res = py_testfunc_struct(in_point)
- assert res == 30
-
- def x_test_annotate_struct(self):
- a = RPythonAnnotator()
- s = a.build_types(py_testfunc_struct, [tagpoint])
- assert s.knowntype == int
-
- if conftest.option.view:
- a.translator.view()
-
- def x_test_annotate_struct2(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_struct_id, [tagpoint])
- assert s.knowntype == tagpoint
- assert s.memorystate == SomeCTypesObject.OWNSMEMORY
-
- def x_test_annotate_pointer_to_struct(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_struct_pointer_id, [oppoint_type])
- assert s.knowntype == oppoint_type
- assert s.memorystate == SomeCTypesObject.MEMORYALIAS
- return t
-
- def x_test_create_point(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_create_point,[])
- assert s.knowntype == int
-
- if conftest.option.view:
- a.translator.view()
-
- def x_test_annotate_byval(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_byval,[tagpoint])
- assert s.knowntype == tuple
- assert len(s.items) == 2
- assert s.items[0].knowntype == int
- assert s.items[1].knowntype == tagpoint
- assert s.items[1].memorystate == SomeCTypesObject.OWNSMEMORY
-
- def x_test_annotate_POINTER(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_POINTER,[tagpoint])
- assert s.knowntype == tuple
- assert len(s.items) == 2
- assert s.items[0].knowntype == int
- assert s.items[1].knowntype == POINTER(tagpoint)
- assert s.items[1].memorystate == SomeCTypesObject.OWNSMEMORY
- #d#t.view()
-
- def x_test_annotate_POINTER_dereference(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_POINTER_dereference, [tagpoint])
- assert s.knowntype == tuple
- assert len(s.items) == 3
- assert s.items[0].knowntype == int
- assert s.items[1].knowntype == tagpoint
- assert s.items[1].memorystate == SomeCTypesObject.OWNSMEMORY
- assert s.items[2].knowntype == tagpoint
- assert s.items[2].memorystate == SomeCTypesObject.OWNSMEMORY
- #d#t.view()
-
- def x_test_annotate_mixed_memorystate(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_test_mixed_memory_state, [int])
- #d#t.view()
- assert s.knowntype == tagpoint
- # This memory state will be supported in the future (#f#)
- # Obviously the test is wrong for now
- #f#assert s.memorystate == SomeCTypesObject.MIXEDMEMORYOWNERSHIP
- assert isinstance(s, SomeObject)
-
- def test_annotate_simple_cint(self):
- a = RPythonAnnotator()
- s = a.build_types(py_test_simple_cint,[])
- assert s.knowntype == c_int
-
- def test_annotate_simple_types(self):
- a = RPythonAnnotator()
- s = a.build_types(py_test_simple_ctypes,[])
- assert s.knowntype == tuple
- assert len(s.items) == 13
- assert s.items[0].knowntype == c_char
- assert s.items[1].knowntype == c_byte
- assert s.items[2].knowntype == c_ubyte
- assert s.items[3].knowntype == c_short
- assert s.items[4].knowntype == c_ushort
- assert s.items[5].knowntype == c_int
- assert s.items[6].knowntype == c_uint
- assert s.items[7].knowntype == c_long
- assert s.items[8].knowntype == c_ulong
- assert s.items[9].knowntype == c_longlong
- assert s.items[10].knowntype == c_ulonglong
- assert s.items[11].knowntype == c_float
- assert s.items[12].knowntype == c_double
-
- def test_annotate_simple_types_non_const(self):
- a = RPythonAnnotator()
- s = a.build_types(py_test_simple_ctypes_non_const,[])
- assert s.knowntype == c_float
-
- def x_test_specialize_struct(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_test_specialize_struct, [])
- # result should be an integer
- assert s.knowntype == int
- try:
- t.buildrtyper().specialize()
- finally:
- if conftest.option.view:
- t.view()
-
- def x_test_specialize_struct_1(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_test_compile_struct, [int, int])
- #d#t.view()
- try:
- t.buildrtyper().specialize()
- finally:
- #d#t.view()
- pass
-
- def x_test_specialize_pointer_to_struct(self):
- t = self.test_annotate_pointer_to_struct()
- t.buildrtyper().specialize()
- if conftest.option.view:
- t.view()
-
- def x_test_compile_pointer_to_struct(self):
- fn = compile( py_testfunc_struct_pointer_id, [ oppoint_type ] )
-
- def x_test_compile_struct(self):
- fn = compile( py_test_compile_struct, [ int, int ] )
- res = fn( 42, -42 )
- assert res == 42
-
- def x_test_specialize_POINTER_dereference(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types(py_testfunc_POINTER_dereference, [tagpoint])
- assert s.knowntype == tuple
- try:
- t.buildrtyper().specialize()
- finally:
- #d#t.view()
- pass
-
- def x_test_specialize_pointer(self):
- t = TranslationContext()
- a = t.buildannotator()
- s = a.build_types( py_test_compile_pointer, [ int, int ] )
- assert s.knowntype == int
- #d#t.view()
- t.buildrtyper().specialize()
- #d#t.view()
-
- def x_test_compile_pointer(self):
- fn = compile( py_test_compile_pointer, [ int, int ] )
- res = fn( -42, 42 )
- assert res == -42
+# XXX no test here so far
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rfunc.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rfunc.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rfunc.py Thu Apr 13 09:02:58 2006
@@ -1,14 +1,34 @@
import py
+import sys
+import pypy.rpython.rctypes.implementation
from pypy.annotation.annrpython import RPythonAnnotator
-from pypy.rpython.rctypes.test.test_rctypes import mylib
from pypy.rpython.test.test_llinterp import interpret
from pypy.translator.c.test.test_genc import compile
from pypy import conftest
from pypy.rpython.rstr import string_repr
from pypy.rpython.lltypesystem import lltype
+from ctypes import cdll
from ctypes import c_int, c_long, c_char_p, c_char
+# __________ the standard C library __________
+
+# LoadLibrary is deprecated in ctypes, this should be removed at some point
+if "load" in dir(cdll):
+ cdll_load = cdll.load
+else:
+ cdll_load = cdll.LoadLibrary
+
+if sys.platform == 'win32':
+ mylib = cdll_load('msvcrt.dll')
+elif sys.platform == 'linux2':
+ mylib = cdll_load('libc.so.6')
+elif sys.platform == 'darwin':
+ mylib = cdll.c
+else:
+ py.test.skip("don't know how to load the c lib for %s" %
+ sys.platform)
+# ____________________________________________
labs = mylib.labs
labs.restype = c_long
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rpointer.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rpointer.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rpointer.py Thu Apr 13 09:02:58 2006
@@ -3,14 +3,13 @@
"""
import py.test
+import pypy.rpython.rctypes.implementation
from pypy.translator.translator import TranslationContext
from pypy import conftest
from pypy.rpython.test.test_llinterp import interpret
from ctypes import c_int, c_float, POINTER, pointer
-import pypy.rpython.rctypes.implementation
-
class Test_annotation:
def test_simple(self):
res = c_int(42)
Modified: pypy/dist/pypy/rpython/rctypes/test/test_rprimitive.py
==============================================================================
--- pypy/dist/pypy/rpython/rctypes/test/test_rprimitive.py (original)
+++ pypy/dist/pypy/rpython/rctypes/test/test_rprimitive.py Thu Apr 13 09:02:58 2006
@@ -3,6 +3,7 @@
"""
import py.test
+import pypy.rpython.rctypes.implementation
from pypy.annotation.annrpython import RPythonAnnotator
from pypy.translator.translator import TranslationContext
from pypy.translator.c.test.test_genc import compile
More information about the Pypy-commit
mailing list