[pypy-svn] r10552 - pypy/dist/pypy/translator/genc

arigo at codespeak.net arigo at codespeak.net
Tue Apr 12 16:28:27 CEST 2005


Author: arigo
Date: Tue Apr 12 16:28:26 2005
New Revision: 10552

Added:
   pypy/dist/pypy/translator/genc/basetype.py
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/t_simple.py
   pypy/dist/pypy/translator/genc/func_template.h
   pypy/dist/pypy/translator/genc/functype.py
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/t_func.py
   pypy/dist/pypy/translator/genc/int_include.h
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/g_simple.h
   pypy/dist/pypy/translator/genc/inttype.py
   pypy/dist/pypy/translator/genc/none_include.h
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/g_simple.h
   pypy/dist/pypy/translator/genc/nonetype.py
   pypy/dist/pypy/translator/genc/pyobj_include.h
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/g_operation.h
   pypy/dist/pypy/translator/genc/pyobjtype.py
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/t_pyobj.py
   pypy/dist/pypy/translator/genc/tuple_include.h
      - copied, changed from r10541, pypy/dist/pypy/translator/genc/g_struct.h
   pypy/dist/pypy/translator/genc/tupletype.py
      - copied, changed from r10542, pypy/dist/pypy/translator/genc/t_tuple.py
Removed:
   pypy/dist/pypy/translator/genc/g_operation.h
   pypy/dist/pypy/translator/genc/g_simple.h
   pypy/dist/pypy/translator/genc/g_struct.h
   pypy/dist/pypy/translator/genc/t_func.py
   pypy/dist/pypy/translator/genc/t_pyobj.py
   pypy/dist/pypy/translator/genc/t_simple.py
   pypy/dist/pypy/translator/genc/t_tuple.py
Modified:
   pypy/dist/pypy/translator/genc/ctyper.py
   pypy/dist/pypy/translator/genc/funcdef.py
   pypy/dist/pypy/translator/genc/g_include.h
   pypy/dist/pypy/translator/genc/g_support.h
   pypy/dist/pypy/translator/genc/genc.py
Log:
Yet another reorganisation.  Looks a bit cleaner, with each type
defined in a file xxxtype.py with a corresponding xxx_include.h
(for generic operations) or xxx_template.h (with %s in it).



Copied: pypy/dist/pypy/translator/genc/basetype.py (from r10541, pypy/dist/pypy/translator/genc/t_simple.py)
==============================================================================
--- pypy/dist/pypy/translator/genc/t_simple.py	(original)
+++ pypy/dist/pypy/translator/genc/basetype.py	Tue Apr 12 16:28:26 2005
@@ -1,4 +1,4 @@
-from pypy.annotation.model import SomeInteger, SomePBC
+import os
 from pypy.objspace.flow.model import SpaceOperation
 from pypy.interpreter.miscutils import getthreadlocals
 
@@ -8,12 +8,6 @@
     def __init__(self, translator):
         self.translator = translator
 
-    def convert_to_obj(self, typer, v1, v2):
-        return [SpaceOperation("conv_to_obj", [v1], v2)]
-
-    def convert_from_obj(self, typer, v1, v2):
-        return [SpaceOperation("conv_from_obj", [v1], v2)]
-
     def debugname(self):
         return self.__class__.__name__
 
@@ -28,39 +22,10 @@
     def collect_globals(self, genc):
         return []
 
-    def cincref(self, expr):
-        return ''
-
-    def cdecref(self, expr):
-        return ''
-
-
-class CIntType(CType):
-    error_return  = '-1'
-    ctypetemplate = 'int %s'
-    s_annotation  = SomeInteger()
-
-    def nameof(self, v, debug=None):
-        return '%d' % (v,)
+    # --- interface for ../typer.py ---
 
-    def fn_conv_to_obj(self):
-        return 'PyInt_FromLong'
-
-    def fn_conv_from_obj(self):
-        return 'PyInt_AsLong'
-
-
-class CNoneType(CType):
-    error_return  = '-1'
-    ctypetemplate = 'int %s'
-    s_annotation  = SomePBC({None: True})
-
-    def nameof(self, v, debug=None):
-        assert v is None
-        return '0'
-
-    def fn_conv_to_obj(self):
-        return 'PyNone_FromInt'
+    def convert_to_obj(self, typer, v1, v2):
+        return [SpaceOperation("conv_to_obj", [v1], v2)]
 
-    def fn_conv_from_obj(self):
-        return 'PyNone_AsInt'
+    def convert_from_obj(self, typer, v1, v2):
+        return [SpaceOperation("conv_from_obj", [v1], v2)]

Modified: pypy/dist/pypy/translator/genc/ctyper.py
==============================================================================
--- pypy/dist/pypy/translator/genc/ctyper.py	(original)
+++ pypy/dist/pypy/translator/genc/ctyper.py	Tue Apr 12 16:28:26 2005
@@ -6,10 +6,11 @@
 from pypy.translator.typer import Specializer
 from pypy.objspace.flow.model import Constant, Variable, SpaceOperation
 from pypy.annotation.model import SomeInteger, SomePBC, SomeTuple
-from pypy.translator.genc.t_pyobj import CPyObjectType
-from pypy.translator.genc.t_simple import CIntType, CNoneType
-from pypy.translator.genc.t_func import CFuncPtrType
-from pypy.translator.genc.t_tuple import CTupleType
+from pypy.translator.genc.pyobjtype import CPyObjectType
+from pypy.translator.genc.inttype import CIntType
+from pypy.translator.genc.nonetype import CNoneType
+from pypy.translator.genc.functype import CFuncPtrType
+from pypy.translator.genc.tupletype import CTupleType
 import types
 from pypy.interpreter.pycode import CO_VARARGS
 

Added: pypy/dist/pypy/translator/genc/func_template.h
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/translator/genc/func_template.h	Tue Apr 12 16:28:26 2005
@@ -0,0 +1,7 @@
+
+/************************************************************/
+ /***  C header template: function pointer %(typename)s    ***/
+
+
+#define OP_INCREF_%(typename)s(x)    /* nothing */
+#define OP_DECREF_%(typename)s(x)    /* nothing */

Modified: pypy/dist/pypy/translator/genc/funcdef.py
==============================================================================
--- pypy/dist/pypy/translator/genc/funcdef.py	(original)
+++ pypy/dist/pypy/translator/genc/funcdef.py	Tue Apr 12 16:28:26 2005
@@ -6,9 +6,10 @@
 from pypy.objspace.flow.model import last_exception, last_exc_value
 from pypy.translator.simplify import simplify_graph
 from pypy.translator.unsimplify import remove_direct_loops
-from pypy.translator.genc.t_simple import CIntType, CNoneType
-from pypy.translator.genc.t_func import CFuncPtrType
-from pypy.translator.genc.t_pyobj import CBorrowedPyObjectType
+from pypy.translator.genc.inttype import CIntType
+from pypy.translator.genc.nonetype import CNoneType
+from pypy.translator.genc.functype import CFuncPtrType
+from pypy.translator.genc.pyobjtype import CBorrowedPyObjectType
 from pypy.interpreter.pycode import CO_VARARGS
 from pypy.tool.compile import compile2
 from types import FunctionType
@@ -77,10 +78,9 @@
         if USE_CALL_TRACE:
             declare_fast_args.insert(0, 'TRACE_ARGS')
         declare_fast_args = ', '.join(declare_fast_args) or 'void'
-        name_and_arguments = '%s(%s)' % (self.fast_name, declare_fast_args)
         ctret = self.ctypeof(graph.getreturnvar())
-        fast_function_header = 'static ' + (
-            ctret.ctypetemplate % (name_and_arguments,))
+        fast_function_header = 'static %s %s(%s)' % (
+            ctret.typename, self.fast_name, declare_fast_args)
 
         # store misc. information
         self.fast_function_header = fast_function_header
@@ -118,7 +118,7 @@
     def decl(self, v):
         assert isinstance(v, Variable)
         ct = self.ctypeof(v)
-        return ct.ctypetemplate % (self.localscope.localname(v.name),)
+        return '%s %s' % (ct.typename, self.localscope.localname(v.name))
 
     def expr(self, v):
         if isinstance(v, Variable):
@@ -275,7 +275,7 @@
             else:
                 convert_from_obj = ct.opname_conv_from_obj  # simple conv only!
                 convertedname = numberedname.replace('o', 'a')
-                print >> f, '\t%s;' % (ct.ctypetemplate % (convertedname,))
+                print >> f, '\t%s %s;' % (ct.typename, convertedname)
                 conversions.append('\tOP_%s(%s, %s, type_error)' % (
                     convert_from_obj.upper(), numberedname, convertedname))
                 # XXX successfully converted objects may need to be decrefed
@@ -288,7 +288,7 @@
             footer = None
         else:
             convert_to_obj = ct.opname_conv_to_obj  # simple conv only for now!
-            print >> f, '\t%s;' % (ct.ctypetemplate % ('aret',))
+            print >> f, '\t%s aret;' % (ct.typename,)
             putresultin = 'aret'
             footer = 'OP_%s(aret, oret, type_error)' % convert_to_obj.upper()
         print >> f
@@ -371,9 +371,7 @@
         
         # generate an incref for each input argument
         for a in self.graphargs:
-            line = self.ctypeof(a).cincref(self.expr(a))
-            if line:
-                print >> f, '\t' + line
+            print >> f, '\t' + self.cincref(a)
 
         # print the body
         for line in body:
