static PyObject *
create_filter(PyObject *category, const char *action)
{
    static PyObject *ignore_str = NULL;
    static PyObject *error_str = NULL;
    static PyObject *default_str = NULL;
    static PyObject *always_str = NULL;
    PyObject *action_obj = NULL;
    PyObject *lineno, *result;

    if (!strcmp(action, "ignore")) {
        if (ignore_str == NULL) {
            ignore_str = PyUnicode_InternFromString("ignore");
            if (ignore_str == NULL)
                return NULL;
        }
        action_obj = ignore_str;
    }
    else if (!strcmp(action, "error")) {
        if (error_str == NULL) {
            error_str = PyUnicode_InternFromString("error");
            if (error_str == NULL)
                return NULL;
        }
        action_obj = error_str;
    }
    else if (!strcmp(action, "default")) {
        if (default_str == NULL) {
            default_str = PyUnicode_InternFromString("default");
            if (default_str == NULL)
                return NULL;
        }
        action_obj = default_str;
    }
    else if (!strcmp(action, "always")) {
        if (always_str == NULL) {
            always_str = PyUnicode_InternFromString("always");
            if (always_str == NULL)
                return NULL;
        }
        action_obj = always_str;
    }
    else {
        Py_FatalError("unknown action");
    }

    /* This assumes the line number is zero for now. */
    lineno = PyLong_FromLong(0);
    if (lineno == NULL)
        return NULL;
    result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
    Py_DECREF(lineno);
    return result;
}
Exemple #2
0
static PyObject *
bool_repr(PyObject *self)
{
    PyObject *s;

    if (self == Py_True)
        s = true_str ? true_str :
            (true_str = PyUnicode_InternFromString("True"));
    else
        s = false_str ? false_str :
            (false_str = PyUnicode_InternFromString("False"));
    Py_XINCREF(s);
    return s;
}
static PyObject *
math_trunc(PyObject *self, PyObject *number)
{
	static PyObject *trunc_str = NULL;
	PyObject *trunc;

	if (Py_TYPE(number)->tp_dict == NULL) {
		if (PyType_Ready(Py_TYPE(number)) < 0)
			return NULL;
	}

	if (trunc_str == NULL) {
		trunc_str = PyUnicode_InternFromString("__trunc__");
		if (trunc_str == NULL)
			return NULL;
	}

	trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
	if (trunc == NULL) {
		PyErr_Format(PyExc_TypeError,
			     "type %.100s doesn't define __trunc__ method",
			     Py_TYPE(number)->tp_name);
		return NULL;
	}
	return PyObject_CallFunctionObjArgs(trunc, number, NULL);
}
Exemple #4
0
PyObject *
PyDescr_NewAdaMethod(PyTypeObject *type, PyObject* cfunc, const char* name)
{
  if (!adamethod_descr_initialized) {
    adamethod_descr_initialized = 1;
    memcpy (&PyAdaMethodDescr_Type, &PyMethodDescr_Type, sizeof (PyTypeObject));
    PyAdaMethodDescr_Type.tp_basicsize = sizeof(PyAdaMethodDescrObject);
    PyAdaMethodDescr_Type.tp_descr_get = (descrgetfunc)adamethod_descr_get;
  }

  PyAdaMethodDescrObject *descr = (PyAdaMethodDescrObject*) PyType_GenericAlloc
    (&PyAdaMethodDescr_Type, 0);

  if (descr != NULL) {
    Py_XINCREF(type);
    PyDescr_TYPE(descr) = type;
    PyDescr_NAME(descr) = PyUnicode_InternFromString(name);
    if (PyDescr_NAME(descr) == NULL) {
      Py_DECREF(descr);
      descr = NULL;
    }
  }

  if (descr != NULL) {
    descr->cfunc = cfunc;
  }

  return (PyObject *)descr;
}
static PyObject *Proxy_getattro(
        ProxyObject *self, PyObject *name)
{
    PyObject *object = NULL;
    PyObject *result = NULL;

    static PyObject *getattr_str = NULL;

    object = PyObject_GenericGetAttr((PyObject *)self, name);

    if (object)
        return object;

    PyErr_Clear();

    if (!getattr_str) {
#if PY_MAJOR_VERSION >= 3
        getattr_str = PyUnicode_InternFromString("__getattr__");
#else
        getattr_str = PyString_InternFromString("__getattr__");
#endif
    }

    object = PyObject_GenericGetAttr((PyObject *)self, getattr_str);

    if (!object)
        return NULL;

    result = PyObject_CallFunctionObjArgs(object, name, NULL);

    Py_DECREF(object);

    return result;
}
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
    while (t->p) {
        #if PY_MAJOR_VERSION < 3
        if (t->is_unicode) {
            *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
        } else if (t->intern) {
            *t->p = PyString_InternFromString(t->s);
        } else {
            *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
        }
        #else  /* Python 3+ has unicode identifiers */
        if (t->is_unicode | t->is_str) {
            if (t->intern) {
                *t->p = PyUnicode_InternFromString(t->s);
            } else if (t->encoding) {
                *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
            } else {
                *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
            }
        } else {
            *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
        }
        #endif
        if (!*t->p)
            return -1;
        ++t;
    }
    return 0;
}
Exemple #7
0
int _PyFrame_Init()
{
    builtin_object = PyUnicode_InternFromString("__builtins__");
    if (builtin_object == NULL)
        return 0;
    return 1;
}
Exemple #8
0
PyObject *
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
{
    PyFunctionObject *op;
    PyObject *doc, *consts, *module;
    static PyObject *__name__ = NULL;

    if (__name__ == NULL) {
        __name__ = PyUnicode_InternFromString("__name__");
        if (__name__ == NULL)
            return NULL;
    }

    op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
    if (op == NULL)
        return NULL;

    op->func_weakreflist = NULL;
    Py_INCREF(code);
    op->func_code = code;
    Py_INCREF(globals);
    op->func_globals = globals;
    op->func_name = ((PyCodeObject *)code)->co_name;
    Py_INCREF(op->func_name);
    op->func_defaults = NULL; /* No default arguments */
    op->func_kwdefaults = NULL; /* No keyword only defaults */
    op->func_closure = NULL;

    consts = ((PyCodeObject *)code)->co_consts;
    if (PyTuple_Size(consts) >= 1) {
        doc = PyTuple_GetItem(consts, 0);
        if (!PyUnicode_Check(doc))
            doc = Py_None;
    }
    else
        doc = Py_None;
    Py_INCREF(doc);
    op->func_doc = doc;

    op->func_dict = NULL;
    op->func_module = NULL;
    op->func_annotations = NULL;

    /* __module__: If module name is in globals, use it.
       Otherwise, use None. */
    module = PyDict_GetItem(globals, __name__);
    if (module) {
        Py_INCREF(module);
        op->func_module = module;
    }
    if (qualname)
        op->func_qualname = qualname;
    else
        op->func_qualname = op->func_name;
    Py_INCREF(op->func_qualname);

    _PyObject_GC_TRACK(op);
    return (PyObject *)op;
}
long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
	PyObject *mod, *func, *result;
	long retval;
	static PyObject *context;

	if (context == NULL)
		context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");

	mod = PyImport_ImportModuleNoBlock("ctypes");
	if (!mod) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		/* There has been a warning before about this already */
		return E_FAIL;
	}

	func = PyObject_GetAttrString(mod, "DllGetClassObject");
	Py_DECREF(mod);
	if (!func) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		return E_FAIL;
	}

	{
		PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
		PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
		PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
		if (!py_rclsid || !py_riid || !py_ppv) {
			Py_XDECREF(py_rclsid);
			Py_XDECREF(py_riid);
			Py_XDECREF(py_ppv);
			Py_DECREF(func);
			PyErr_WriteUnraisable(context ? context : Py_None);
			return E_FAIL;
		}
		result = PyObject_CallFunctionObjArgs(func,
						      py_rclsid,
						      py_riid,
						      py_ppv,
						      NULL);
		Py_DECREF(py_rclsid);
		Py_DECREF(py_riid);
		Py_DECREF(py_ppv);
	}
	Py_DECREF(func);
	if (!result) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		return E_FAIL;
	}

	retval = PyLong_AsLong(result);
	if (PyErr_Occurred()) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		retval = E_FAIL;
	}
	Py_DECREF(result);
	return retval;
}
Exemple #10
0
static PyObject *
instancemethod_get_doc(PyObject *self, void *context)
{
    static PyObject *docstr;
    if (docstr == NULL) {
        docstr = PyUnicode_InternFromString("__doc__");
        if (docstr == NULL)
            return NULL;
    }
    return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr);
}
    static PyObject* function_get_name(PyObject* op, void*)
    {
        function* f = downcast<function>(op);
        if (f->name().is_none())
#if PY_VERSION_HEX >= 0x03000000
            return PyUnicode_InternFromString("<unnamed Boost.Python function>");
#else
            return PyString_InternFromString("<unnamed Boost.Python function>");
#endif
        else
            return python::incref(f->name().ptr());
Exemple #12
0
//-------------------------------------------------------------------------------------
PyObject* PropertyDescription::onSetValue(PyObject* parentObj, PyObject* value)
{
	PyObject* pyName = PyUnicode_InternFromString(getName());
	int result = PyObject_GenericSetAttr(parentObj, pyName, value);
	Py_DECREF(pyName);
	
	if(result == -1)
		return NULL;

	return value;	
}
Exemple #13
0
static PyObject *
method_get_doc(PyMethodObject *im, void *context)
{
    static PyObject *docstr;
    if (docstr == NULL) {
        docstr= PyUnicode_InternFromString("__doc__");
        if (docstr == NULL)
            return NULL;
    }
    return PyObject_GetAttr(im->im_func, docstr);
}
Exemple #14
0
/* Module */
PyObject *
init_fibers(void)
{
    PyObject *fibers;

    /* Main module */
#if PY_MAJOR_VERSION >= 3
    fibers = PyModule_Create(&fibers_module);
#else
    fibers = Py_InitModule("fibers._cfibers", fibers_methods);
#endif

    /* keys for per-thread dictionary */
#if PY_MAJOR_VERSION >= 3
    main_fiber_key = PyUnicode_InternFromString("__fibers_main");
    current_fiber_key = PyUnicode_InternFromString("__fibers_current");
#else
    main_fiber_key = PyString_InternFromString("__fibers_main");
    current_fiber_key = PyString_InternFromString("__fibers_current");
#endif
    if ((current_fiber_key == NULL) || (main_fiber_key == NULL)) {
        goto fail;
    }

    /* Exceptions */
    PyExc_FiberError = PyErr_NewException("fibers._cfibers.error", NULL, NULL);
    MyPyModule_AddType(fibers, "error", (PyTypeObject *)PyExc_FiberError);

    /* Types */
    MyPyModule_AddType(fibers, "Fiber", &FiberType);

    return fibers;

fail:
#if PY_MAJOR_VERSION >= 3
    Py_DECREF(fibers);
#endif
    return NULL;

}
static PyObject *
__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op)
{
    if (op->func_name == NULL) {
#if PY_MAJOR_VERSION >= 3
        op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name);
#else
        op->func_name = PyString_InternFromString(op->func.m_ml->ml_name);
#endif
    }
    Py_INCREF(op->func_name);
    return op->func_name;
}
Exemple #16
0
FunctionParameter::FunctionParameter(const std::string& fmt, bool keyword_only)
  : optional(false)
  , allow_none(false)
  , keyword_only(keyword_only)
  , size(0)
  , default_scalar(0)
{
  auto space = fmt.find(' ');
  if (space == std::string::npos) {
    throw std::runtime_error("FunctionParameter(): missing type: " + fmt);
  }

  auto type_str = fmt.substr(0, space);

  auto question = type_str.find('?');
  if (question != std::string::npos) {
    allow_none = true;
    type_str = type_str.substr(0, question);
  }

  // Parse and remove brackets from type_str
  auto bracket = type_str.find('[');
  if (bracket != std::string::npos) {
    auto size_str = type_str.substr(bracket + 1, type_str.length() - bracket - 2);
    size = atoi(size_str.c_str());
    type_str = type_str.substr(0, bracket);
  }

  auto name_str = fmt.substr(space + 1);
  auto it = type_map.find(type_str);
  if (it == type_map.end()) {
    throw std::runtime_error("FunctionParameter(): invalid type string: " + type_str);
  }
  type_ = it->second;

  auto eq = name_str.find('=');
  if (eq != std::string::npos) {
    name = name_str.substr(0, eq);
    optional = true;
    set_default_str(name_str.substr(eq + 1));
  } else {
    name = name_str;
  }
#if PY_MAJOR_VERSION == 2
  python_name = PyString_InternFromString(name.c_str());
#else
  python_name = PyUnicode_InternFromString(name.c_str());
#endif
}
static PyObject * math_floor(PyObject *self, PyObject *number) {
	static PyObject *floor_str = NULL;
	PyObject *method;

	if (floor_str == NULL) {
		floor_str = PyUnicode_InternFromString("__floor__");
		if (floor_str == NULL)
			return NULL;
	}

	method = _PyType_Lookup(Py_TYPE(number), floor_str);
	if (method == NULL)
        	return math_1_to_int(number, floor, 0);
	else
		return PyObject_CallFunction(method, "O", number);
}
Exemple #18
0
/*
 * PyArray_GetAttrString_SuppressException:
 *
 * Stripped down version of PyObject_GetAttrString,
 * avoids lookups for None, tuple, and List objects,
 * and doesn't create a PyErr since this code ignores it.
 *
 * This can be much faster then PyObject_GetAttrString where
 * exceptions are not used by caller.
 *
 * 'obj' is the object to search for attribute.
 *
 * 'name' is the attribute to search for.
 *
 * Returns attribute value on success, 0 on failure.
 */