@@ -417,14 +415,10 @@
                     ct1 = self.ctypeof(a1)
                     ct2 = self.ctypeof(a2)
                     assert ct1 == ct2
-                    line2 = ct1.cincref(self.expr(a2))
-                    if line2:
-                        line += '\t' + line2
+                    line += '\t' + self.cincref(a2)
                 yield line
             for v in has_ref:
-                line = self.ctypeof(v).cdecref(linklocalvars[v])
-                if line:
-                    yield line
+                yield self.cdecref(v, linklocalvars[v])
             yield 'goto block%d;' % blocknum[link.target]
 
         # collect all blocks
@@ -522,9 +516,7 @@
             while to_release:
                 v = to_release.pop()
                 if err_reachable:
-                    line = self.ctypeof(v).cdecref(self.expr(v))
-                    if line:
-                        yield line
+                    yield self.cdecref(v)
                 yield 'err%d_%d:' % (blocknum[block], len(to_release))
                 err_reachable = True
             if err_reachable:
@@ -577,25 +569,29 @@
         return '%s = %s(%s); if (PyErr_Occurred()) FAIL(%s)' % (
             r, args[0], ', '.join(args[1:]), err)
 
-    def OP_INCREF(self, op, err):
-        v = op.args[0]
-        return self.ctypeof(v).cincref(self.expr(v))
-
-    def OP_DECREF(self, op, err):
-        v = op.args[0]
-        return self.ctypeof(v).cdecref(self.expr(v))
-
     def OP_CONV_TO_OBJ(self, op, err):
         v = op.args[0]
-        convfnname = self.ctypeof(v).fn_conv_to_obj()
-        return '%s = %s(%s); if (PyErr_Occurred()) FAIL(%s)' % (
-            self.expr(op.result), convfnname, self.expr(v), err)
+        return '%s = CONV_TO_OBJ_%s(%s); if (PyErr_Occurred()) FAIL(%s)' % (
+            self.expr(op.result), self.ctypeof(v).typename, self.expr(v), err)
 
     def OP_CONV_FROM_OBJ(self, op, err):
         v = op.args[0]
-        convfnname = self.ctypeof(op.result).fn_conv_from_obj()
-        return '%s = %s(%s); if (PyErr_Occurred()) FAIL(%s)' % (
-            self.expr(op.result), convfnname, self.expr(v), err)
+        return '%s = CONV_FROM_OBJ_%s(%s); if (PyErr_Occurred()) FAIL(%s)' %(
+            self.expr(op.result), self.ctypeof(op.result).typename,
+            self.expr(v), err)
+
+    def OP_INCREF(self, op, err):
+        return self.cincref(op.args[0])
+
+    def OP_DECREF(self, op, err):
+        return self.cdecref(op.args[0])
+
+    def cincref(self, v):
+        return 'OP_INCREF_%s(%s)' % (self.ctypeof(v).typename, self.expr(v))
+
+    def cdecref(self, v, expr=None):
+        return 'OP_DECREF_%s(%s)' % (self.ctypeof(v).typename,
+                                     expr or self.expr(v))
 
 # ____________________________________________________________
 

Copied: pypy/dist/pypy/translator/genc/functype.py (from r10541, pypy/dist/pypy/translator/genc/t_func.py)
==============================================================================
--- pypy/dist/pypy/translator/genc/t_func.py	(original)
+++ pypy/dist/pypy/translator/genc/functype.py	Tue Apr 12 16:28:26 2005
@@ -1,23 +1,18 @@
-from pypy.translator.genc.t_simple import CType
+from __future__ import generators
+from pypy.translator.genc.basetype import CType
 
 
 class CFuncPtrType(CType):
     error_return = 'NULL'
 
+    Counter = 0
+
     def __init__(self, translator, argtypes, returntype):
         super(CFuncPtrType, self).__init__(translator)
         self.argtypes = argtypes
         self.returntype = returntype
-        # build a type declaration template matching the strange C syntax
-        # for function pointer types:
-        #    <returntype> (*<name_to_insert_here>) (<argument types>)
-        # which becomes funny when <returntype> itself is a complex type;
-        # in that case, the whole rest of the line, i.e. the "(*..)(...)",
-        # is what should be inserted into the returntype's "%s".
-        arglist = [ct.ctypetemplate % ('',) for ct in argtypes]
-        argtemplate = ', '.join(arglist or ['void'])
-        header = '(*%s)(' + argtemplate + ')'
-        self.ctypetemplate = returntype.ctypetemplate % (header,)
+        self.typename = 'funcptr%d' % CFuncPtrType.Counter
+        CFuncPtrType.Counter += 1
 
     def debugname(self):
         # a nice textual name for debugging...
@@ -27,3 +22,16 @@
 
     def nameof(self, func, debug=None):
         return self.genc().getfuncdef(func).fast_name
+
+    def init_globals(self, genc):
+        # build a type declaration template matching the C syntax
+        # for function pointer types:
+        #    <returntype> (*<name_to_insert_here>) (<argument types>)
+        arglist = [ct.typename for ct in self.argtypes]
+        argtemplate = ', '.join(arglist or ['void'])
+        yield "typedef %s (*%s) (%s);" % (self.returntype.typename,
+                                          self.typename,
+                                          argtemplate)
+        yield genc.loadincludefile('func_template.h') % {
+            'typename': self.typename,
+            }

Modified: pypy/dist/pypy/translator/genc/g_include.h
==============================================================================
--- pypy/dist/pypy/translator/genc/g_include.h	(original)
+++ pypy/dist/pypy/translator/genc/g_include.h	Tue Apr 12 16:28:26 2005
@@ -10,9 +10,11 @@
 #include "marshal.h"
 #include "eval.h"
 
-#include "g_operation.h"
-#include "g_simple.h"
-#include "g_struct.h"
 #include "g_trace.h"
 #include "g_support.h"
 #include "g_module.h"
+
+#include "int_include.h"
+#include "none_include.h"
+#include "pyobj_include.h"
+#include "tuple_include.h"