PyObject *
PyArray_GetAttrString_SuppressException(PyObject *obj, char *name)
{
    PyTypeObject *tp = Py_TYPE(obj);
    PyObject *res = (PyObject *)NULL;

    /* We do not need to check for special attributes on trivial types */
    if (obj == Py_None ||
            /* Basic number types */
#if !defined(NPY_PY3K)
            PyInt_CheckExact(obj) ||
#endif
            PyLong_CheckExact(obj) ||
            PyFloat_CheckExact(obj) ||
            /* Basic sequence types */
            PyList_CheckExact(obj) ||
            PyTuple_CheckExact(obj)) {
        return NULL;
    }

    /* Attribute referenced by (char *)name */
    if (tp->tp_getattr != NULL) {
        res = (*tp->tp_getattr)(obj, name);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    /* Attribute referenced by (PyObject *)name */
    else if (tp->tp_getattro != NULL) {
#if defined(NPY_PY3K)
        PyObject *w = PyUnicode_InternFromString(name);
#else
        PyObject *w = PyString_InternFromString(name);
#endif
        if (w == NULL) {
            return (PyObject *)NULL;
        }
        res = (*tp->tp_getattro)(obj, w);
        Py_DECREF(w);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    return res;
}
Exemple #19
0
/*
   Returns a new reference.
   A NULL return value can mean false or an error.
*/
static PyObject *
get_warnings_attr(const char *attr, int try_import)
{
    static PyObject *warnings_str = NULL;
    PyObject *all_modules;
    PyObject *warnings_module, *obj;

    if (warnings_str == NULL) {
        warnings_str = PyUnicode_InternFromString("warnings");
        if (warnings_str == NULL)
            return NULL;
    }

    /* don't try to import after the start of the Python finallization */
    if (try_import && _Py_Finalizing == NULL) {
        warnings_module = PyImport_Import(warnings_str);
        if (warnings_module == NULL) {
            /* Fallback to the C implementation if we cannot get
               the Python implementation */
            PyErr_Clear();
            return NULL;
        }
    }
    else {
        all_modules = PyImport_GetModuleDict();

        warnings_module = PyDict_GetItem(all_modules, warnings_str);
        if (warnings_module == NULL)
            return NULL;

        Py_INCREF(warnings_module);
    }

    if (!PyObject_HasAttrString(warnings_module, attr)) {
        Py_DECREF(warnings_module);
        return NULL;
    }

    obj = PyObject_GetAttrString(warnings_module, attr);
    Py_DECREF(warnings_module);
    return obj;
}
Exemple #20
0
/* Module */
PyObject *
init_fibers(void)
{
    PyObject *fibers;

    /* Main module */
#if PY_MAJOR_VERSION >= 3
    fibers = PyModule_Create(&fibers_module);
#else
    fibers = Py_InitModule("fibers", fibers_methods);
#endif

    /* keys for per-thread dictionary */
#if PY_MAJOR_VERSION >= 3
    current_fiber_key = PyUnicode_InternFromString("__fibers_current");
#else
    current_fiber_key = PyString_InternFromString("__fibers_current");
#endif
    if (current_fiber_key == NULL) {
        goto fail;
    }

    /* Exceptions */
    PyExc_FiberError = PyErr_NewException("fibers.error", NULL, NULL);
    MyPyModule_AddType(fibers, "error", (PyTypeObject *)PyExc_FiberError);

    /* Types */
    MyPyModule_AddType(fibers, "Fiber", &FiberType);

    /* Module version (the MODULE_VERSION macro is defined by setup.py) */
    PyModule_AddStringConstant(fibers, "__version__", STRINGIFY(MODULE_VERSION));

    return fibers;

fail:
#if PY_MAJOR_VERSION >= 3
    Py_DECREF(fibers);
#endif
    return NULL;

}
Exemple #21
0
static PlanarBBoxObject *
get_bounding_box(PyObject *shape)
{
    PlanarBBoxObject *bbox;

    static PyObject *bounding_box_str = NULL;
    if (bounding_box_str == NULL) {
        bounding_box_str = PyUnicode_InternFromString("bounding_box");
		if (bounding_box_str == NULL) {
			return NULL;
		}
	}
    bbox = (PlanarBBoxObject *)PyObject_GetAttr(shape, bounding_box_str);
    if (bbox != NULL && !PlanarBBox_Check(bbox)) {
        PyErr_SetString(PyExc_TypeError,
            "Shape returned incompatible object "
            "for attribute bounding_box.");
        Py_CLEAR(bbox);
    }
    return bbox;
}
long Call_CanUnloadNow(void)
{
	PyObject *mod, *func, *result;
	long retval;
	static PyObject *context;

	if (context == NULL)
		context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");

	mod = PyImport_ImportModuleNoBlock("ctypes");
	if (!mod) {
/*		OutputDebugString("Could not import ctypes"); */
		/* We assume that this error can only occur when shutting
		   down, so we silently ignore it */
		PyErr_Clear();
		return E_FAIL;
	}
	/* Other errors cannot be raised, but are printed to stderr */
	func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
	Py_DECREF(mod);
	if (!func) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		return E_FAIL;
	}

	result = PyObject_CallFunction(func, NULL);
	Py_DECREF(func);
	if (!result) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		return E_FAIL;
	}

	retval = PyLong_AsLong(result);
	if (PyErr_Occurred()) {
		PyErr_WriteUnraisable(context ? context : Py_None);
		retval = E_FAIL;
	}
	Py_DECREF(result);
	return retval;
}
Exemple #23
0
/*
  This function creates and returns a thread-local Python object that has
  space to store two integer error numbers; once created the Python object is
  kept alive in the thread state dictionary as long as the thread itself.
*/
PyObject *
_ctypes_get_errobj(int **pspace)
{
	PyObject *dict = PyThreadState_GetDict();
	PyObject *errobj;
	static PyObject *error_object_name;
	if (dict == 0) {
		PyErr_SetString(PyExc_RuntimeError,
				"cannot get thread state");
		return NULL;
	}
	if (error_object_name == NULL) {
		error_object_name = PyUnicode_InternFromString("ctypes.error_object");
		if (error_object_name == NULL)
			return NULL;
	}
	errobj = PyDict_GetItem(dict, error_object_name);
	if (errobj)
		Py_INCREF(errobj);
	else {
		void *space = PyMem_Malloc(sizeof(int) * 2);
		if (space == NULL)
			return NULL;
		memset(space, 0, sizeof(int) * 2);
		errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
		if (errobj == NULL)
			return NULL;
		if (-1 == PyDict_SetItem(dict, error_object_name,
					 errobj)) {
			Py_DECREF(errobj);
			return NULL;
		}
	}
	*pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
	return errobj;
}
Exemple #24
0
/*
   Returns a new reference.
   A NULL return value can mean false or an error.
*/
static PyObject *
get_warnings_attr(const char *attr)
{
    static PyObject *warnings_str = NULL;
    PyObject *all_modules;
    PyObject *warnings_module;
    int result;

    if (warnings_str == NULL) {
        warnings_str = PyUnicode_InternFromString("warnings");
        if (warnings_str == NULL)
            return NULL;
    }

    all_modules = PyImport_GetModuleDict();
    result = PyDict_Contains(all_modules, warnings_str);
    if (result == -1 || result == 0)
        return NULL;

    warnings_module = PyDict_GetItem(all_modules, warnings_str);
    if (!PyObject_HasAttrString(warnings_module, attr))
            return NULL;
    return PyObject_GetAttrString(warnings_module, attr);
}
Exemple #25
0
/*
 * PyArray_GetAttrString_SuppressException:
 *
 * Stripped down version of PyObject_GetAttrString,
 * avoids lookups for None, tuple, and List objects,
 * and doesn't create a PyErr since this code ignores it.
 *
 * This can be much faster then PyObject_GetAttrString where
 * exceptions are not used by caller.
 *
 * 'obj' is the object to search for attribute.
 *
 * 'name' is the attribute to search for.
 *
 * Returns attribute value on success, 0 on failure.
 */