Deleted: /pypy/dist/pypy/translator/genc/g_operation.h
==============================================================================
--- /pypy/dist/pypy/translator/genc/g_operation.h	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,161 +0,0 @@
-
-/************************************************************/
- /***  C header subsection: untyped operations             ***/
-  /***  as OP_XXX() macros calling the CPython API          ***/
-
-
-#define op_bool(r,err,what) { \
-		int _retval = what; \
-		if (_retval < 0) { \
-			FAIL(err) \
-		} \
-		r = PyBool_FromLong(_retval); \
-	}
-
-#define op_richcmp(x,y,r,err,dir) \
-					if (!(r=PyObject_RichCompare(x,y,dir))) FAIL(err)
-#define OP_LT(x,y,r,err)  op_richcmp(x,y,r,err, Py_LT)
-#define OP_LE(x,y,r,err)  op_richcmp(x,y,r,err, Py_LE)
-#define OP_EQ(x,y,r,err)  op_richcmp(x,y,r,err, Py_EQ)
-#define OP_NE(x,y,r,err)  op_richcmp(x,y,r,err, Py_NE)
-#define OP_GT(x,y,r,err)  op_richcmp(x,y,r,err, Py_GT)
-#define OP_GE(x,y,r,err)  op_richcmp(x,y,r,err, Py_GE)
-
-#define OP_IS_(x,y,r,err) op_bool(r,err,(x == y))
-
-#define OP_IS_TRUE(x,r,err) op_bool(r,err,PyObject_IsTrue(x))
-
-#define OP_LEN(x,r,err) { \
-		int _retval = PyObject_Size(x); \
-		if (_retval < 0) { \
-			FAIL(err) \
-		} \
-		r = PyInt_FromLong(_retval); \
-	}
-#define OP_NEG(x,r,err)           if (!(r=PyNumber_Negative(x)))     FAIL(err)
-#define OP_POS(x,r,err)           if (!(r=PyNumber_Positive(x)))     FAIL(err)
-#define OP_INVERT(x,r,err)        if (!(r=PyNumber_Invert(x)))       FAIL(err)
-
-#define OP_ADD(x,y,r,err)         if (!(r=PyNumber_Add(x,y)))        FAIL(err)
-#define OP_SUB(x,y,r,err)         if (!(r=PyNumber_Subtract(x,y)))   FAIL(err)
-#define OP_MUL(x,y,r,err)         if (!(r=PyNumber_Multiply(x,y)))   FAIL(err)
-#define OP_TRUEDIV(x,y,r,err)     if (!(r=PyNumber_TrueDivide(x,y))) FAIL(err)
-#define OP_FLOORDIV(x,y,r,err)    if (!(r=PyNumber_FloorDivide(x,y)))FAIL(err)
-#define OP_DIV(x,y,r,err)         if (!(r=PyNumber_Divide(x,y)))     FAIL(err)
-#define OP_MOD(x,y,r,err)         if (!(r=PyNumber_Remainder(x,y)))  FAIL(err)
-#define OP_POW(x,y,z,r,err)       if (!(r=PyNumber_Power(x,y,z)))    FAIL(err)
-#define OP_LSHIFT(x,y,r,err)      if (!(r=PyNumber_Lshift(x,y)))     FAIL(err)
-#define OP_RSHIFT(x,y,r,err)      if (!(r=PyNumber_Rshift(x,y)))     FAIL(err)
-#define OP_AND_(x,y,r,err)        if (!(r=PyNumber_And(x,y)))        FAIL(err)
-#define OP_OR_(x,y,r,err)         if (!(r=PyNumber_Or(x,y)))         FAIL(err)
-#define OP_XOR(x,y,r,err)         if (!(r=PyNumber_Xor(x,y)))        FAIL(err)
-
-#define OP_INPLACE_ADD(x,y,r,err) if (!(r=PyNumber_InPlaceAdd(x,y)))           \
-								     FAIL(err)
-#define OP_INPLACE_SUB(x,y,r,err) if (!(r=PyNumber_InPlaceSubtract(x,y)))      \
-								     FAIL(err)
-#define OP_INPLACE_MUL(x,y,r,err) if (!(r=PyNumber_InPlaceMultiply(x,y)))      \
-								     FAIL(err)
-#define OP_INPLACE_TRUEDIV(x,y,r,err) if (!(r=PyNumber_InPlaceTrueDivide(x,y)))\
-								     FAIL(err)
-#define OP_INPLACE_FLOORDIV(x,y,r,err)if(!(r=PyNumber_InPlaceFloorDivide(x,y)))\
-								     FAIL(err)
-#define OP_INPLACE_DIV(x,y,r,err) if (!(r=PyNumber_InPlaceDivide(x,y)))        \
-								     FAIL(err)
-#define OP_INPLACE_MOD(x,y,r,err) if (!(r=PyNumber_InPlaceRemainder(x,y)))     \
-								     FAIL(err)
-#define OP_INPLACE_POW(x,y,r,err) if (!(r=PyNumber_InPlacePower(x,y,Py_None))) \
-								     FAIL(err)
-#define OP_INPLACE_LSHIFT(x,y,r,err) if (!(r=PyNumber_InPlaceLshift(x,y)))     \
-								     FAIL(err)
-#define OP_INPLACE_RSHIFT(x,y,r,err) if (!(r=PyNumber_InPlaceRshift(x,y)))     \
-								     FAIL(err)
-#define OP_INPLACE_AND(x,y,r,err)    if (!(r=PyNumber_InPlaceAnd(x,y)))        \
-								     FAIL(err)
-#define OP_INPLACE_OR(x,y,r,err)     if (!(r=PyNumber_InPlaceOr(x,y)))         \
-								     FAIL(err)
-#define OP_INPLACE_XOR(x,y,r,err)    if (!(r=PyNumber_InPlaceXor(x,y)))        \
-								     FAIL(err)
-
-#define OP_GETITEM(x,y,r,err)     if (!(r=PyObject_GetItem1(x,y)))   FAIL(err)
-#define OP_SETITEM(x,y,z,r,err)   if ((PyObject_SetItem1(x,y,z))<0)  FAIL(err) \
-				  r=Py_None; Py_INCREF(r);
-#define OP_DELITEM(x,y,r,err)     if ((PyObject_DelItem(x,y))<0)     FAIL(err) \
-				  r=Py_None; Py_INCREF(r);
-#define OP_CONTAINS(x,y,r,err)    op_bool(r,err,(PySequence_Contains(x,y)))
-
-#define OP_GETATTR(x,y,r,err)     if (!(r=PyObject_GetAttr(x,y)))    FAIL(err)
-#define OP_SETATTR(x,y,z,r,err)   if ((PyObject_SetAttr(x,y,z))<0)   FAIL(err) \
-				  r=Py_None; Py_INCREF(r);
-#define OP_DELATTR(x,y,r,err)     if ((PyObject_SetAttr(x,y,NULL))<0)FAIL(err) \
-				  r=Py_None; Py_INCREF(r);
-
-#define OP_NEWSLICE(x,y,z,r,err)  if (!(r=PySlice_New(x,y,z)))       FAIL(err)
-
-#define OP_GETSLICE(x,y,z,r,err)  {					\
-		PyObject *__yo = y, *__zo = z;				\
-		int __y = 0, __z = INT_MAX;				\
-		if (__yo == Py_None) __yo = NULL;			\
-		if (__zo == Py_None) __zo = NULL;			\
-		if (!_PyEval_SliceIndex(__yo, &__y) ||			\
-		    !_PyEval_SliceIndex(__zo, &__z) ||			\
-		    !(r=PySequence_GetSlice(x, __y, __z))) FAIL(err)	\
-	}
-
-#define OP_ALLOC_AND_SET(x,y,r,err) { \
-		/* XXX check for long/int overflow */ \
-		int __i, __x = PyInt_AsLong(x); \
-		if (PyErr_Occurred()) FAIL(err) \
-		if (!(r = PyList_New(__x))) FAIL(err) \
-		for (__i=0; __i<__x; __i++) { \
-			Py_INCREF(y); \
-			PyList_SET_ITEM(r, __i, y); \
-		} \
-	}
-
-#define OP_ITER(x,r,err)          if (!(r=PyObject_GetIter(x)))      FAIL(err)
-#define OP_NEXT(x,r,err)          if (!(r=PyIter_Next(x))) {                   \
-		if (!PyErr_Occurred()) PyErr_SetNone(PyExc_StopIteration);     \
-		FAIL(err)                                                      \
-	}
-
-#define OP_SIMPLE_CALL(args,r,err) if (!(r=PyObject_CallFunctionObjArgs args)) \
-					FAIL(err)
-#define OP_CALL_ARGS(args,r,err)   if (!(r=CallWithShape args))    FAIL(err)
-
-/* Needs to act like getattr(x, '__class__', type(x)) */
-#define OP_TYPE(x,r,err) { \
-		PyObject *o = x; \
-		if (PyInstance_Check(o)) { \
-			r = (PyObject*)(((PyInstanceObject*)o)->in_class); \
-		} else { \
-			r = (PyObject*)o->ob_type; \
-		} \
-		Py_INCREF(r); \
-	}
-
-/* Needs to act like instance(x,y) */
-#define OP_ISSUBTYPE(x,y,r,err)  \
-		op_bool(r,err,PyClass_IsSubclass(x, y))
-
-
-/*** misc ***/
-
-#define MOVE(x, y)             y = x;
-
-/*** operations with a variable number of arguments ***/
-
-#define OP_NEWLIST0(r,err)         if (!(r=PyList_New(0))) FAIL(err)
-#define OP_NEWLIST(args,r,err)     if (!(r=PyList_Pack args)) FAIL(err)
-#define OP_NEWDICT0(r,err)         if (!(r=PyDict_New())) FAIL(err)
-#define OP_NEWDICT(args,r,err)     if (!(r=PyDict_Pack args)) FAIL(err)
-#define OP_NEWTUPLE(args,r,err)    if (!(r=PyTuple_Pack args)) FAIL(err)
-
-/*** argument parsing ***/
-
-#define OP_DECODE_ARG(fname, pos, name, vargs, vkwds, r, err)	\
-	if (!(r=decode_arg(fname, pos, name, vargs, vkwds, NULL))) FAIL(err)
-#define OP_DECODE_ARG_DEF(fname, pos, name, vargs, vkwds, def, r, err)	\
-	if (!(r=decode_arg(fname, pos, name, vargs, vkwds, def))) FAIL(err)
-#define OP_CHECK_NO_MORE_ARG(fname, n, vargs, r, err)	\
-	if (check_no_more_arg(fname, n, vargs) < 0) FAIL(err)