PyObject *
PyArray_GetAttrString_SuppressException(PyObject *obj, char *name)
{
    PyTypeObject *tp = Py_TYPE(obj);
    PyObject *res = (PyObject *)NULL;

    /* We do not need to check for special attributes on trivial types */
    if (_is_basic_python_type(obj)) {
        return NULL;
    }

    /* Attribute referenced by (char *)name */
    if (tp->tp_getattr != NULL) {
        res = (*tp->tp_getattr)(obj, name);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    /* Attribute referenced by (PyObject *)name */
    else if (tp->tp_getattro != NULL) {
#if defined(NPY_PY3K)
        PyObject *w = PyUnicode_InternFromString(name);
#else
        PyObject *w = PyString_InternFromString(name);
#endif
        if (w == NULL) {
            return (PyObject *)NULL;
        }
        res = (*tp->tp_getattro)(obj, w);
        Py_DECREF(w);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    return res;
}
PyMODINIT_FUNC
PyInit__io(void)
{
    PyObject *m = PyModule_Create(&_PyIO_Module);
    _PyIO_State *state = NULL;
    if (m == NULL)
        return NULL;
    state = IO_MOD_STATE(m);
    state->initialized = 0;

    /* put os in the module state */
    state->os_module = PyImport_ImportModule("os");
    if (state->os_module == NULL)
        goto fail;

#define ADD_TYPE(type, name) \
    if (PyType_Ready(type) < 0) \
        goto fail; \
    Py_INCREF(type); \
    if (PyModule_AddObject(m, name, (PyObject *)type) < 0) {  \
        Py_DECREF(type); \
        goto fail; \
    }

    /* DEFAULT_BUFFER_SIZE */
    if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
        goto fail;

    /* UnsupportedOperation inherits from ValueError and IOError */
    state->unsupported_operation = PyObject_CallFunction(
        (PyObject *)&PyType_Type, "s(OO){}",
        "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
    if (state->unsupported_operation == NULL)
        goto fail;
    Py_INCREF(state->unsupported_operation);
    if (PyModule_AddObject(m, "UnsupportedOperation",
                           state->unsupported_operation) < 0)
        goto fail;

    /* BlockingIOError */
    _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
    ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");

    /* Concrete base types of the IO ABCs.
       (the ABCs themselves are declared through inheritance in io.py)
    */
    ADD_TYPE(&PyIOBase_Type, "_IOBase");
    ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
    ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
    ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");

    /* Implementation of concrete IO objects. */
    /* FileIO */
    PyFileIO_Type.tp_base = &PyRawIOBase_Type;
    ADD_TYPE(&PyFileIO_Type, "FileIO");

    /* BytesIO */
    PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBytesIO_Type, "BytesIO");
    if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
        goto fail;

    /* StringIO */
    PyStringIO_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyStringIO_Type, "StringIO");

    /* BufferedReader */
    PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");

    /* BufferedWriter */
    PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");

    /* BufferedRWPair */
    PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");

    /* BufferedRandom */
    PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");

    /* TextIOWrapper */
    PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");

    /* IncrementalNewlineDecoder */
    ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");

    /* Interned strings */
    if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
        goto fail;
    if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
        goto fail;
    if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
        goto fail;
    if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
        goto fail;
    if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
        goto fail;
    if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
        goto fail;
    if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
        goto fail;
    if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
        goto fail;
    if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
        goto fail;
    if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
        goto fail;
    if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
        goto fail;
    if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
        goto fail;
    if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
        goto fail;
    if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
        goto fail;
    if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
        goto fail;
    if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
        goto fail;
    if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
        goto fail;
    if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
        goto fail;
    if (!(_PyIO_str_setstate = PyUnicode_InternFromString("setstate")))
        goto fail;
    if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
        goto fail;
    if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
        goto fail;
    if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
        goto fail;
    if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
        goto fail;
    
    if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_zero = PyLong_FromLong(0L)))
        goto fail;

    state->initialized = 1;

    return m;

  fail:
    Py_XDECREF(state->os_module);
    Py_XDECREF(state->unsupported_operation);
    Py_DECREF(m);
    return NULL;
}
Exemple #27
0
/* This is the main function.  Read this to understand how the
 * collection process works. */
static Py_ssize_t
collect(int generation)
{
    int i;
    Py_ssize_t m = 0; /* # objects collected */
    Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
    PyGC_Head *young; /* the generation we are examining */
    PyGC_Head *old; /* next older generation */
#ifdef STACKLESS
    /* unlinking may occur in a different tasklet during collection
     * so these must not be on the stack
     */
    static PyGC_Head unreachable; /* non-problematic unreachable trash */
    static PyGC_Head finalizers;  /* objects with, & reachable from, __del__ */
#else
    PyGC_Head unreachable; /* non-problematic unreachable trash */
    PyGC_Head finalizers;  /* objects with, & reachable from, __del__ */
#endif
    PyGC_Head *gc;
    double t1 = 0.0;

    if (delstr == NULL) {
        delstr = PyUnicode_InternFromString("__del__");
        if (delstr == NULL)
            Py_FatalError("gc couldn't allocate \"__del__\"");
    }

    if (debug & DEBUG_STATS) {
        PySys_WriteStderr("gc: collecting generation %d...\n",
                          generation);
        PySys_WriteStderr("gc: objects in each generation:");
        for (i = 0; i < NUM_GENERATIONS; i++)
            PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
                              gc_list_size(GEN_HEAD(i)));
        t1 = get_time();
        PySys_WriteStderr("\n");
    }

    /* update collection and allocation counters */
    if (generation+1 < NUM_GENERATIONS)
        generations[generation+1].count += 1;
    for (i = 0; i <= generation; i++)
        generations[i].count = 0;

    /* merge younger generations with one we are currently collecting */
    for (i = 0; i < generation; i++) {
        gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
    }

    /* handy references */
    young = GEN_HEAD(generation);
    if (generation < NUM_GENERATIONS-1)
        old = GEN_HEAD(generation+1);
    else
        old = young;

    /* Using ob_refcnt and gc_refs, calculate which objects in the
     * container set are reachable from outside the set (i.e., have a
     * refcount greater than 0 when all the references within the
     * set are taken into account).
     */
    update_refs(young);
    subtract_refs(young);

    /* Leave everything reachable from outside young in young, and move
     * everything else (in young) to unreachable.
     * NOTE:  This used to move the reachable objects into a reachable
     * set instead.  But most things usually turn out to be reachable,
     * so it's more efficient to move the unreachable things.
     */
    gc_list_init(&unreachable);
    move_unreachable(young, &unreachable);

    /* Move reachable objects to next generation. */
    if (young != old) {
        if (generation == NUM_GENERATIONS - 2) {
            long_lived_pending += gc_list_size(young);
        }
        gc_list_merge(young, old);
    }
    else {
        long_lived_pending = 0;
        long_lived_total = gc_list_size(young);
    }

    /* All objects in unreachable are trash, but objects reachable from
     * finalizers can't safely be deleted.  Python programmers should take
     * care not to create such things.  For Python, finalizers means
     * instance objects with __del__ methods.  Weakrefs with callbacks
     * can also call arbitrary Python code but they will be dealt with by
     * handle_weakrefs().
     */
    gc_list_init(&finalizers);
    move_finalizers(&unreachable, &finalizers);
    /* finalizers contains the unreachable objects with a finalizer;
     * unreachable objects reachable *from* those are also uncollectable,
     * and we move those into the finalizers list too.
     */
    move_finalizer_reachable(&finalizers);

    /* Collect statistics on collectable objects found and print
     * debugging information.
     */
    for (gc = unreachable.gc.gc_next; gc != &unreachable;
                    gc = gc->gc.gc_next) {
        m++;
        if (debug & DEBUG_COLLECTABLE) {
            debug_cycle("collectable", FROM_GC(gc));
        }
    }

    /* Clear weakrefs and invoke callbacks as necessary. */
    m += handle_weakrefs(&unreachable, old);

    /* Call tp_clear on objects in the unreachable set.  This will cause
     * the reference cycles to be broken.  It may also cause some objects
     * in finalizers to be freed.
     */
    delete_garbage(&unreachable, old);

    /* Collect statistics on uncollectable objects found and print
     * debugging information. */
    for (gc = finalizers.gc.gc_next;
         gc != &finalizers;
         gc = gc->gc.gc_next) {
        n++;
        if (debug & DEBUG_UNCOLLECTABLE)
            debug_cycle("uncollectable", FROM_GC(gc));
    }
    if (debug & DEBUG_STATS) {
        double t2 = get_time();
        if (m == 0 && n == 0)
            PySys_WriteStderr("gc: done");
        else
            PySys_WriteStderr(
                "gc: done, "
                "%" PY_FORMAT_SIZE_T "d unreachable, "
                "%" PY_FORMAT_SIZE_T "d uncollectable",
                n+m, n);
        if (t1 && t2) {
            PySys_WriteStderr(", %.4fs elapsed", t2-t1);
        }
        PySys_WriteStderr(".\n");
    }

    /* Append instances in the uncollectable set to a Python
     * reachable list of garbage.  The programmer has to deal with
     * this if they insist on creating this type of structure.
     */
    (void)handle_finalizers(&finalizers, old);

    /* Clear free list only during the collection of the highest
     * generation */
    if (generation == NUM_GENERATIONS-1) {
        clear_freelists();
    }

    if (PyErr_Occurred()) {
        if (gc_str == NULL)
            gc_str = PyUnicode_FromString("garbage collection");
        PyErr_WriteUnraisable(gc_str);
        Py_FatalError("unexpected exception during garbage collection");
    }
    return n+m;
}
Exemple #28
0
PyMODINIT_FUNC
initgreenlet(void)
#endif
{
	PyObject* m = NULL;
	char** p = NULL;
	PyObject *c_api_object;
	static void *_PyGreenlet_API[PyGreenlet_API_pointers];

	GREENLET_NOINLINE_INIT();

#if PY_MAJOR_VERSION >= 3
	m = PyModule_Create(&greenlet_module_def);
#else
	m = Py_InitModule("greenlet", GreenMethods);
#endif
	if (m == NULL)
	{
		INITERROR;
	}

	if (PyModule_AddStringConstant(m, "__version__", GREENLET_VERSION) < 0)
	{
		INITERROR;
	}

#if PY_MAJOR_VERSION >= 3
	ts_curkey = PyUnicode_InternFromString("__greenlet_ts_curkey");
	ts_delkey = PyUnicode_InternFromString("__greenlet_ts_delkey");
#else
	ts_curkey = PyString_InternFromString("__greenlet_ts_curkey");
	ts_delkey = PyString_InternFromString("__greenlet_ts_delkey");
#endif
	if (ts_curkey == NULL || ts_delkey == NULL)
	{
		INITERROR;
	}
	if (PyType_Ready(&PyGreenlet_Type) < 0)
	{
		INITERROR;
	}
	PyExc_GreenletError = PyErr_NewException("greenlet.error", NULL, NULL);
	if (PyExc_GreenletError == NULL)
	{
		INITERROR;
	}
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
	PyExc_GreenletExit = PyErr_NewException("greenlet.GreenletExit",
						PyExc_BaseException, NULL);
#else
	PyExc_GreenletExit = PyErr_NewException("greenlet.GreenletExit",
						NULL, NULL);
#endif
	if (PyExc_GreenletExit == NULL)
	{
		INITERROR;
	}

	ts_current = green_create_main();
	if (ts_current == NULL)
	{
		INITERROR;
	}

	Py_INCREF(&PyGreenlet_Type);
	PyModule_AddObject(m, "greenlet", (PyObject*) &PyGreenlet_Type);
	Py_INCREF(PyExc_GreenletError);
	PyModule_AddObject(m, "error", PyExc_GreenletError);
	Py_INCREF(PyExc_GreenletExit);
	PyModule_AddObject(m, "GreenletExit", PyExc_GreenletExit);
#ifdef GREENLET_USE_GC
	PyModule_AddObject(m, "GREENLET_USE_GC", PyBool_FromLong(1));
#else
	PyModule_AddObject(m, "GREENLET_USE_GC", PyBool_FromLong(0));
#endif

        /* also publish module-level data as attributes of the greentype. */
	for (p=copy_on_greentype; *p; p++) {
		PyObject* o = PyObject_GetAttrString(m, *p);
		if (!o) continue;
		PyDict_SetItemString(PyGreenlet_Type.tp_dict, *p, o);
		Py_DECREF(o);
	}

	/*
	 * Expose C API
	 */

	/* types */
	_PyGreenlet_API[PyGreenlet_Type_NUM] = (void *) &PyGreenlet_Type;

	/* exceptions */
	_PyGreenlet_API[PyExc_GreenletError_NUM] = (void *) PyExc_GreenletError;
	_PyGreenlet_API[PyExc_GreenletExit_NUM] = (void *) PyExc_GreenletExit;

	/* methods */
	_PyGreenlet_API[PyGreenlet_New_NUM] = (void *) PyGreenlet_New;
	_PyGreenlet_API[PyGreenlet_GetCurrent_NUM] =
		(void *) PyGreenlet_GetCurrent;
	_PyGreenlet_API[PyGreenlet_Throw_NUM] = (void *) PyGreenlet_Throw;
	_PyGreenlet_API[PyGreenlet_Switch_NUM] = (void *) PyGreenlet_Switch;
	_PyGreenlet_API[PyGreenlet_SetParent_NUM] =
		(void *) PyGreenlet_SetParent;

#ifdef GREENLET_USE_PYCAPSULE
	c_api_object = PyCapsule_New((void *) _PyGreenlet_API, "greenlet._C_API", NULL);
#else
	c_api_object = PyCObject_FromVoidPtr((void *) _PyGreenlet_API, NULL);
#endif
	if (c_api_object != NULL)
	{
		PyModule_AddObject(m, "_C_API", c_api_object);
	}

#if PY_MAJOR_VERSION >= 3
	return m;
#endif
}
Exemple #29
0
/* This evals py driver expressions, 'expr' is a Python expression that
 * should evaluate to a float number, which is returned.
 *
 * note: PyGILState_Ensure() isnt always called because python can call the
 * bake operator which intern starts a thread which calls scene update which
 * does a driver update. to avoid a deadlock check PyThreadState_Get() if PyGILState_Ensure() is needed.
 */