Deleted: /pypy/dist/pypy/translator/genc/g_simple.h
==============================================================================
--- /pypy/dist/pypy/translator/genc/g_simple.h	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,31 +0,0 @@
-
-/************************************************************/
- /***  C header subsection: operations between ints        ***/
-
-
-static PyObject* PyNone_FromInt(int x)
-{
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static int PyNone_AsInt(PyObject* o)
-{
-	if (o != Py_None) {
-		PyErr_SetString(PyExc_TypeError, "None expected");
-		return -1;
-	}
-	return 0;
-}
-
-static PyObject* PyObject_SameObject(PyObject* obj)
-{
-	Py_INCREF(obj);
-	return obj;
-}
-
-
-#define OP_INT_IS_TRUE(x,r,err)   r = (x != 0);
-
-#define OP_INT_ADD(x,y,r,err)     r = x + y;
-#define OP_INT_SUB(x,y,r,err)     r = x - y;

Deleted: /pypy/dist/pypy/translator/genc/g_struct.h
==============================================================================
--- /pypy/dist/pypy/translator/genc/g_struct.h	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,12 +0,0 @@
-
-/************************************************************/
- /***  C header subsection: containers data structures     ***/
-
-
-#define OP_TUPLE_NEW(r,err)   /* r is a struct, can be left uninitialized */
-#define OP_TUPLE_GETITEM(s,i,r,err)    r = s.f##i;
-#define OP_TUPLE_SETITEM(s,i,o,r,err)  s.f##i = o;  r = 0;
-
-#define OP_PYTUPLE_GETITEM(t,i,r,err)  if (!(r=PyTuple_GetItem(t,i))) FAIL(err)
-#define OP_PYTUPLE_SETITEM(t,i,o,r,err) \
-		if (PyTuple_SetItem(t,i,o)) FAIL(err) else r = 0;

Modified: pypy/dist/pypy/translator/genc/g_support.h
==============================================================================
--- pypy/dist/pypy/translator/genc/g_support.h	(original)
+++ pypy/dist/pypy/translator/genc/g_support.h	Tue Apr 12 16:28:26 2005
@@ -3,10 +3,14 @@
  /***  C header subsection: support functions              ***/
 
 
+/*** misc ***/
+
 #if !defined(MIN)
 #define MIN(a,b) (((a)<(b))?(a):(b))
 #endif /* MIN */
 
+#define MOVE(x, y)             y = x;
+
 
 /* we need a subclass of 'builtin_function_or_method' which can be used
    as methods: builtin function objects that can be bound on instances */

Modified: pypy/dist/pypy/translator/genc/genc.py
==============================================================================
--- pypy/dist/pypy/translator/genc/genc.py	(original)
+++ pypy/dist/pypy/translator/genc/genc.py	Tue Apr 12 16:28:26 2005
@@ -9,7 +9,7 @@
 from pypy.translator.gensupp import uniquemodulename
 
 from pypy.translator.genc.funcdef import FunctionDef, USE_CALL_TRACE
-from pypy.translator.genc.t_pyobj import CPyObjectType
+from pypy.translator.genc.pyobjtype import CPyObjectType
 
 # ____________________________________________________________
 
@@ -130,10 +130,12 @@
     def gen_global_declarations(self):
         # collect more of the latercode between the functions,
         # and produce the corresponding global declarations
+        insert_first = []
         for ct in self.translator.ctlist:
             if ct not in self.ctypes_alreadyseen:
-                self.globaldecl += list(ct.init_globals(self))
+                insert_first += list(ct.init_globals(self))
                 self.ctypes_alreadyseen[ct] = True
+        self.globaldecl[:0] = insert_first
         for ct in self.translator.ctlist:
             self.globaldecl += list(ct.collect_globals(self))
         g = self.globaldecl
@@ -167,6 +169,14 @@
                 pass
             Variable.instances.clear()
 
+    def loadincludefile(basename):
+        filename = os.path.join(autopath.this_dir, basename)
+        f = open(filename, 'r')
+        content = f.read()
+        f.close()
+        return content
+    loadincludefile = staticmethod(loadincludefile)
+
 # ____________________________________________________________
 
     C_HEADER = '#include "g_include.h"\n'

Copied: pypy/dist/pypy/translator/genc/int_include.h (from r10541, pypy/dist/pypy/translator/genc/g_simple.h)
==============================================================================
--- pypy/dist/pypy/translator/genc/g_simple.h	(original)
+++ pypy/dist/pypy/translator/genc/int_include.h	Tue Apr 12 16:28:26 2005
@@ -3,27 +3,10 @@
  /***  C header subsection: operations between ints        ***/
 
 
-static PyObject* PyNone_FromInt(int x)
-{
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static int PyNone_AsInt(PyObject* o)
-{
-	if (o != Py_None) {
-		PyErr_SetString(PyExc_TypeError, "None expected");
-		return -1;
-	}
-	return 0;
-}
-
-static PyObject* PyObject_SameObject(PyObject* obj)
-{
-	Py_INCREF(obj);
-	return obj;
-}
-
+#define OP_INCREF_int(x)          /* nothing */
+#define OP_DECREF_int(x)          /* nothing */
+#define CONV_TO_OBJ_int           PyInt_FromLong
+#define CONV_FROM_OBJ_int         PyInt_AsLong
 
 #define OP_INT_IS_TRUE(x,r,err)   r = (x != 0);
 

Added: pypy/dist/pypy/translator/genc/inttype.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/translator/genc/inttype.py	Tue Apr 12 16:28:26 2005
@@ -0,0 +1,12 @@
+from __future__ import generators
+from pypy.annotation.model import SomeInteger
+from pypy.translator.genc.basetype import CType
+
+
+class CIntType(CType):
+    typename      = 'int'
+    error_return  = '-1'
+    s_annotation  = SomeInteger()
+
+    def nameof(self, v, debug=None):
+        return '%d' % (v,)

Copied: pypy/dist/pypy/translator/genc/none_include.h (from r10541, pypy/dist/pypy/translator/genc/g_simple.h)
==============================================================================
--- pypy/dist/pypy/translator/genc/g_simple.h	(original)
+++ pypy/dist/pypy/translator/genc/none_include.h	Tue Apr 12 16:28:26 2005
@@ -1,15 +1,16 @@
 
 /************************************************************/
- /***  C header subsection: operations between ints        ***/
+ /***  C header subsection: operations between Nones       ***/
 
+typedef int none;
+
+#define OP_INCREF_none(x)          /* nothing */
+#define OP_DECREF_none(x)          /* nothing */
 
-static PyObject* PyNone_FromInt(int x)
-{
-	Py_INCREF(Py_None);
-	return Py_None;
-}
 
-static int PyNone_AsInt(PyObject* o)
+#define CONV_TO_OBJ_none(x)    ((void)Py_INCREF(Py_None), Py_None)
+
+static none CONV_FROM_OBJ_none(PyObject* o)
 {
 	if (o != Py_None) {
 		PyErr_SetString(PyExc_TypeError, "None expected");
@@ -17,15 +18,3 @@
 	}
 	return 0;
 }
-
-static PyObject* PyObject_SameObject(PyObject* obj)
-{
-	Py_INCREF(obj);
-	return obj;
-}
-
-
-#define OP_INT_IS_TRUE(x,r,err)   r = (x != 0);
-
-#define OP_INT_ADD(x,y,r,err)     r = x + y;
-#define OP_INT_SUB(x,y,r,err)     r = x - y;

Added: pypy/dist/pypy/translator/genc/nonetype.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/translator/genc/nonetype.py	Tue Apr 12 16:28:26 2005
@@ -0,0 +1,13 @@
+from __future__ import generators
+from pypy.annotation.model import SomePBC
+from pypy.translator.genc.basetype import CType
+
+
+class CNoneType(CType):
+    typename      = 'none'
+    error_return  = '-1'
+    s_annotation  = SomePBC({None: True})
+
+    def nameof(self, v, debug=None):
+        assert v is None
+        return '0'

Copied: pypy/dist/pypy/translator/genc/pyobj_include.h (from r10541, pypy/dist/pypy/translator/genc/g_operation.h)
==============================================================================
--- pypy/dist/pypy/translator/genc/g_operation.h	(original)
+++ pypy/dist/pypy/translator/genc/pyobj_include.h	Tue Apr 12 16:28:26 2005
@@ -139,10 +139,6 @@
 		op_bool(r,err,PyClass_IsSubclass(x, y))
 
 
-/*** misc ***/
-
-#define MOVE(x, y)             y = x;
-
 /*** operations with a variable number of arguments ***/
 
 #define OP_NEWLIST0(r,err)         if (!(r=PyList_New(0))) FAIL(err)
@@ -159,3 +155,13 @@
 	if (!(r=decode_arg(fname, pos, name, vargs, vkwds, def))) FAIL(err)
 #define OP_CHECK_NO_MORE_ARG(fname, n, vargs, r, err)	\
 	if (check_no_more_arg(fname, n, vargs) < 0) FAIL(err)
+
+/*** conversions, reference counting ***/
+
+#define OP_INCREF_pyobj(o)          Py_INCREF(o);
+#define OP_DECREF_pyobj(o)          Py_DECREF(o);
+#define CONV_TO_OBJ_pyobj(o)        ((void)Py_INCREF(o), o)
+#define CONV_FROM_OBJ_pyobj(o)      ((void)Py_INCREF(o), o)
+
+#define OP_INCREF_borrowedpyobj(o)  /* nothing */
+#define OP_DECREF_borrowedpyobj(o)  /* nothing */

Copied: pypy/dist/pypy/translator/genc/pyobjtype.py (from r10541, pypy/dist/pypy/translator/genc/t_pyobj.py)
==============================================================================
--- pypy/dist/pypy/translator/genc/t_pyobj.py	(original)
+++ pypy/dist/pypy/translator/genc/pyobjtype.py	Tue Apr 12 16:28:26 2005
@@ -2,7 +2,7 @@
 import autopath, os, sys, __builtin__, marshal, zlib
 from pypy.objspace.flow.model import Variable, Constant
 from pypy.translator.gensupp import builtin_base, NameManager
-from pypy.translator.genc.t_simple import CType
+from pypy.translator.genc.basetype import CType
 from types import FunctionType, CodeType, InstanceType, ClassType
 
 from pypy.tool.rarithmetic import r_int, r_uint
@@ -14,7 +14,7 @@
     of Python objects to be 'pickled' as Python source code that will
     reconstruct them.
     """
-    ctypetemplate = 'PyObject *%s'
+    typename      = 'pyobj'
     error_return  = 'NULL'
 
     def __init__(self, translator):
@@ -51,12 +51,6 @@
         self.globalobjects = []
         self.debugstack = ()  # linked list of nested nameof()
 
-    def cincref(self, expr):
-        return 'Py_INCREF(%s);' % expr
-
-    def cdecref(self, expr):
-        return 'Py_DECREF(%s);' % expr
-
     def nameof(self, obj, debug=None):
         key = Constant(obj).key
         try:
@@ -429,6 +423,9 @@
     def later(self, gen):
         self.latercode.append((gen, self.debugstack))
 
+    def init_globals(self, genc):
+        yield 'typedef PyObject* pyobj;'
+
     def collect_globals(self, genc):
         while self.latercode:
             gen, self.debugstack = self.latercode.pop()
@@ -463,13 +460,10 @@
         del source
         return marshal.dumps(co)
 
-    def fn_conv_to_obj(self):
-        return "PyObject_SameObject"
-
-    def fn_conv_from_obj(self):
-        return "PyObject_SameObject"
-
 
 class CBorrowedPyObjectType(CType):
-    ctypetemplate = 'PyObject *%s'
+    typename      = 'borrowedpyobj'
     error_return  = 'NULL'
+
+    def init_globals(self, genc):
+        yield 'typedef PyObject* borrowedpyobj;'

Deleted: /pypy/dist/pypy/translator/genc/t_func.py
==============================================================================
--- /pypy/dist/pypy/translator/genc/t_func.py	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,29 +0,0 @@
-from pypy.translator.genc.t_simple import CType
-
-
-class CFuncPtrType(CType):
-    error_return = 'NULL'
-
-    def __init__(self, translator, argtypes, returntype):
-        super(CFuncPtrType, self).__init__(translator)
-        self.argtypes = argtypes
-        self.returntype = returntype
-        # build a type declaration template matching the strange C syntax
-        # for function pointer types:
-        #    <returntype> (*<name_to_insert_here>) (<argument types>)
-        # which becomes funny when <returntype> itself is a complex type;
-        # in that case, the whole rest of the line, i.e. the "(*..)(...)",
-        # is what should be inserted into the returntype's "%s".
-        arglist = [ct.ctypetemplate % ('',) for ct in argtypes]
-        argtemplate = ', '.join(arglist or ['void'])
-        header = '(*%s)(' + argtemplate + ')'
-        self.ctypetemplate = returntype.ctypetemplate % (header,)
-
-    def debugname(self):
-        # a nice textual name for debugging...
-        argnames = [ct.debugname() for ct in self.argtypes]
-        returnname = self.returntype.debugname()
-        return 'fn(%s) -> %s' % (', '.join(argnames), returnname)
-
-    def nameof(self, func, debug=None):
-        return self.genc().getfuncdef(func).fast_name

Deleted: /pypy/dist/pypy/translator/genc/t_pyobj.py
==============================================================================
--- /pypy/dist/pypy/translator/genc/t_pyobj.py	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,475 +0,0 @@
-from __future__ import generators
-import autopath, os, sys, __builtin__, marshal, zlib
-from pypy.objspace.flow.model import Variable, Constant
-from pypy.translator.gensupp import builtin_base, NameManager
-from pypy.translator.genc.t_simple import CType
-from types import FunctionType, CodeType, InstanceType, ClassType
-
-from pypy.tool.rarithmetic import r_int, r_uint
-
-
-class CPyObjectType(CType):
-    """The PyObject* C type.
-    This class contains all the nameof_xxx() methods that allow a wild variety
-    of Python objects to be 'pickled' as Python source code that will
-    reconstruct them.
-    """
-    ctypetemplate = 'PyObject *%s'
-    error_return  = 'NULL'
-
-    def __init__(self, translator):
-        super(CPyObjectType, self).__init__(translator)
-        self.namespace= NameManager()
-        # keywords cannot be reused.  This is the C99 draft's list.
-        self.namespace.make_reserved_names('''
-           auto      enum      restrict  unsigned
-           break     extern    return    void
-           case      float     short     volatile
-           char      for       signed    while
-           const     goto      sizeof    _Bool
-           continue  if        static    _Complex
-           default   inline    struct    _Imaginary
-           do        int       switch
-           double    long      typedef
-           else      register  union
-           ''')
-        self.cnames = {Constant(None).key:  'Py_None',
-                       Constant(False).key: 'Py_False',
-                       Constant(True).key:  'Py_True',
-                       }
-        self.initcode = [      # list of lines for the module's initxxx()
-            'import new, types, sys',
-            'Py_None  = None',
-            'Py_False = False',
-            'Py_True  = True',
-            ]
-
-        self.globaldecl = []
-        self.latercode = []    # list of generators generating extra lines
-                               #   for later in initxxx() -- for recursive
-                               #   objects
-        self.globalobjects = []
-        self.debugstack = ()  # linked list of nested nameof()
-
-    def cincref(self, expr):
-        return 'Py_INCREF(%s);' % expr
-
-    def cdecref(self, expr):
-        return 'Py_DECREF(%s);' % expr
-
-    def nameof(self, obj, debug=None):
-        key = Constant(obj).key
-        try:
-            return self.cnames[key]
-        except KeyError:
-            if debug:
-                stackentry = debug, obj
-            else:
-                stackentry = obj
-            self.debugstack = (self.debugstack, stackentry)
-            obj_builtin_base = builtin_base(obj)
-            if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base:
-                # assume it's a user defined thingy
-                name = self.nameof_instance(obj)
-            else:
-                for cls in type(obj).__mro__:
-                    meth = getattr(self,
-                                   'nameof_' + cls.__name__.replace(' ', ''),
-                                   None)
-                    if meth:
-                        break
-                else:
-                    raise Exception, "nameof(%r)" % (obj,)
-                name = meth(obj)
-            self.debugstack, x = self.debugstack
-            assert x is stackentry
-            self.cnames[key] = name
-            return name
-
-    def uniquename(self, basename):
-        name = self.namespace.uniquename(basename)
-        self.globalobjects.append(name)
-        self.globaldecl.append('static PyObject *%s;' % (name,))
-        return name
-
-    def initcode_python(self, name, pyexpr):
-        # generate init code that will evaluate the given Python expression
-        #self.initcode.append("print 'setting up', %r" % name)
-        self.initcode.append("%s = %s" % (name, pyexpr))
-
-    def nameof_object(self, value):
-        if type(value) is not object:
-            raise Exception, "nameof(%r)" % (value,)
-        name = self.uniquename('g_object')
-        self.initcode_python(name, "object()")
-        return name
-
-    def nameof_module(self, value):
-        assert value is os or not hasattr(value, "__file__") or \
-               not (value.__file__.endswith('.pyc') or
-                    value.__file__.endswith('.py') or
-                    value.__file__.endswith('.pyo')), \
-               "%r is not a builtin module (probably :)"%value
-        name = self.uniquename('mod%s'%value.__name__)
-        self.initcode_python(name, "__import__(%r)" % (value.__name__,))
-        return name
-        
-
-    def nameof_int(self, value):
-        if value >= 0:
-            name = 'gint_%d' % value
-        else:
-            name = 'gint_minus%d' % abs(value)
-        name = self.uniquename(name)
-        self.initcode_python(name, repr(value))
-        return name
-
-    def nameof_long(self, value):
-        if value >= 0:
-            name = 'glong%d' % value
-        else:
-            name = 'glong_minus%d' % abs(value)
-        name = self.uniquename(name)
-        self.initcode_python(name, repr(value))
-        return name
-
-    def nameof_float(self, value):
-        name = 'gfloat_%s' % value
-        name = (name.replace('-', 'minus')
-                    .replace('.', 'dot'))
-        name = self.uniquename(name)
-        self.initcode_python(name, repr(value))
-        return name
-
-    def nameof_str(self, value):
-        name = self.uniquename('gstr_' + value[:32])
-##        if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']:
-##            # non-printable string
-##            s = 'chr_%s' % name
-##            self.globaldecl.append('static char %s[] = { %s };' % (
-##                s, ', '.join(['%d' % ord(c) for c in value])))
-##        else:
-##            # printable string
-##            s = '"%s"' % value
-        self.initcode_python(name, repr(value))
-        return name
-
-    def skipped_function(self, func):
-        # debugging only!  Generates a placeholder for missing functions
-        # that raises an exception when called.
-        if self.translator.frozen:
-            warning = 'NOT GENERATING'
-        else:
-            warning = 'skipped'
-        printable_name = '(%s:%d) %s' % (
-            func.func_globals.get('__name__', '?'),
-            func.func_code.co_firstlineno,
-            func.__name__)
-        print warning, printable_name
-        name = self.uniquename('gskippedfunc_' + func.__name__)
-        self.initcode.append('def %s(*a,**k):' % name)
-        self.initcode.append('  raise NotImplementedError')
-        return name
-
-    def nameof_function(self, func, progress=['-\x08', '\\\x08',
-                                              '|\x08', '/\x08']):
-        funcdef = self.genc().getfuncdef(func)
-        if funcdef is None:
-            return self.skipped_function(func)
-        if not self.translator.frozen:
-            p = progress.pop(0)
-            sys.stderr.write(p)
-            progress.append(p)
-        return funcdef.get_globalobject()
-
-    def nameof_staticmethod(self, sm):
-        # XXX XXX XXXX
-        func = sm.__get__(42.5)
-        name = self.uniquename('gsm_' + func.__name__)
-        functionname = self.nameof(func)
-        self.initcode_python(name, 'staticmethod(%s)' % functionname)
-        return name
-
-    def nameof_instancemethod(self, meth):
-        if meth.im_self is None:
-            # no error checking here
-            return self.nameof(meth.im_func)
-        else:
-            ob = self.nameof(meth.im_self)
-            func = self.nameof(meth.im_func)
-            typ = self.nameof(meth.im_class)
-            name = self.uniquename('gmeth_'+meth.im_func.__name__)
-            self.initcode_python(name, 'new.instancemethod(%s, %s, %s)' % (
-                func, ob, typ))
-            return name
-
-    def should_translate_attr(self, pbc, attr):
-        ann = self.translator.annotator
-        if ann is None:
-            ignore = getattr(pbc.__class__, 'NOT_RPYTHON_ATTRIBUTES', [])
-            if attr in ignore:
-                return False
-            else:
-                return "probably"   # True
-        classdef = ann.getuserclasses().get(pbc.__class__)
-        if classdef and classdef.about_attribute(attr) is not None:
-            return True
-        return False
-
-    def nameof_instance(self, instance):
-        klass = instance.__class__
-        name = self.uniquename('ginst_' + klass.__name__)
-        cls = self.nameof(klass)
-        if hasattr(klass, '__base__'):
-            base_class = builtin_base(instance)
-            base = self.nameof(base_class)
-        else:
-            base_class = None
-            base = cls
-        def initinstance():
-            content = instance.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if self.should_translate_attr(instance, key):
-                    line = '%s.%s = %s' % (name, key, self.nameof(value))
-                    yield line
-        if hasattr(instance,'__reduce_ex__'):
-            import copy_reg
-            reduced = instance.__reduce_ex__()
-            assert reduced[0] is copy_reg._reconstructor,"not clever enough"
-            assert reduced[1][1] is base_class, "not clever enough for %r vs. %r" % (base_class, reduced)
-            state = reduced[1][2]
-        else:
-            state = None
-        self.initcode.append('if isinstance(%s, type):' % cls)
-        if state is not None:
-            self.initcode.append('    %s = %s.__new__(%s, %r)' % (name, base, cls, state))
-        else:
-            self.initcode.append('    %s = %s.__new__(%s)' % (name, base, cls))
-        self.initcode.append('else:')
-        self.initcode.append('    %s = new.instance(%s)' % (name, cls))
-        self.later(initinstance())
-        return name
-
-    def nameof_builtin_function_or_method(self, func):
-        if func.__self__ is None:
-            # builtin function
-            # where does it come from? Python2.2 doesn't have func.__module__
-            for modname, module in sys.modules.items():
-                if hasattr(module, '__file__'):
-                    if (module.__file__.endswith('.py') or
-                        module.__file__.endswith('.pyc') or
-                        module.__file__.endswith('.pyo')):
-                        continue    # skip non-builtin modules
-                if func is getattr(module, func.__name__, None):
-                    break
-            else:
-                raise Exception, '%r not found in any built-in module' % (func,)
-            name = self.uniquename('gbltin_' + func.__name__)
-            if modname == '__builtin__':
-                self.initcode_python(name, func.__name__)
-            else:
-                modname = self.nameof(module)
-                self.initcode_python(name, '%s.%s' % (modname, func.__name__))
-        else:
-            # builtin (bound) method
-            name = self.uniquename('gbltinmethod_' + func.__name__)
-            selfname = self.nameof(func.__self__)
-            self.initcode_python(name, '%s.%s' % (selfname, func.__name__))
-        return name
-
-    def nameof_classobj(self, cls):
-        if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'):
-            raise Exception, "%r should never be reached" % (cls,)
-
-        metaclass = "type"
-        if issubclass(cls, Exception):
-            if cls.__module__ == 'exceptions':
-                name = self.uniquename('gexc_' + cls.__name__)
-                self.initcode_python(name, cls.__name__)
-                return name
-            #else:
-            #    # exceptions must be old-style classes (grr!)
-            #    metaclass = "&PyClass_Type"
-        # For the moment, use old-style classes exactly when the
-        # pypy source uses old-style classes, to avoid strange problems.
-        if not isinstance(cls, type):
-            assert type(cls) is ClassType
-            metaclass = "types.ClassType"
-
-        name = self.uniquename('gcls_' + cls.__name__)
-        basenames = [self.nameof(base) for base in cls.__bases__]
-        def initclassobj():
-            content = cls.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if key.startswith('__'):
-                    if key in ['__module__', '__doc__', '__dict__',
-                               '__weakref__', '__repr__', '__metaclass__']:
-                        continue
-                    # XXX some __NAMES__ are important... nicer solution sought
-                    #raise Exception, "unexpected name %r in class %s"%(key, cls)
-                if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen:
-                    print value
-                    continue
-                if isinstance(value, classmethod) and value.__get__(cls).__doc__.lstrip().startswith("NOT_RPYTHON"):
-                    continue
-                if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen:
-                    print value
-                    continue
-                    
-                yield '%s.%s = %s' % (name, key, self.nameof(value))
-
-        baseargs = ", ".join(basenames)
-        if baseargs:
-            baseargs = '(%s)' % baseargs
-        self.initcode.append('class %s%s:' % (name, baseargs))
-        self.initcode.append('  __metaclass__ = %s' % metaclass)
-        self.later(initclassobj())
-        return name
-
-    nameof_class = nameof_classobj   # for Python 2.2
-
-    typename_mapping = {
-        InstanceType: 'types.InstanceType',
-        type(None):   'type(None)',
-        CodeType:     'types.CodeType',
-        type(sys):    'type(new)',
-
-        r_int:        'int',   # XXX
-        r_uint:       'int',   # XXX
-
-        # XXX more hacks
-        # type 'builtin_function_or_method':
-        type(len): 'type(len)',
-        # type 'method_descriptor':
-        type(list.append): 'type(list.append)',
-        # type 'wrapper_descriptor':
-        type(type(None).__repr__): 'type(type(None).__repr__)',
-        # type 'getset_descriptor':
-        type(type.__dict__['__dict__']): "type(type.__dict__['__dict__'])",
-        # type 'member_descriptor':
-        type(type.__dict__['__basicsize__']): "type(type.__dict__['__basicsize__'])",
-        }
-
-    def nameof_type(self, cls):
-        if cls.__module__ != '__builtin__':
-            return self.nameof_classobj(cls)   # user-defined type
-        name = self.uniquename('gtype_%s' % cls.__name__)
-        if getattr(__builtin__, cls.__name__, None) is cls:
-            expr = cls.__name__    # type available from __builtin__
-        else:
-            expr = self.typename_mapping[cls]
-        self.initcode_python(name, expr)
-        return name
-
-    def nameof_tuple(self, tup):
-        name = self.uniquename('g%dtuple' % len(tup))
-        args = [self.nameof(x) for x in tup]
-        args = ', '.join(args)
-        if args:
-            args += ','
-        self.initcode_python(name, '(%s)' % args)
-        return name
-
-    def nameof_list(self, lis):
-        name = self.uniquename('g%dlist' % len(lis))
-        def initlist():
-            for i in range(len(lis)):
-                item = self.nameof(lis[i])
-                yield '%s.append(%s)' % (name, item)
-        self.initcode_python(name, '[]')
-        self.later(initlist())
-        return name
-
-    def nameof_dict(self, dic):
-        assert dic is not __builtins__
-        assert '__builtins__' not in dic, 'Seems to be the globals of %s' % (
-            dic.get('__name__', '?'),)
-        name = self.uniquename('g%ddict' % len(dic))
-        def initdict():
-            for k in dic:
-                if type(k) is str:
-                    yield '%s[%r] = %s' % (name, k, self.nameof(dic[k]))
-                else:
-                    yield '%s[%s] = %s' % (name, self.nameof(k),
-                                           self.nameof(dic[k]))
-        self.initcode_python(name, '{}')
-        self.later(initdict())
-        return name
-
-    # strange prebuilt instances below, don't look too closely
-    # XXX oh well.
-    def nameof_member_descriptor(self, md):
-        name = self.uniquename('gdescriptor_%s_%s' % (
-            md.__objclass__.__name__, md.__name__))
-        cls = self.nameof(md.__objclass__)
-        self.initcode_python(name, '%s.__dict__[%r]' % (cls, md.__name__))
-        return name
-    nameof_getset_descriptor  = nameof_member_descriptor
-    nameof_method_descriptor  = nameof_member_descriptor
-    nameof_wrapper_descriptor = nameof_member_descriptor
-
-    def nameof_file(self, fil):
-        if fil is sys.stdin:
-            name = self.uniquename("gsys_stdin")
-            self.initcode_python(name, "sys.stdin")
-            return name
-        if fil is sys.stdout:
-            name = self.uniquename("gsys_stdout")
-            self.initcode_python(name, "sys.stdout")
-            return name
-        if fil is sys.stderr:
-            name = self.uniquename("gsys_stderr")
-            self.initcode_python(name, "sys.stderr")
-            return name
-        raise Exception, 'Cannot translate an already-open file: %r' % (fil,)
-
-
-    def later(self, gen):
-        self.latercode.append((gen, self.debugstack))
-
-    def collect_globals(self, genc):
-        while self.latercode:
-            gen, self.debugstack = self.latercode.pop()
-            #self.initcode.extend(gen) -- eats TypeError! bad CPython!
-            for line in gen:
-                self.initcode.append(line)
-            self.debugstack = ()
-        if genc.f2 is not None:
-            for line in self.initcode:
-                print >> genc.f2, line
-            del self.initcode[:]
-        result = self.globaldecl
-        self.globaldecl = []
-        return result
-
-    def getfrozenbytecode(self, genc):
-        if genc.f2 is not None:
-            genc.f2.seek(0)
-            self.initcode.insert(0, genc.f2.read())
-        self.initcode.append('')
-        source = '\n'.join(self.initcode)
-        del self.initcode[:]
-        co = compile(source, genc.modname, 'exec')
-        del source
-        small = zlib.compress(marshal.dumps(co))
-        source = """if 1:
-            import zlib, marshal
-            exec marshal.loads(zlib.decompress(%r))""" % small
-        # Python 2.2 SyntaxError without newline: Bug #501622
-        source += '\n'
-        co = compile(source, genc.modname, 'exec')
-        del source
-        return marshal.dumps(co)
-
-    def fn_conv_to_obj(self):
-        return "PyObject_SameObject"
-
-    def fn_conv_from_obj(self):
-        return "PyObject_SameObject"
-
-
-class CBorrowedPyObjectType(CType):
-    ctypetemplate = 'PyObject *%s'
-    error_return  = 'NULL'

Deleted: /pypy/dist/pypy/translator/genc/t_simple.py
==============================================================================
--- /pypy/dist/pypy/translator/genc/t_simple.py	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,66 +0,0 @@
-from pypy.annotation.model import SomeInteger, SomePBC
-from pypy.objspace.flow.model import SpaceOperation
-from pypy.interpreter.miscutils import getthreadlocals
-
-
-class CType(object):
-
-    def __init__(self, translator):
-        self.translator = translator
-
-    def convert_to_obj(self, typer, v1, v2):
-        return [SpaceOperation("conv_to_obj", [v1], v2)]
-
-    def convert_from_obj(self, typer, v1, v2):
-        return [SpaceOperation("conv_from_obj", [v1], v2)]
-
-    def debugname(self):
-        return self.__class__.__name__
-
-    def genc():
-        """A hack to get at the currently running GenC instance."""
-        return getthreadlocals().genc
-    genc = staticmethod(genc)
-
-    def init_globals(self, genc):
-        return []
-
-    def collect_globals(self, genc):
-        return []
-
-    def cincref(self, expr):
-        return ''
-
-    def cdecref(self, expr):
-        return ''
-
-
-class CIntType(CType):
-    error_return  = '-1'
-    ctypetemplate = 'int %s'
-    s_annotation  = SomeInteger()
-
-    def nameof(self, v, debug=None):
-        return '%d' % (v,)
-
-    def fn_conv_to_obj(self):
-        return 'PyInt_FromLong'
-
-    def fn_conv_from_obj(self):
-        return 'PyInt_AsLong'
-
-
-class CNoneType(CType):
-    error_return  = '-1'
-    ctypetemplate = 'int %s'
-    s_annotation  = SomePBC({None: True})
-
-    def nameof(self, v, debug=None):
-        assert v is None
-        return '0'
-
-    def fn_conv_to_obj(self):
-        return 'PyNone_FromInt'
-
-    def fn_conv_from_obj(self):
-        return 'PyNone_AsInt'

Deleted: /pypy/dist/pypy/translator/genc/t_tuple.py
==============================================================================
--- /pypy/dist/pypy/translator/genc/t_tuple.py	Tue Apr 12 16:28:26 2005
+++ (empty file)
@@ -1,146 +0,0 @@
-from __future__ import generators
-from pypy.translator.genc.t_simple import CType
-from pypy.objspace.flow.model import SpaceOperation, Constant, Variable
-
-
-class CTupleType(CType):
-
-    Counter = {}
-
-    def __init__(self, translator, itemtypes):
-        super(CTupleType, self).__init__(translator)
-        self.itemtypes = itemtypes
-        self.structname = 'struct tuple%d_%d' % (
-            len(itemtypes),
-            CTupleType.Counter.setdefault(len(itemtypes), 0))
-        CTupleType.Counter[len(itemtypes)] += 1
-        self.ctypetemplate = self.structname + ' %s'
-        self.error_return = self.structname.replace(' ', '_err_')
-        self.cnames = {}
-        self.globaldecl = []
-        self._conv_to_obj = None
-        self._conv_from_obj = None
-
-    def debugname(self):
-        # a nice textual name for debugging...
-        itemnames = [ct.debugname() for ct in self.itemtypes]
-        return 'tuple(%s)' % (', '.join(itemnames),)
-
-    def fieldnames(self):
-        return ['f%d' % i for i in range(len(self.itemtypes))]
-
-    def init_globals(self, genc):
-        yield '%s {' % self.structname
-        for ct, name in zip(self.itemtypes, self.fieldnames()):
-            yield '\t' + ct.ctypetemplate % (name,) + ';'
-        yield '};'
-        self.globaldecl.append(
-            '%s %s;  /* uninitialized */' % (self.structname,
-                                             self.error_return))
-
-    def collect_globals(self, genc):
-        result = self.globaldecl
-        self.globaldecl = []
-        return result
-
-    def cincref(self, expr):
-        result = []
-        for i in range(len(self.itemtypes)):
-            line = self.itemtypes[i].cincref('%s.f%d' % (expr, i))
-            if line:
-                result.append(line)
-        return ' '.join(result)
-
-    def cdecref(self, expr):
-        result = []
-        for i in range(len(self.itemtypes)):
-            line = self.itemtypes[i].cdecref('%s.f%d' % (expr, i))
-            if line:
-                result.append(line)
-        return '\t'.join(result)
-
-    def nameof(self, tup, debug=None):
-        try:
-            return self.cnames[tup]
-        except KeyError:
-            genc = self.genc()
-            name = genc.namespace.uniquename('gtup')
-            self.globaldecl.append('%s %s = {' % (self.structname, name))
-            lines = []
-            for x, ct in zip(tup, self.itemtypes):
-                lines.append('\t' + genc.nameofvalue(x, ct))
-            self.globaldecl.append(',\n'.join(lines))
-            self.globaldecl.append('};')
-            self.cnames[tup] = name
-            return name
-
-    def fn_conv_to_obj(self):
-        if self._conv_to_obj is None:
-            # build a function that converts from our custom struct
-            # format to a full-blown PyTupleObject.
-            self._conv_to_obj = self.structname.replace(' ', '_to_obj_')
-            self.globaldecl += [
-                "static PyObject* %s(%s tup)" % (self._conv_to_obj,
-                                                 self.structname),
-                "{",
-                "\tPyObject* o;",
-                "\tPyObject* result = PyTuple_New(%d);" % len(self.itemtypes),
-                "\tif (result == NULL) return NULL;",
-                ]
-            for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
-                self.globaldecl += [
-                    "\to = %s(tup.f%d);" % (ct.fn_conv_to_obj(), i),
-                    "\tif (o == NULL) goto err;",
-                    "\tPyTuple_SET_ITEM(result, %d, o);" % i,
-                    ]
-            self.globaldecl += [
-                "\treturn result;",
-                "   err:",
-                "\tPy_DECREF(result);",
-                "\treturn NULL;",
-                "}",
-                ]
-        return self._conv_to_obj
-
-    def fn_conv_from_obj(self):
-        if self._conv_from_obj is None:
-            # build a function that decodes a PyTupleObject and store it
-            # into our custom struct format.
-            self._conv_from_obj = self.structname.replace(' ', '_from_obj_')
-            self.globaldecl += [
-                "static %s %s(PyObject* obj)" % (self.structname,
-                                                 self._conv_from_obj),
-                "{",
-                "\t%s result;" % self.structname,
-                "\tif (PyTuple_Size(obj) != %d) { /* also if not a tuple */" %
-                    len(self.itemtypes),
-                "\t\tPyErr_SetString(PyExc_TypeError,",
-                '\t\t\t"tuple of length %d expected");' % len(self.itemtypes),
-                "\t\tgoto err0;",
-                "\t}",
-                ]
-            for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
-                self.globaldecl += [
-                    "\tresult.f%d = %s(PyTuple_GET_ITEM(obj, %d));" % (
-                        i, ct.fn_conv_from_obj(), i),
-                    "\tif (PyErr_Occurred()) goto err%d;" % i,
-                    ]
-            self.globaldecl += [
-                "\treturn result;",
-                ]
-            # errors may occur in the middle of the construction of the struct,
-            # we must decref only the fields that have been successfully built
-            # so far...
-            errlabels = range(len(self.itemtypes)) or [0]
-            errlabels.reverse()
-            for i in errlabels:
-                self.globaldecl.append("   err%d:" % i)
-                if i > 0:
-                    cdecref = self.itemtypes[i-1].cdecref('result.f%d' % (i-1))
-                    if cdecref:
-                        self.globaldecl.append('\t' + cdecref)
-            self.globaldecl += [
-                "\treturn %s;" % self.error_return,
-                "}",
-                ]
-        return self._conv_from_obj

Copied: pypy/dist/pypy/translator/genc/tuple_include.h (from r10541, pypy/dist/pypy/translator/genc/g_struct.h)
==============================================================================
--- pypy/dist/pypy/translator/genc/g_struct.h	(original)
+++ pypy/dist/pypy/translator/genc/tuple_include.h	Tue Apr 12 16:28:26 2005
@@ -1,12 +1,8 @@
 
 /************************************************************/
- /***  C header subsection: containers data structures     ***/
+ /***  C header subsection: operations involving tuples    ***/
 
 
 #define OP_TUPLE_NEW(r,err)   /* r is a struct, can be left uninitialized */
 #define OP_TUPLE_GETITEM(s,i,r,err)    r = s.f##i;
 #define OP_TUPLE_SETITEM(s,i,o,r,err)  s.f##i = o;  r = 0;
-
-#define OP_PYTUPLE_GETITEM(t,i,r,err)  if (!(r=PyTuple_GetItem(t,i))) FAIL(err)
-#define OP_PYTUPLE_SETITEM(t,i,o,r,err) \
-		if (PyTuple_SetItem(t,i,o)) FAIL(err) else r = 0;

Copied: pypy/dist/pypy/translator/genc/tupletype.py (from r10542, pypy/dist/pypy/translator/genc/t_tuple.py)
==============================================================================
--- pypy/dist/pypy/translator/genc/t_tuple.py	(original)
+++ pypy/dist/pypy/translator/genc/tupletype.py	Tue Apr 12 16:28:26 2005
@@ -1,5 +1,5 @@
 from __future__ import generators
-from pypy.translator.genc.t_simple import CType
+from pypy.translator.genc.basetype import CType
 from pypy.objspace.flow.model import SpaceOperation, Constant, Variable
 
 
@@ -10,62 +10,44 @@
     def __init__(self, translator, itemtypes):
         super(CTupleType, self).__init__(translator)
         self.itemtypes = itemtypes
-        self.structname = 'struct tuple%d_%d' % (
+        self.typename = 'tuple%d_%d' % (
             len(itemtypes),
             CTupleType.Counter.setdefault(len(itemtypes), 0))
         CTupleType.Counter[len(itemtypes)] += 1
-        self.ctypetemplate = self.structname + ' %s'
-        self.error_return = self.structname.replace(' ', '_err_')
+        self.error_return = 'err_' + self.typename
         self.cnames = {}
         self.globaldecl = []
-        self._conv_to_obj = None
-        self._conv_from_obj = None
 
     def debugname(self):
         # a nice textual name for debugging...
         itemnames = [ct.debugname() for ct in self.itemtypes]
         return 'tuple(%s)' % (', '.join(itemnames),)
 
-    def fieldnames(self):
-        return ['f%d' % i for i in range(len(self.itemtypes))]
-
     def init_globals(self, genc):
-        yield '%s {' % self.structname
-        for ct, name in zip(self.itemtypes, self.fieldnames()):
-            yield '\t' + ct.ctypetemplate % (name,) + ';'
-        yield '};'
+        yield 'typedef struct {'
+        for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
+            yield '\t%s f%d;' % (ct.typename, i)
+        yield '} %s;' % self.typename
         self.globaldecl.append(
-            '%s %s;  /* uninitialized */' % (self.structname,
+            '%s %s;  /* uninitialized */' % (self.typename,
                                              self.error_return))
+        self.generate_xxxref('INC')
+        self.generate_xxxref('DEC')
+        self.generate_conv_to_obj()
+        self.generate_conv_from_obj()
 
     def collect_globals(self, genc):
         result = self.globaldecl
         self.globaldecl = []
         return result
 
-    def cincref(self, expr):
-        result = []
-        for i in range(len(self.itemtypes)):
-            line = self.itemtypes[i].cincref('%s.f%d' % (expr, i))
-            if line:
-                result.append(line)
-        return ' '.join(result)
-
-    def cdecref(self, expr):
-        result = []
-        for i in range(len(self.itemtypes)):
-            line = self.itemtypes[i].cdecref('%s.f%d' % (expr, i))
-            if line:
-                result.append(line)
-        return '\t'.join(result)
-
     def nameof(self, tup, debug=None):
         try:
             return self.cnames[tup]
         except KeyError:
             genc = self.genc()
             name = genc.namespace.uniquename('gtup')
-            self.globaldecl.append('%s %s = {' % (self.structname, name))
+            self.globaldecl.append('%s %s = {' % (self.typename, name))
             lines = []
             for x, ct in zip(tup, self.itemtypes):
                 lines.append('\t' + genc.nameofvalue(x, ct))
@@ -74,73 +56,74 @@
             self.cnames[tup] = name
             return name
 
-    def fn_conv_to_obj(self):
-        if self._conv_to_obj is None:
-            # build a function that converts from our custom struct
-            # format to a full-blown PyTupleObject.
-            self._conv_to_obj = self.structname.replace(' ', '_to_obj_')
-            self.globaldecl += [
-                "static PyObject* %s(%s tup)" % (self._conv_to_obj,
-                                                 self.structname),
-                "{",
-                "\tPyObject* o;",
-                "\tPyObject* result = PyTuple_New(%d);" % len(self.itemtypes),
-                "\tif (result == NULL) return NULL;",
-                ]
-            for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
-                self.globaldecl += [
-                    "\to = %s(tup.f%d);" % (ct.fn_conv_to_obj(), i),
-                    "\tif (o == NULL) goto err;",
-                    "\tPyTuple_SET_ITEM(result, %d, o);" % i,
-                    ]
-            self.globaldecl += [
-                "\treturn result;",
-                "   err:",
-                "\tPy_DECREF(result);",
-                "\treturn NULL;",
-                "}",
-                ]
-        return self._conv_to_obj
-
-    def fn_conv_from_obj(self):
-        if self._conv_from_obj is None:
-            # build a function that decodes a PyTupleObject and store it
-            # into our custom struct format.
-            self._conv_from_obj = self.structname.replace(' ', '_from_obj_')
-            self.globaldecl += [
-                "static %s %s(PyObject* obj)" % (self.structname,
-                                                 self._conv_from_obj),
-                "{",
-                "\t%s result;" % self.structname,
-                "\tif (PyTuple_Size(obj) != %d) { /* also if not a tuple */" %
-                    len(self.itemtypes),
-                "\t\tPyErr_SetString(PyExc_TypeError,",
-                '\t\t\t"tuple of length %d expected");' % len(self.itemtypes),
-                "\t\tgoto err0;",
-                "\t}",
-                ]
-            for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
-                self.globaldecl += [
-                    "\tresult.f%d = %s(PyTuple_GET_ITEM(obj, %d));" % (
-                        i, ct.fn_conv_from_obj(), i),
-                    "\tif (PyErr_Occurred()) goto err%d;" % i,
-                    ]
+    def generate_xxxref(self, op):
+        self.globaldecl.append('#define OP_%sREF_%s(tup) \\' % (op,
+                                                                self.typename))
+        for i in range(len(self.itemtypes)):
+            self.globaldecl.append('\tOP_%sREF_%s(tup.f%d) \\' % (
+                op, self.itemtypes[i].typename, i))
+        self.globaldecl.append('\t/* end */')
+
+    def generate_conv_to_obj(self):
+        # build a function that converts from our custom struct
+        # format to a full-blown PyTupleObject.
+        self.globaldecl += [
+            "static PyObject* CONV_TO_OBJ_%s(%s tup)" % (self.typename,
+                                                         self.typename),
+            "{",
+            "\tPyObject* o;",
+            "\tPyObject* result = PyTuple_New(%d);" % len(self.itemtypes),
+            "\tif (result == NULL) return NULL;",
+            ]
+        for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
             self.globaldecl += [
-                "\treturn result;",
+                "\to = CONV_TO_OBJ_%s(tup.f%d);" % (ct.typename, i),
+                "\tif (o == NULL) goto err;",
+                "\tPyTuple_SET_ITEM(result, %d, o);" % i,
                 ]
-            # errors may occur in the middle of the construction of the struct,
-            # we must decref only the fields that have been successfully built
-            # so far...
-            errlabels = range(len(self.itemtypes)) or [0]
-            errlabels.reverse()
-            for i in errlabels:
-                self.globaldecl.append("   err%d:" % i)
-                if i > 0:
-                    cdecref = self.itemtypes[i-1].cdecref('result.f%d' % (i-1))
-                    if cdecref:
-                        self.globaldecl.append('\t' + cdecref)
+        self.globaldecl += [
+            "\treturn result;",
+            "   err:",
+            "\tPy_DECREF(result);",
+            "\treturn NULL;",
+            "}",
+            ]
+
+    def generate_conv_from_obj(self):
+        # build a function that decodes a PyTupleObject and store it
+        # into our custom struct format.
+        self.globaldecl += [
+            "static %s CONV_FROM_OBJ_%s(PyObject* obj)" % (self.typename,
+                                                           self.typename),
+            "{",
+            "\t%s result;" % self.typename,
+            "\tif (PyTuple_Size(obj) != %d) { /* also if not a tuple */" %
+                len(self.itemtypes),
+            "\t\tPyErr_SetString(PyExc_TypeError,",
+            '\t\t\t"tuple of length %d expected");' % len(self.itemtypes),
+            "\t\tgoto err0;",
+            "\t}",
+            ]
+        for i, ct in zip(range(len(self.itemtypes)), self.itemtypes):
             self.globaldecl += [
-                "\treturn %s;" % self.error_return,
-                "}",
+                "\tresult.f%d = CONV_FROM_OBJ_%s(PyTuple_GET_ITEM(obj, %d));" %
+                    (i, ct.typename, i),
+                "\tif (PyErr_Occurred()) goto err%d;" % i,
                 ]
-        return self._conv_from_obj
+        self.globaldecl += [
+            "\treturn result;",
+            ]
+        # errors may occur in the middle of the construction of the struct,
+        # we must decref only the fields that have been successfully built
+        # so far...
+        errlabels = range(len(self.itemtypes)) or [0]
+        errlabels.reverse()
+        for i in errlabels:
+            self.globaldecl.append("   err%d:" % i)
+            if i > 0:
+                self.globaldecl.append('\tOP_DECREF_%s(result.f%d)' % (
+                    self.itemtypes[i-1].typename, i-1))
+        self.globaldecl += [
+            "\treturn %s;" % self.error_return,
+            "}",
+            ]



More information about the Pypy-commit mailing list