float BPY_driver_exec(ChannelDriver *driver)
{
	PyObject *driver_vars=NULL;
	PyObject *retval= NULL;
	PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
	PyObject *expr_code;
	PyGILState_STATE gilstate;
	int use_gil;

	DriverVar *dvar;
	double result = 0.0; /* default return */
	char *expr = NULL;
	short targets_ok= 1;
	int i;

	/* get the py expression to be evaluated */
	expr = driver->expression;
	if ((expr == NULL) || (expr[0]=='\0'))
		return 0.0f;

	if(!(G.f & G_SCRIPT_AUTOEXEC)) {
		printf("skipping driver '%s', automatic scripts are disabled\n", driver->expression);
		return 0.0f;
	}

	use_gil= 1; //(PyThreadState_Get()==NULL);

	if(use_gil)
		gilstate = PyGILState_Ensure();

	/* init global dictionary for py-driver evaluation settings */
	if (!bpy_pydriver_Dict) {
		if (bpy_pydriver_create_dict() != 0) {
			fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
			if(use_gil)
				PyGILState_Release(gilstate);
			return 0.0f;
		}
	}

	if(driver->expr_comp==NULL)
		driver->flag |= DRIVER_FLAG_RECOMPILE;

	/* compile the expression first if it hasn't been compiled or needs to be rebuilt */
	if(driver->flag & DRIVER_FLAG_RECOMPILE) {
		Py_XDECREF(driver->expr_comp);
		driver->expr_comp= PyTuple_New(2);

		expr_code= Py_CompileString(expr, "<bpy driver>", Py_eval_input);
		PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, expr_code);

		driver->flag &= ~DRIVER_FLAG_RECOMPILE;
		driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
	}
	else {
		expr_code= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 0);
	}

	if(driver->flag & DRIVER_FLAG_RENAMEVAR) {
		/* may not be set */
		expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
		Py_XDECREF(expr_vars);

		/* intern the arg names so creating the namespace for every run is faster */
		expr_vars= PyTuple_New(BLI_countlist(&driver->variables));
		PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 1, expr_vars);

		for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
			PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_InternFromString(dvar->name));
		}
		
		driver->flag &= ~DRIVER_FLAG_RENAMEVAR;
	}
	else {
		expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
	}

	/* add target values to a dict that will be used as '__locals__' dict */
	driver_vars = PyDict_New(); // XXX do we need to decref this?
	for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
		PyObject *driver_arg = NULL;
		float tval = 0.0f;
		
		/* try to get variable value */
		tval= driver_get_variable_value(driver, dvar);
		driver_arg= PyFloat_FromDouble((double)tval);
		
		/* try to add to dictionary */
		/* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
		if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) < 0) { /* use string interning for faster namespace creation */
			/* this target failed - bad name */
			if (targets_ok) {
				/* first one - print some extra info for easier identification */
				fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
				targets_ok= 0;
			}
			
			fprintf(stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
			// BPy_errors_to_report(NULL); // TODO - reports
			PyErr_Print();
			PyErr_Clear();
		}
	}

#if 0 // slow, with this can avoid all Py_CompileString above.
	/* execute expression to get a value */
	retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
#else
	/* evaluate the compiled expression */
	if (expr_code)
		retval= PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
#endif

	/* decref the driver vars first...  */
	Py_DECREF(driver_vars);

	/* process the result */
	if (retval == NULL) {
		pydriver_error(driver);
	} else if((result= PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
		pydriver_error(driver);
		Py_DECREF(retval);
		result = 0.0;
	}
	else {
		/* all fine, make sure the "invalid expression" flag is cleared */
		driver->flag &= ~DRIVER_FLAG_INVALID;
		Py_DECREF(retval);
	}

	if(use_gil)
		PyGILState_Release(gilstate);
    
	if(finite(result)) {
		return (float)result;
	}
	else {
		fprintf(stderr, "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n", dvar->name, result);
		return 0.0f;
	}
}
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *r, *i, *tmp, *f;
    PyNumberMethods *nbr, *nbi = NULL;
    Py_complex cr, ci;
    int own_r = 0;
    int cr_is_complex = 0;
    int ci_is_complex = 0;
    static PyObject *complexstr;
    static char *kwlist[] = {"real", "imag", 0};

    r = Py_False;
    i = NULL;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
                                     &r, &i))
        return NULL;

    /* Special-case for a single argument when type(arg) is complex. */
    if (PyComplex_CheckExact(r) && i == NULL &&
        type == &PyComplex_Type) {
        /* Note that we can't know whether it's safe to return
           a complex *subclass* instance as-is, hence the restriction
           to exact complexes here.  If either the input or the
           output is a complex subclass, it will be handled below
           as a non-orthogonal vector.  */
        Py_INCREF(r);
        return r;
    }
    if (PyUnicode_Check(r)) {
        if (i != NULL) {
            PyErr_SetString(PyExc_TypeError,
                            "complex() can't take second arg"
                            " if first is a string");
            return NULL;
        }
        return complex_subtype_from_string(type, r);
    }
    if (i != NULL && PyUnicode_Check(i)) {
        PyErr_SetString(PyExc_TypeError,
                        "complex() second arg can't be a string");
        return NULL;
    }

    /* XXX Hack to support classes with __complex__ method */
    if (complexstr == NULL) {
        complexstr = PyUnicode_InternFromString("__complex__");
        if (complexstr == NULL)
            return NULL;
    }
    f = PyObject_GetAttr(r, complexstr);
    if (f == NULL)
        PyErr_Clear();
    else {
        PyObject *args = PyTuple_New(0);
        if (args == NULL)
            return NULL;
        r = PyEval_CallObject(f, args);
        Py_DECREF(args);
        Py_DECREF(f);
        if (r == NULL)
            return NULL;
        own_r = 1;
    }
    nbr = r->ob_type->tp_as_number;
    if (i != NULL)
        nbi = i->ob_type->tp_as_number;
    if (nbr == NULL || nbr->nb_float == NULL ||
        ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
        PyErr_SetString(PyExc_TypeError,
                   "complex() argument must be a string or a number");
        if (own_r) {
            Py_DECREF(r);
        }
        return NULL;
    }

    /* If we get this far, then the "real" and "imag" parts should
       both be treated as numbers, and the constructor should return a
       complex number equal to (real + imag*1j).

       Note that we do NOT assume the input to already be in canonical
       form; the "real" and "imag" parts might themselves be complex
       numbers, which slightly complicates the code below. */
    if (PyComplex_Check(r)) {
        /* Note that if r is of a complex subtype, we're only
           retaining its real & imag parts here, and the return
           value is (properly) of the builtin complex type. */
        cr = ((PyComplexObject*)r)->cval;
        cr_is_complex = 1;
        if (own_r) {
            Py_DECREF(r);
        }
    }
    else {
        /* The "real" part really is entirely real, and contributes
           nothing in the imaginary direction.
           Just treat it as a double. */
        tmp = PyNumber_Float(r);
        if (own_r) {
            /* r was a newly created complex number, rather
               than the original "real" argument. */
            Py_DECREF(r);
        }
        if (tmp == NULL)
            return NULL;
        if (!PyFloat_Check(tmp)) {
            PyErr_SetString(PyExc_TypeError,
                            "float(r) didn't return a float");
            Py_DECREF(tmp);
            return NULL;
        }
        cr.real = PyFloat_AsDouble(tmp);
        cr.imag = 0.0; /* Shut up compiler warning */
        Py_DECREF(tmp);
    }
    if (i == NULL) {
        ci.real = 0.0;
    }
    else if (PyComplex_Check(i)) {
        ci = ((PyComplexObject*)i)->cval;
        ci_is_complex = 1;
    } else {
        /* The "imag" part really is entirely imaginary, and
           contributes nothing in the real direction.
           Just treat it as a double. */
        tmp = (*nbi->nb_float)(i);
        if (tmp == NULL)
            return NULL;
        ci.real = PyFloat_AsDouble(tmp);
        Py_DECREF(tmp);
    }
    /*  If the input was in canonical form, then the "real" and "imag"
        parts are real numbers, so that ci.imag and cr.imag are zero.
        We need this correction in case they were not real numbers. */

    if (ci_is_complex) {
        cr.real -= ci.imag;
    }
    if (cr_is_complex) {
        ci.real += cr.imag;
    }
    return complex_subtype_from_doubles(type, cr.real, ci.real);
}