From 7da5d6344d9f9dc57f472e44a7c6b6267a307dd3 Mon Sep 17 00:00:00 2001 From: Joel de Guzman Date: Tue, 1 Oct 2002 00:31:57 +0000 Subject: [PATCH] Removing V1 Artifacts [SVN r15592] --- src/classes.cpp | 1047 --------------------------- src/conversions.cpp | 223 ------ src/converter/from_python.cpp | 4 +- src/cross_module.cpp | 104 --- src/extension_class.cpp | 685 ------------------ src/functions.cpp | 181 ----- src/gen_all.py | 26 - src/gen_arg_tuple_size.py | 139 ---- src/gen_call.py | 82 --- src/gen_callback.py | 124 ---- src/gen_caller.py | 138 ---- src/gen_extclass.py | 948 ------------------------ src/gen_function.py | 243 ------- src/gen_init_function.py | 215 ------ src/gen_py_api.py | 776 -------------------- src/gen_returning.py | 201 ------ src/gen_signature.py | 90 --- src/gen_signatures.py | 158 ---- src/gen_singleton.py | 58 -- src/gen_value_holder.py | 35 - src/init_function.cpp | 38 - src/module.cpp | 6 +- src/module_builder.cpp | 64 -- src/object/function.cpp | 139 +++- src/object/iterator.cpp | 1 - src/objects.cpp | 488 ------------- src/py_interface.cpp | 1103 ---------------------------- src/types.cpp | 1272 --------------------------------- 28 files changed, 119 insertions(+), 8469 deletions(-) delete mode 100644 src/classes.cpp delete mode 100644 src/conversions.cpp delete mode 100644 src/cross_module.cpp delete mode 100644 src/extension_class.cpp delete mode 100644 src/functions.cpp delete mode 100644 src/gen_all.py delete mode 100644 src/gen_arg_tuple_size.py delete mode 100644 src/gen_call.py delete mode 100644 src/gen_callback.py delete mode 100644 src/gen_caller.py delete mode 100644 src/gen_extclass.py delete mode 100644 src/gen_function.py delete mode 100644 src/gen_init_function.py delete mode 100644 src/gen_py_api.py delete mode 100644 src/gen_returning.py delete mode 100644 src/gen_signature.py delete mode 100644 src/gen_signatures.py delete mode 100644 src/gen_singleton.py delete mode 100644 src/gen_value_holder.py delete mode 100644 src/init_function.cpp delete mode 100644 src/module_builder.cpp delete mode 100644 src/objects.cpp delete mode 100644 src/py_interface.cpp delete mode 100644 src/types.cpp diff --git a/src/classes.cpp b/src/classes.cpp deleted file mode 100644 index 440fe6a7..00000000 --- a/src/classes.cpp +++ /dev/null @@ -1,1047 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// Revision History: -// 04 Mar 01 Rolled in const_cast from Dragon fork (Dave Abrahams) -// 03 Mar 01 added: pickle safety measures (Ralf W. Grosse-Kunstleve) -// 03 Mar 01 bug fix: use bound_function::create() (instead of new bound_function) - -#define BOOST_PYTHON_SOURCE - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { namespace python { - -namespace detail { - void enable_named_method(boost::python::detail::class_base* type_obj, const char* name); -} - -namespace { - // Add the name of the module currently being loaded to the name_space with the - // key "__module__". If no module is being loaded, or if name_space already has - // a key "__module", has no effect. This is not really a useful public - // interface; it's just used for class_t<>::class_t() below. - void add_current_module_name(dictionary&); - - bool is_prefix(const char* s1, const char* s2); - bool is_special_name(const char* name); - void enable_special_methods(boost::python::detail::class_base* derived, const tuple& bases, const dictionary& name_space); - - void report_ignored_exception(PyObject* source) - { - // This bit of code copied wholesale from classobject.c in the Python source. - PyObject *f, *t, *v, *tb; - PyErr_Fetch(&t, &v, &tb); - f = PySys_GetObject(const_cast("stderr")); - if (f != NULL) - { - PyFile_WriteString(const_cast("Exception "), f); - if (t) { - PyFile_WriteObject(t, f, Py_PRINT_RAW); - if (v && v != Py_None) { - PyFile_WriteString(const_cast(": "), f); - PyFile_WriteObject(v, f, 0); - } - } - PyFile_WriteString(const_cast(" in "), f); - PyFile_WriteObject(source, f, 0); - PyFile_WriteString(const_cast(" ignored\n"), f); - PyErr_Clear(); /* Just in case */ - } - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); - } - - // - // pickle support courtesy of "Ralf W. Grosse-Kunstleve" - // - PyObject* class_reduce(PyObject* klass) - { - return PyObject_GetAttrString(klass, const_cast("__name__")); - } - - ref global_class_reduce() - { - return ref(detail::new_wrapped_function(class_reduce)); - } - - - tuple instance_reduce(PyObject* obj) - { - ref instance_class(PyObject_GetAttrString(obj, const_cast("__class__"))); - - ref getinitargs(PyObject_GetAttrString(obj, const_cast("__getinitargs__")), - ref::null_ok); - PyErr_Clear(); - ref initargs; - if (getinitargs.get() != 0) - { - initargs = ref(PyEval_CallObject(getinitargs.get(), NULL)); - initargs = ref(PySequence_Tuple(initargs.get())); - } - else - { - initargs = ref(PyTuple_New(0)); - } - - ref getstate(PyObject_GetAttrString(obj, const_cast("__getstate__")), - ref::null_ok); - PyErr_Clear(); - - ref dict(PyObject_GetAttrString(obj, const_cast("__dict__")), ref::null_ok); - PyErr_Clear(); - - if (getstate.get() != 0) - { - if (dict.get() != 0 && dictionary(dict).size() > 0) - { - ref getstate_manages_dict(PyObject_GetAttrString(instance_class.get(), const_cast("__getstate_manages_dict__")), ref::null_ok); - PyErr_Clear(); - if (getstate_manages_dict.get() == 0) - { - PyErr_SetString(PyExc_RuntimeError, "Incomplete pickle support (__getstate_manages_dict__ not set)"); - throw_error_already_set(); - } - } - - ref state = ref(PyEval_CallObject(getstate.get(), NULL)); - return tuple(instance_class, initargs, state); - } - - if (getinitargs.get() == 0) - { - ref dict_defines_state(PyObject_GetAttrString(instance_class.get(), const_cast("__dict_defines_state__")), ref::null_ok); - PyErr_Clear(); - if (dict_defines_state.get() == 0) - { - PyErr_SetString(PyExc_RuntimeError, "Incomplete pickle support (__dict_defines_state__ not set)"); - throw_error_already_set(); - } - } - - if (dict.get() != 0 && dictionary(dict).size() > 0) - { - return tuple(instance_class, initargs, dict); - } - - return tuple(instance_class, initargs); - } - - ref global_instance_reduce() - { - return ref(detail::new_wrapped_function(instance_reduce)); - } -} - - -namespace detail { - - class_base::class_base(PyTypeObject* meta_class_obj, string name, tuple bases, const dictionary& name_space) - : type_object_base(meta_class_obj), - m_name(name), - m_bases(bases), - m_name_space(name_space) - { - this->tp_name = const_cast(name.c_str()); - enable(type_object_base::getattr); - enable(type_object_base::setattr); - add_current_module_name(m_name_space); - static const boost::python::string docstr("__doc__", boost::python::string::interned); - if (PyDict_GetItem(m_name_space.get(), docstr.get())== 0) - { - PyDict_SetItem(m_name_space.get(), docstr.get(), Py_None); - } - enable_special_methods(this, bases, name_space); - } - - void class_base::add_base(ref base) - { - tuple new_bases(m_bases.size() + 1); - for (std::size_t i = 0; i < m_bases.size(); ++i) - new_bases.set_item(i, m_bases[i]); - new_bases.set_item(m_bases.size(), base); - m_bases = new_bases; - } - - PyObject* class_base::getattr(const char* name) - { - if (!BOOST_CSTD_::strcmp(name, "__dict__")) - { - PyObject* result = m_name_space.get(); - Py_INCREF(result); - return result; - } - - if (!BOOST_CSTD_::strcmp(name, "__bases__")) - { - PyObject* result = m_bases.get(); - Py_INCREF(result); - return result; - } - - if (!BOOST_CSTD_::strcmp(name, "__name__")) - { - PyObject* result = m_name.get(); - Py_INCREF(result); - return result; - } - - // pickle support courtesy of "Ralf W. Grosse-Kunstleve" - if (!BOOST_CSTD_::strcmp(name, "__safe_for_unpickling__")) - { - return PyInt_FromLong(1); - } - if (!BOOST_CSTD_::strcmp(name, "__reduce__")) - { - PyObject* self = as_object(this); - ref target(self, ref::increment_count); - return bound_function::create(target, global_class_reduce()); - } - - ref local_attribute = m_name_space.get_item(string(name).reference()); - - if (local_attribute.get()) - return local_attribute.release(); - - // In case there are no bases... - PyErr_SetString(PyExc_AttributeError, name); - - // Check bases - for (std::size_t i = 0; i < m_bases.size(); ++i) - { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); // we're going to try a base class - else if (PyErr_Occurred()) - break; // Other errors count, though! - - PyObject* base_attribute = PyObject_GetAttrString(m_bases[i].get(), const_cast(name)); - - if (base_attribute != 0) - { - // Unwind the actual underlying function from unbound Python class - // methods in case of multiple inheritance from real Python - // classes. Python stubbornly insists that the first argument to a - // method must be a true Python instance object otherwise. Do not - // unwrap bound methods; that would interfere with intended semantics. - if (PyMethod_Check(base_attribute) - && reinterpret_cast(base_attribute)->im_self == 0) - { - PyObject* function - = reinterpret_cast(base_attribute)->im_func; - Py_INCREF(function); - Py_DECREF(base_attribute); - return function; - } - else - { - return base_attribute; - } - } - } - return 0; - } - - // Mostly copied wholesale from Python's classobject.c - PyObject* class_base::repr() const - { - PyObject *mod = PyDict_GetItemString( - m_name_space.get(), const_cast("__module__")); - unsigned long address = reinterpret_cast(this); - string result = (mod == NULL || !PyString_Check(mod)) - ? string("") % tuple(m_name, address) - : string("") % tuple(ref(mod, ref::increment_count), m_name, address); - return result.reference().release(); - } - - - int class_base::setattr(const char* name, PyObject* value) - { - if (is_special_name(name) - && BOOST_CSTD_::strcmp(name, "__doc__") != 0 - && BOOST_CSTD_::strcmp(name, "__name__") != 0) - { - boost::python::string message("Special attribute names other than '__doc__' and '__name__' are read-only, in particular: "); - PyErr_SetObject(PyExc_TypeError, (message + name).get()); - throw_error_already_set(); - } - - if (PyCallable_Check(value)) - detail::enable_named_method(this, name); - - return PyDict_SetItemString( - m_name_space.reference().get(), const_cast(name), value); - } - - bool class_base::initialize_instance(instance* obj, PyObject* args, PyObject* keywords) - { - // Getting the init function off the obj should result in a - // bound method. - PyObject* const init_function = obj->getattr("__init__", false); - - if (init_function == 0) - { - if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); // no __init__? That's legal. - } - else { - return false; // Something else? Keep the error - } - } - else - { - // Manage the reference to the bound function - ref init_function_holder(init_function); - - // Declare a ref to manage the result of calling __init__ (which should be None). - ref init_result( - PyEval_CallObjectWithKeywords(init_function, args, keywords)); - } - return true; - } - - void class_base::instance_dealloc(PyObject* obj) const - { - Py_INCREF(obj); // This allows a __del__ function to revive the obj - - PyObject* exc_type; - PyObject* exc_value; - PyObject* exc_traceback; - PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); - - // This scope ensures that the reference held by del_function doesn't release - // the last reference and delete the object recursively (infinitely). - { - ref del_function; - try { - instance* const target = boost::python::downcast(obj); - del_function = ref(target->getattr("__del__", false), ref::null_ok); - } - catch(...) { - } - - if (del_function.get() != 0) - { - ref result(PyEval_CallObject(del_function.get(), (PyObject *)NULL), ref::null_ok); - - if (result.get() == NULL) - report_ignored_exception(del_function.get()); - } - } - PyErr_Restore(exc_type, exc_value, exc_traceback); - - if (--obj->ob_refcnt <= 0) - delete_instance(obj); - } - - -} - -instance::instance(PyTypeObject* class_) - : boost::python::detail::base_object(class_) -{ -} - -instance::~instance() -{ -} - -PyObject* instance::getattr(const char* name, bool use_special_function) -{ - if (!BOOST_CSTD_::strcmp(name, "__dict__")) - { - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "instance.__dict__ not accessible in restricted mode"); - return 0; - } - Py_INCREF(m_name_space.get()); - return m_name_space.get(); - } - - if (!BOOST_CSTD_::strcmp(name, "__class__")) - { - Py_INCREF(this->ob_type); - return as_object(this->ob_type); - } - - if (!BOOST_CSTD_::strcmp(name, "__reduce__")) - { - return detail::bound_function::create(ref(this, ref::increment_count), global_instance_reduce()); - } - - ref local_attribute = m_name_space.get_item(string(name).reference()); - - if (local_attribute.get()) - return local_attribute.release(); - - // Check its class. - PyObject* function = - PyObject_GetAttrString(as_object(this->ob_type), const_cast(name)); - - if (function == 0 && !use_special_function) - { - return 0; - } - - ref class_attribute; - if (function != 0) - { - // This will throw if the attribute wasn't found - class_attribute = ref(function); - } - else - { - // Clear the error while we try special methods method (if any). - PyErr_Clear(); - - // First we try the special method that comes from concatenating - // "__getattr__" and and 2 trailing underscores. This is an - // extension to regular Python class functionality. - const string specific_getattr_name(detail::getattr_string() + name + "__"); - PyObject* getattr_method = PyObject_GetAttr( - as_object(this->ob_type), specific_getattr_name.get()); - - // Use just the first arg to PyEval_CallFunction if found - char* arg_format = const_cast("(O)"); - - // Try for the regular __getattr__ method if not found - if (getattr_method == 0) - { - PyErr_Clear(); - getattr_method = PyObject_GetAttrString( - as_object(this->ob_type), const_cast("__getattr__")); - - // Use both args to PyEval_CallFunction - arg_format = const_cast("(Os)"); - } - - // If there is no such method, throw now. - if (PyErr_Occurred()) - { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - // Take ownership of the method - ref owner(getattr_method); - - // Call it to get the attribute. - return PyEval_CallFunction(getattr_method, arg_format, this, name); - } - - if (!PyCallable_Check(class_attribute.get())) - { - PyErr_Clear(); - return class_attribute.release(); - } - else - { - return detail::bound_function::create(ref(this, ref::increment_count), class_attribute); - } -} - -// instance::setattr_dict -// -// Implements setattr() functionality for the "__dict__" attribute -// -int instance::setattr_dict(PyObject* value) -{ - if (PyEval_GetRestricted()) - { - PyErr_SetString(PyExc_RuntimeError, - "__dict__ not accessible in restricted mode"); - return -1; - } - - if (value == 0 || !PyDict_Check(value)) - { - PyErr_SetString(PyExc_TypeError, - "__dict__ must be set to a dictionary"); - return -1; - } - m_name_space = dictionary(ref(value, ref::increment_count)); - return 0; -} - -// instance::setattr - -// -// Implements the setattr() and delattr() functionality for our own instance -// objects, using the standard Python interface: if value == 0, we are deleting -// the attribute, and returns 0 unless an error occurred. -int instance::setattr(const char* name, PyObject* value) -{ - if (BOOST_CSTD_::strcmp(name, "__class__") == 0) - { - PyErr_SetString(PyExc_TypeError, "__class__ attribute is read-only"); - throw_error_already_set(); - } - - if (BOOST_CSTD_::strcmp(name, "__dict__") == 0) - return setattr_dict(value); - - // Try to find an appropriate "specific" setter or getter method, either - // __setattr____(value) or __delattr____(). This is an extension - // to regular Python class functionality. - const string& base_name = value ? detail::setattr_string() : detail::delattr_string(); - const string specific_method_name(base_name + name + "__"); - - ref special_method( - PyObject_GetAttr(as_object(this->ob_type), specific_method_name.get()), - ref::null_ok); - - PyObject* result_object = 0; - if (special_method.get() != 0) - { - // The specific function was found; call it now. Note that if value is - // not included in the format string, it is ignored. - char* format_string = const_cast(value ? "(OO)" : "(O)"); - result_object = PyEval_CallFunction(special_method.get(), format_string, this, value); - } - else - { - // If not found, try the usual __setattr__(name, value) or - // __delattr__(name) functions. - PyErr_Clear(); - special_method.reset( - PyObject_GetAttr(as_object(this->ob_type), base_name.get()), - ref::null_ok); - - if (special_method.get() != 0) - { - // The special function was found; call it now. Note that if value - // is not included in the format string, it is ignored. - char* format_string = const_cast(value ? "(OsO)" : "(Os)"); - result_object = PyEval_CallFunction( - special_method.get(), format_string, this, name, value); - } - } - - // If we found an appropriate special method, handle the return value. - if (special_method.get() != 0) - { - ref manage_result(result_object); - return 0; - } - - PyErr_Clear(); // Nothing was found; clear the python error state - - if (value == 0) // Try to remove the attribute from our name space - { - const int result = PyDict_DelItemString(m_name_space.reference().get(), - const_cast(name)); - if (result < 0) - { - PyErr_Clear(); - PyErr_SetString(PyExc_AttributeError, "delete non-existing instance attribute"); - } - return result; - } - else // Change the specified item in our name space - { - return PyDict_SetItemString(m_name_space.reference().get(), - const_cast(name), value); - } -} - -PyObject* instance::call(PyObject* args, PyObject* keywords) -{ - return PyEval_CallObjectWithKeywords( - ref(getattr("__call__")).get(), // take possession of the result from getattr() - args, keywords); -} - -PyObject* instance::repr() -{ - return callback::call_method(this, "__repr__"); -} - -int instance::compare(PyObject* other) -{ - return callback::call_method(this, "__cmp__", other); -} - -PyObject* instance::str() -{ - return callback::call_method(this, "__str__"); -} - -long instance::hash() -{ - return callback::call_method(this, "__hash__"); -} - -int instance::length() -{ - return callback::call_method(this, "__len__"); -} - -PyObject* instance::get_subscript(PyObject* key) -{ - return callback::call_method(this, "__getitem__", key); -} - -void instance::set_subscript(PyObject* key, PyObject* value) -{ - if (value == 0) - callback::call_method(this, "__delitem__", key); - else - callback::call_method(this, "__setitem__", key, value); -} - -PyObject* instance::get_slice(int start, int finish) -{ - return callback::call_method(this, "__getslice__", start, finish); -} - -void instance::set_slice(int start, int finish, PyObject* value) -{ - if (value == 0) - callback::call_method(this, "__delslice__", start, finish); - else - callback::call_method(this, "__setslice__", start, finish, value); -} - -PyObject* instance::add(PyObject* other) -{ - return callback::call_method(this, "__add__", other); -} - -PyObject* instance::subtract(PyObject* other) -{ - return callback::call_method(this, "__sub__", other); -} - -PyObject* instance::multiply(PyObject* other) -{ - return callback::call_method(this, "__mul__", other); -} - -PyObject* instance::divide(PyObject* other) -{ - return callback::call_method(this, "__div__", other); -} - -PyObject* instance::remainder(PyObject* other) -{ - return callback::call_method(this, "__mod__", other); -} - -PyObject* instance::divmod(PyObject* other) -{ - return callback::call_method(this, "__divmod__", other); -} - -PyObject* instance::power(PyObject* exponent, PyObject* modulus) -{ - if (as_object(modulus) == Py_None) - return callback::call_method(this, "__pow__", exponent); - else - return callback::call_method(this, "__pow__", exponent, modulus); -} - -PyObject* instance::negative() -{ - return callback::call_method(this, "__neg__"); -} - -PyObject* instance::positive() -{ - return callback::call_method(this, "__pos__"); -} - -PyObject* instance::absolute() -{ - return callback::call_method(this, "__abs__"); -} - -int instance::nonzero() -{ - return callback::call_method(this, "__nonzero__"); -} - -PyObject* instance::invert() -{ - return callback::call_method(this, "__invert__"); -} - -PyObject* instance::lshift(PyObject* other) -{ - return callback::call_method(this, "__lshift__", other); -} - -PyObject* instance::rshift(PyObject* other) -{ - return callback::call_method(this, "__rshift__", other); -} - -PyObject* instance::do_and(PyObject* other) -{ - return callback::call_method(this, "__and__", other); -} - -PyObject* instance::do_xor(PyObject* other) -{ - return callback::call_method(this, "__xor__", other); -} - -PyObject* instance::do_or(PyObject* other) -{ - return callback::call_method(this, "__or__", other); -} - -int instance::coerce(PyObject** x, PyObject** y) -{ - assert(this == *x); - - // Coerce must return a tuple - tuple result(callback::call_method(this, "__coerce__", *y)); - - *x = result[0].release(); - *y = result[1].release(); - return 0; -} - -PyObject* instance::as_int() -{ - return callback::call_method(this, "__int__"); -} - -PyObject* instance::as_long() -{ - return callback::call_method(this, "__long__"); -} - -PyObject* instance::as_float() -{ - return callback::call_method(this, "__float__"); -} - -PyObject* instance::oct() -{ - return callback::call_method(this, "__oct__"); -} - -PyObject* instance::hex() -{ - return callback::call_method(this, "__hex__"); -} - -PyObject* instance::lt(PyObject* other) -{ - return callback::call_method(this, "__lt__", other); -} - -PyObject* instance::le(PyObject* other) -{ - return callback::call_method(this, "__le__", other); -} - -PyObject* instance::eq(PyObject* other) -{ - return callback::call_method(this, "__eq__", other); -} - -PyObject* instance::ne(PyObject* other) -{ - return callback::call_method(this, "__ne__", other); -} - -PyObject* instance::gt(PyObject* other) -{ - return callback::call_method(this, "__gt__", other); -} - -PyObject* instance::ge(PyObject* other) -{ - return callback::call_method(this, "__ge__", other); -} - -PyObject* instance::inplace_add(PyObject* other) -{ - return callback::call_method(this, "__iadd__", other); -} - -PyObject* instance::inplace_subtract(PyObject* other) -{ - return callback::call_method(this, "__isub__", other); -} - -PyObject* instance::inplace_multiply(PyObject* other) -{ - return callback::call_method(this, "__imul__", other); -} - -PyObject* instance::inplace_divide(PyObject* other) -{ - return callback::call_method(this, "__idiv__", other); -} - -PyObject* instance::inplace_remainder(PyObject* other) -{ - return callback::call_method(this, "__imod__", other); -} - -PyObject* instance::inplace_power(PyObject* exponent, PyObject* modulus) -{ - if (modulus == Py_None) - return callback::call_method(this, "__ipow__", exponent); - else - return callback::call_method(this, "__ipow__", exponent, modulus); -} - -PyObject* instance::inplace_lshift(PyObject* other) -{ - return callback::call_method(this, "__ilshift__", other); -} - -PyObject* instance::inplace_rshift(PyObject* other) -{ - return callback::call_method(this, "__irshift__", other); -} - -PyObject* instance::inplace_and(PyObject* other) -{ - return callback::call_method(this, "__iand__", other); -} - -PyObject* instance::inplace_or(PyObject* other) -{ - return callback::call_method(this, "__ior__", other); -} - -PyObject* instance::inplace_xor(PyObject* other) -{ - return callback::call_method(this, "__ixor__", other); -} - -namespace { - struct named_capability - { - const char* name; - detail::type_object_base::capability capability; - }; - - const named_capability enablers[] = - { - { "__hash__", detail::type_object_base::hash }, - { "__cmp__", detail::type_object_base::compare }, - { "__gt__", detail::type_object_base::richcompare }, - { "__ge__", detail::type_object_base::richcompare }, - { "__lt__", detail::type_object_base::richcompare }, - { "__le__", detail::type_object_base::richcompare }, - { "__eq__", detail::type_object_base::richcompare }, - { "__ne__", detail::type_object_base::richcompare }, - { "__iadd__", detail::type_object_base::number_inplace_add }, - { "__isub__", detail::type_object_base::number_inplace_subtract }, - { "__imul__", detail::type_object_base::number_inplace_multiply }, - { "__idiv__", detail::type_object_base::number_inplace_divide }, - { "__imod__", detail::type_object_base::number_inplace_remainder }, - { "__ipow__", detail::type_object_base::number_inplace_power }, - { "__ilshift__", detail::type_object_base::number_inplace_lshift }, - { "__irshift__", detail::type_object_base::number_inplace_rshift }, - { "__iand__", detail::type_object_base::number_inplace_and }, - { "__ixor__", detail::type_object_base::number_inplace_xor }, - { "__ior__", detail::type_object_base::number_inplace_or }, - { "__repr__", detail::type_object_base::repr }, - { "__str__", detail::type_object_base::str }, - { "__call__", detail::type_object_base::call }, - { "__getattr__", detail::type_object_base::getattr }, - { "__setattr__", detail::type_object_base::setattr }, - { "__len__", detail::type_object_base::mapping_length }, - { "__len__", detail::type_object_base::sequence_length }, - { "__getitem__", detail::type_object_base::mapping_subscript }, - { "__getitem__", detail::type_object_base::sequence_item }, - { "__setitem__", detail::type_object_base::mapping_ass_subscript }, - { "__setitem__", detail::type_object_base::sequence_ass_item }, - { "__delitem__", detail::type_object_base::mapping_ass_subscript }, - { "__delitem__", detail::type_object_base::sequence_ass_item }, - { "__getslice__", detail::type_object_base::sequence_slice }, - { "__setslice__", detail::type_object_base::sequence_ass_slice }, - { "__delslice__", detail::type_object_base::sequence_ass_slice }, - { "__add__", detail::type_object_base::number_add }, - { "__sub__", detail::type_object_base::number_subtract }, - { "__mul__", detail::type_object_base::number_multiply }, - { "__div__", detail::type_object_base::number_divide }, - { "__mod__", detail::type_object_base::number_remainder }, - { "__divmod__", detail::type_object_base::number_divmod }, - { "__pow__", detail::type_object_base::number_power }, - { "__neg__", detail::type_object_base::number_negative }, - { "__pos__", detail::type_object_base::number_positive }, - { "__abs__", detail::type_object_base::number_absolute }, - { "__nonzero__", detail::type_object_base::number_nonzero }, - { "__invert__", detail::type_object_base::number_invert }, - { "__lshift__", detail::type_object_base::number_lshift }, - { "__rshift__", detail::type_object_base::number_rshift }, - { "__and__", detail::type_object_base::number_and }, - { "__xor__", detail::type_object_base::number_xor }, - { "__or__", detail::type_object_base::number_or }, - { "__coerce__", detail::type_object_base::number_coerce }, - { "__int__", detail::type_object_base::number_int }, - { "__long__", detail::type_object_base::number_long }, - { "__float__", detail::type_object_base::number_float }, - { "__oct__", detail::type_object_base::number_oct }, - { "__hex__", detail::type_object_base::number_hex } - }; - - bool is_prefix(const char* s1, const char* s2) - { - while (*s1 != 0 && *s2 != 0 && *s1 == *s2) - ++s1, ++s2; - return *s1 == 0; - } - - bool is_special_name(const char* name) - { - if (name[0] != '_' || name[1] != '_' || name[2] == 0 || name[3] == 0) - return false; - - std::size_t name_length = BOOST_CSTD_::strlen(name); - return name[name_length - 1] == '_' && name[name_length - 2] == '_'; - } -} - -namespace detail { - // Enable the special handler for methods of the given name, if any. - void enable_named_method(boost::python::detail::class_base* type_obj, const char* name) - { - const std::size_t num_enablers = PY_ARRAY_LENGTH(enablers); - - // Make sure this ends with "__" since we'll only compare the head of the - // string. This is done to make the __getattr____/__setattr____ - // extension work. - if (!is_special_name(name)) - return; - - for (std::size_t i = 0; i < num_enablers; ++i) - { - if (is_prefix(enablers[i].name + 2, name + 2)) - { - type_obj->enable(enablers[i].capability); - } - } - } -} - -namespace { - // Enable any special methods which are enabled in the base class. - void enable_special_methods(boost::python::detail::class_base* derived, const tuple& bases, const dictionary& name_space) - { - for (std::size_t i = 0; i < bases.size(); ++i) - { - PyObject* base = bases[i].get(); - - for (std::size_t n = 0; n < PY_ARRAY_LENGTH(enablers); ++n) - { - ref attribute( - PyObject_GetAttrString(base, const_cast(enablers[n].name)), - ref::null_ok); - PyErr_Clear(); - if (attribute.get() != 0 && PyCallable_Check(attribute.get())) - detail::add_capability(enablers[n].capability, derived); - } - } - - list keys(name_space.keys()); - for (std::size_t j = 0, len = keys.size(); j < len; ++j) - { - string name_obj(keys.get_item(j)); - const char* name = name_obj.c_str(); - - if (!is_special_name(name)) - continue; - - for (std::size_t i = 0; i < PY_ARRAY_LENGTH(enablers); ++i) - { - if (is_prefix(enablers[i].name + 2, name + 2)) - { - detail::add_capability(enablers[i].capability, derived); - } - } - } - } - - void add_current_module_name(dictionary& name_space) - { - static string module_key("__module__", string::interned); - - // If the user didn't specify a __module__ attribute already - if (name_space.get_item(module_key).get() == 0) - { - if (module_builder::initializing()) - { - // The global __name__ is not properly set in this case - name_space.set_item(module_key, module_builder::name()); - } - else - { - // Get the module name from the global __name__ - PyObject *globals = PyEval_GetGlobals(); - if (globals != NULL) - { - PyObject *module_name = PyDict_GetItemString(globals, const_cast("__name__")); - if (module_name != NULL) - name_space.set_item(module_key, module_name); - } - } - } - } -} - -BOOST_PYTHON_DECL bool adjust_slice_indices(PyObject* obj, int& start, int& finish) -{ - ref len(PyEval_CallMethod(obj, "__len__", "()") - , ref::null_ok); - - if (len.get() == 0) - return false; - - int length = PyInt_AsLong(len.get()); - - // This is standard Python class behavior. - if (start < 0) - start += length; - if (finish < 0) - finish += length; - - // This is not - if (start < 0) - start = 0; - if (finish < 0) - finish = 0; - - return true; -} - -namespace detail { -const string& setattr_string() -{ - static string x("__setattr__", string::interned); - return x; -} - -const string& getattr_string() -{ - static string x("__getattr__", string::interned); - return x; -} - -const string& delattr_string() -{ - static string x("__delattr__", string::interned); - return x; -} -} - -}} // namespace boost::python diff --git a/src/conversions.cpp b/src/conversions.cpp deleted file mode 100644 index 3c5edad5..00000000 --- a/src/conversions.cpp +++ /dev/null @@ -1,223 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// Revision History: -// 05 Apr 01 added: from_python std::string type checking (rwgk) -// 12 Mar 01 Python 1.5.2 fixes (Ralf W. Grosse-Kunstleve) -// 11 Mar 01 std::string *MAY* include nulls (Alex Martelli) -// 04 Mar 01 std::complex<> fixes for MSVC (Dave Abrahams) -// 03 Mar 01 added: converters for [plain] char (Ralf W. Grosse-Kunstleve) - -#define BOOST_PYTHON_SOURCE - -#include -#include -#include -#include -#include - -BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE - -BOOST_PYTHON_DECL long from_python(PyObject* p, boost::python::type) -{ - // Why am I clearing the error here before trying to convert? I know there's a reason... - long result; - { - result = PyInt_AsLong(p); - if (PyErr_Occurred()) - boost::python::throw_argument_error(); - } - return result; -} - -BOOST_PYTHON_DECL double from_python(PyObject* p, boost::python::type) -{ - double result; - { - result = PyFloat_AsDouble(p); - if (PyErr_Occurred()) - boost::python::throw_argument_error(); - } - return result; -} - -template -T integer_from_python(PyObject* p, boost::python::type) -{ - const long long_result = from_python(p, boost::python::type()); - - try - { - return boost::numeric_cast(long_result); - } - catch(const boost::bad_numeric_cast&) - { - char buffer[256]; - const char message[] = "%ld out of range for %s"; - sprintf(buffer, message, long_result, typeid(T).name()); - PyErr_SetString(PyExc_ValueError, buffer); - boost::python::throw_argument_error(); - } - return 0; // Not smart enough to know that the catch clause always rethrows -} - -template -PyObject* integer_to_python(T value) -{ - long value_as_long; - - try - { - value_as_long = boost::numeric_cast(value); - } - catch(const boost::bad_numeric_cast&) - { - const char message[] = "value out of range for Python int"; - PyErr_SetString(PyExc_ValueError, message); - boost::python::throw_error_already_set(); - } - - return to_python(value_as_long); -} - -BOOST_PYTHON_DECL int from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(unsigned int i) -{ - return integer_to_python(i); -} - -BOOST_PYTHON_DECL unsigned int from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL short from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL float from_python(PyObject* p, boost::python::type) -{ - return static_cast(from_python(p, boost::python::type())); -} - -BOOST_PYTHON_DECL PyObject* to_python(unsigned short i) -{ - return integer_to_python(i); -} - -BOOST_PYTHON_DECL unsigned short from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(char c) -{ - if (c == '\0') return PyString_FromString(""); - return PyString_FromStringAndSize(&c, 1); -} - -BOOST_PYTHON_DECL char from_python(PyObject* p, boost::python::type) -{ - int l = -1; - if (PyString_Check(p)) l = PyString_Size(p); - if (l < 0 || l > 1) { - PyErr_SetString(PyExc_TypeError, "expected string of length 0 or 1"); - boost::python::throw_argument_error(); - } - if (l == 0) return '\0'; - return PyString_AsString(p)[0]; -} - -BOOST_PYTHON_DECL PyObject* to_python(unsigned char i) -{ - return integer_to_python(i); -} - -BOOST_PYTHON_DECL unsigned char from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(signed char i) -{ - return integer_to_python(i); -} - -BOOST_PYTHON_DECL signed char from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(unsigned long x) -{ - return integer_to_python(x); -} - -BOOST_PYTHON_DECL unsigned long from_python(PyObject* p, boost::python::type type) -{ - return integer_from_python(p, type); -} - -BOOST_PYTHON_DECL void from_python(PyObject* p, boost::python::type) -{ - if (p != Py_None) { - PyErr_SetString(PyExc_TypeError, "expected argument of type None"); - boost::python::throw_argument_error(); - } -} - -BOOST_PYTHON_DECL const char* from_python(PyObject* p, boost::python::type) -{ - const char* s = PyString_AsString(p); - if (!s) - boost::python::throw_argument_error(); - return s; -} - -BOOST_PYTHON_DECL PyObject* to_python(const std::string& s) -{ - return PyString_FromStringAndSize(s.data(), s.size()); -} - -BOOST_PYTHON_DECL std::string from_python(PyObject* p, boost::python::type) -{ - if (! PyString_Check(p)) { - PyErr_SetString(PyExc_TypeError, "expected a string"); - boost::python::throw_argument_error(); - } - return std::string(PyString_AsString(p), PyString_Size(p)); -} - -BOOST_PYTHON_DECL bool from_python(PyObject* p, boost::python::type) -{ - int value = from_python(p, boost::python::type()); - if (value == 0) - return false; - return true; -} - -#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 -// An optimizer bug prevents these from being inlined. -BOOST_PYTHON_DECL PyObject* to_python(double d) -{ - return PyFloat_FromDouble(d); -} - -BOOST_PYTHON_DECL PyObject* to_python(float f) -{ - return PyFloat_FromDouble(f); -} -#endif - -BOOST_PYTHON_END_CONVERSION_NAMESPACE - diff --git a/src/converter/from_python.cpp b/src/converter/from_python.cpp index ade39a21..b6ce54ff 100644 --- a/src/converter/from_python.cpp +++ b/src/converter/from_python.cpp @@ -257,7 +257,7 @@ BOOST_PYTHON_DECL void void_result_from_python(PyObject* o) Py_DECREF(expect_non_null(o)); } -} +} // namespace boost::python::converter BOOST_PYTHON_DECL PyObject* pytype_check(PyTypeObject* type_, PyObject* source) @@ -277,4 +277,4 @@ pytype_check(PyTypeObject* type_, PyObject* source) return source; } -}} // namespace boost::python::converter +}} // namespace boost::python diff --git a/src/cross_module.cpp b/src/cross_module.cpp deleted file mode 100644 index d339c4a7..00000000 --- a/src/cross_module.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* (C) Copyright Ralf W. Grosse-Kunstleve 2001. Permission to copy, use, - modify, sell and distribute this software is granted provided this - copyright notice appears in all copies. This software is provided - "as is" without express or implied warranty, and with no claim as to - its suitability for any purpose. - - Revision History: - 17 Apr 01 merged into boost CVS trunk (Ralf W. Grosse-Kunstleve) -*/ - -#define BOOST_PYTHON_SOURCE - -# include -namespace python = boost::python; -# include // MSVC6.0SP4 does not know std::fprintf -# include // MSVC6.0SP4 does not know std::strcmp - -namespace -{ - - PyObject* get_module_dict(const char* module_name) - { - python::ref module_obj(PyImport_ImportModule((char*) module_name)); - PyObject* module_dict = PyModule_GetDict(module_obj.get()); - if (module_dict == 0) python::throw_import_error(); - return module_dict; - } -} - -namespace boost { namespace python { - -void BOOST_PYTHON_DECL throw_import_error() -{ - throw import_error(); -} - -void BOOST_PYTHON_DECL throw_export_error() -{ - throw export_error(); -} - -namespace detail -{ - BOOST_PYTHON_DECL const char* converters_attribute_name = "__converters__"; - - BOOST_PYTHON_DECL void* import_converter_object(const std::string& module_name, - const std::string& py_class_name, - const std::string& attribute_name) - { - static std::string err; - PyObject* module_dict = get_module_dict(const_cast(module_name.c_str())); - PyObject* py_class = PyDict_GetItemString(module_dict, const_cast(py_class_name.c_str())); - if (py_class == 0) { - err = std::string("module ") + module_name + " has no attribute " + py_class_name; - PyErr_SetString(PyExc_RuntimeError, const_cast(err.c_str())); - python::throw_import_error(); - } - python::ref c_obj(PyObject_GetAttrString(py_class, const_cast(attribute_name.c_str())), ref::null_ok); - if (c_obj.get() == 0) { - err = std::string("object ") + module_name + "." + py_class_name - + " has no attribute " + attribute_name; - PyErr_SetString(PyExc_RuntimeError, const_cast(err.c_str())); - python::throw_import_error(); - } - if (! PyCObject_Check(c_obj.get())) { - err = std::string("object ") + module_name + "." + py_class_name + "." - + attribute_name + " is not a PyCObject"; - PyErr_SetString(PyExc_RuntimeError, const_cast(err.c_str())); - python::throw_import_error(); - } - return PyCObject_AsVoidPtr(c_obj.get()); - } - - BOOST_PYTHON_DECL void check_export_converters_api(const int importing_major, - const int importing_minor, - const int imported_major, - const int imported_minor) - { - if (importing_major != imported_major) { - // Python uses fprintf(stderr, ...) for API warnings. - fprintf(stderr, - "Fatal: export_converters_api mismatch:" - " Importing module = %d.%d" - " Imported module = %d.%d\n", - importing_major, importing_minor, - imported_major, imported_minor); - PyErr_SetString(PyExc_RuntimeError, - "Fatal: export_converters_api mismatch"); - throw_import_error(); - } - if (importing_minor != imported_minor) { - // Python uses fprintf(stderr, ...) for API warnings. - fprintf(stderr, - "Warning: export_converters_api mismatch:" - " Importing module = %d.%d" - " Imported module = %d.%d\n", - importing_major, importing_minor, - imported_major, imported_minor); - } - } - -} - -}} // namespace boost::python::detail diff --git a/src/extension_class.cpp b/src/extension_class.cpp deleted file mode 100644 index 5dc6ec23..00000000 --- a/src/extension_class.cpp +++ /dev/null @@ -1,685 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// Revision History: -// 04 Mar 01 Use PyObject_INIT() instead of trying to hand-initialize (David Abrahams) - -#define BOOST_PYTHON_SOURCE -#define BOOST_PYTHON_EXPORT - -#include -#include -#include -#include -#include - -namespace boost { namespace python { -namespace detail { - - struct operator_dispatcher - : public PyObject - { - static PyTypeObject type_obj; - static PyNumberMethods number_methods; - - static operator_dispatcher* create(const ref& o, const ref& s); - - ref m_object; - ref m_self; - - // data members for allocation/deallocation optimization - operator_dispatcher* m_free_list_link; - static operator_dispatcher* free_list; - - private: - // only accessible through create() - operator_dispatcher(const ref& o, const ref& s); - }; - - operator_dispatcher* operator_dispatcher::free_list = 0; - -}}} // namespace boost::python::detail - -BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE - -inline PyObject* to_python(boost::python::detail::operator_dispatcher* n) { return n; } - -BOOST_PYTHON_END_CONVERSION_NAMESPACE - - -namespace boost { namespace python { - -BOOST_PYTHON_DECL tuple standard_coerce(ref l, ref r) -{ - // Introduced sequence points for exception-safety. - ref first(detail::operator_dispatcher::create(l, l)); - - ref second(r->ob_type == &detail::operator_dispatcher::type_obj - ? r - : ref(detail::operator_dispatcher::create(r, ref()))); - - return tuple(first, second); -} - -namespace detail { - - enum { unwrap_exception_code = -1000 }; - - int unwrap_args(PyObject* left, PyObject* right, PyObject*& self, PyObject*& other) - { - if (left->ob_type != &operator_dispatcher::type_obj || - right->ob_type != &operator_dispatcher::type_obj) - { - PyErr_SetString(PyExc_RuntimeError, "operator_dispatcher::unwrap_args(): expecting operator_dispatcher arguments only!"); - return unwrap_exception_code; - } - - typedef reference DPtr; - DPtr lwrapper(static_cast(left), DPtr::increment_count); - DPtr rwrapper(static_cast(right), DPtr::increment_count); - - if (lwrapper->m_self.get() != 0) - { - self = lwrapper->m_self.get(); - other = rwrapper->m_object.get(); - return 0; - } - else - { - self = rwrapper->m_self.get(); - other = lwrapper->m_object.get(); - return 1; - } - } - - int unwrap_pow_args(PyObject* left, PyObject* right, PyObject* m, - PyObject*& self, PyObject*& first, PyObject*& second) - { - if (left->ob_type != &operator_dispatcher::type_obj || - right->ob_type != &operator_dispatcher::type_obj || - m->ob_type != &operator_dispatcher::type_obj) - { - PyErr_SetString(PyExc_RuntimeError, "operator_dispatcher::unwrap_pow_args(): expecting operator_dispatcher arguments only!"); - return unwrap_exception_code; - } - - typedef reference DPtr; - DPtr lwrapper(static_cast(left), DPtr::increment_count); - DPtr rwrapper(static_cast(right), DPtr::increment_count); - DPtr mwrapper(static_cast(m), DPtr::increment_count); - - if (lwrapper->m_self.get() != 0) - { - self = lwrapper->m_self.get(); - first = rwrapper->m_object.get(); - second = mwrapper->m_object.get(); - return 0; - } - else if (rwrapper->m_self.get() != 0) - { - self = rwrapper->m_self.get(); - first = lwrapper->m_object.get(); - second = mwrapper->m_object.get(); - return 1; - } - else - { - self = mwrapper->m_self.get(); - first = lwrapper->m_object.get(); - second = rwrapper->m_object.get(); - return 2; - } - } - -extension_instance* get_extension_instance(PyObject* p) -{ - // The object's type will just be some class_t object, - // but if its meta-type is right, then it is an extension_instance. - if (p->ob_type->ob_type != extension_meta_class()) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - boost::python::throw_argument_error(); - } - return static_cast(p); -} - -void -extension_instance::add_implementation(std::auto_ptr holder) -{ - for (held_objects::const_iterator p = m_wrapped_objects.begin(); - p != m_wrapped_objects.end(); ++p) - { - if (typeid(*holder) == typeid(**p)) - { - PyErr_SetString(PyExc_RuntimeError, "Base class already initialized"); - throw_error_already_set(); - } - } - m_wrapped_objects.push_back(holder.release()); -} - -extension_instance::extension_instance(PyTypeObject* class_) - : instance(class_) -{ -} - -extension_instance::~extension_instance() -{ - for (held_objects::const_iterator p = m_wrapped_objects.begin(), - finish = m_wrapped_objects.end(); - p != finish; ++p) - { - delete *p; - } -} - -BOOST_PYTHON_DECL meta_class* extension_meta_class() -{ - static meta_class result; - return &result; -} - -typedef class_t extension_class_t; - -bool is_subclass(const extension_class_t* derived, - const PyObject* possible_base) -{ - - tuple bases = derived->bases(); - - for (std::size_t i = 0, size = bases.size(); i < size; ++i) - { - const PyObject* base = bases[i].get(); - - if (base == possible_base) - return true; - - if (base->ob_type == extension_meta_class()) - { - const extension_class_t* base_class = downcast(base); - if (is_subclass(base_class, possible_base)) - return true; - } - } - return false; -} - -// Return true iff obj is an obj of target_class -bool is_instance(extension_instance* obj, - class_t* target_class) -{ - if (obj->ob_type == target_class) - return true; - else - { - return is_subclass( - downcast >(obj->ob_type).get(), - as_object(target_class)); - } -} - -void two_string_error(PyObject* exception_object, const char* format, const char* s1, const char* s2) -{ - char buffer[256]; - std::size_t format_length = BOOST_CSTD_::strlen(format); - std::size_t length1 = BOOST_CSTD_::strlen(s1); - std::size_t length2 = BOOST_CSTD_::strlen(s2); - - std::size_t additional_length = length1 + length2; - if (additional_length + format_length > format_length - 1) - { - std::size_t difference = sizeof(buffer) - 1 - additional_length; - length1 -= difference / 2; - additional_length -= difference / 2; - } - - sprintf(buffer, format, length1, s1, length2, s2); - - PyErr_SetString(exception_object, buffer); - if (exception_object == PyExc_TypeError) - throw_argument_error(); - else - throw_error_already_set(); -} - -// This is called when an attempt has been made to convert the given obj to -// a C++ type for which it doesn't have any obj data. In that case, either -// the obj was not derived from the target_class, or the appropriate -// __init__ function wasn't called to initialize the obj data of the target class. -void report_missing_instance_data( - extension_instance* obj, // The object being converted - class_t* target_class, // the extension class of the C++ type - const std::type_info& target_typeid, // The typeid of the C++ type - bool target_is_ptr) -{ - char buffer[256]; - if (is_instance(obj, target_class)) - { - if (target_is_ptr) - { - two_string_error(PyExc_RuntimeError, - "Object of extension class '%.*s' does not wrap <%.*s>.", - obj->ob_type->tp_name, target_typeid.name()); - } - else - { - const char message[] = "__init__ function for extension class '%.*s' was never called."; - sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, - target_class->tp_name); - } - PyErr_SetString(PyExc_RuntimeError, buffer); - } - else if (target_class == 0) - { - const char message[] = "Cannot convert to <%.*s>; its Python class was never created or has been deleted."; - sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, target_typeid.name()); - PyErr_SetString(PyExc_RuntimeError, buffer); - } - else - { - two_string_error(PyExc_TypeError, "extension class '%.*s' is not convertible into '%.*s'.", - obj->ob_type->tp_name, target_class->tp_name); - } -} - -void report_missing_instance_data( - extension_instance* obj, // The object being converted - class_t* target_class, // the extension class of the C++ type - const std::type_info& target_typeid) // The typeid of the C++ type -{ - report_missing_instance_data(obj, target_class, target_typeid, false); -} - -void report_missing_ptr_data( - extension_instance* obj, // The object being converted - class_t* target_class, // the extension class of the C++ type - const std::type_info& target_typeid) // The typeid of the C++ type -{ - report_missing_instance_data(obj, target_class, target_typeid, true); -} - -void report_missing_class_object(const std::type_info& info) -{ - char buffer[256]; - const char message[] = "Cannot convert <%.*s> to python; its Python class was never created or has been deleted."; - sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, info.name()); - PyErr_SetString(PyExc_RuntimeError, buffer); - throw_error_already_set(); -} - -void report_released_smart_pointer(const std::type_info& info) -{ - char buffer[256]; - const char message[] = "Converting from python, pointer or smart pointer to <%.*s> is NULL."; - sprintf(buffer, message, sizeof(buffer) - sizeof(message) - 1, info.name()); - PyErr_SetString(PyExc_RuntimeError, buffer); - throw_argument_error(); -} - -read_only_setattr_function::read_only_setattr_function(const char* name) - : m_name(name) -{ -} - -PyObject* read_only_setattr_function::do_call(PyObject* /*args*/, PyObject* /*keywords*/) const -{ - PyErr_SetObject(PyExc_AttributeError, ("'" + m_name + "' attribute is read-only").get()); - return 0; -} - -const char* read_only_setattr_function::description() const -{ - return "uncallable"; -} - -extension_class_base::extension_class_base(const char* name) - : class_t( - extension_meta_class(), string(name), tuple(), dictionary()) -{ -} - -// This function is used in from_python() to convert wrapped classes that are -// related by inheritance. The problem is this: although C++ provides all necessary -// conversion operators, source and target of a conversion must be known at compile -// time. However, in Python we want to convert classes at runtime. The solution is to -// generate conversion functions at compile time, register them within the appropriate -// class objects and call them when a particular runtime conversion is required. - -// If functions for any possible conversion have to be stored, their number will grow -// qudratically. To reduce this number, we actually store only conversion functions -// between adjacent levels in the inheritance tree. By traversing the tree recursively, -// we can build any allowed conversion as a concatenation of simple conversions. This -// traversal is done in the functions try_base_class_conversions() and -// try_derived_class_conversions(). If a particular conversion is impossible, all -// conversion functions will return a NULL pointer. - -// The function extract_object_from_holder() attempts to actually extract the pointer -// to the contained object from an instance_holder_base (a wrapper class). A conversion -// of the held object to 'T *' is allowed when the conversion -// 'dynamic_cast *>(an_instance_holder_base)' succeeds. -void* extension_class_base::try_class_conversions(instance_holder_base* object) const -{ - void* result = try_derived_class_conversions(object); - if (result) - return result; - - if (!object->held_by_value()) - return try_base_class_conversions(object); - else - return 0; -} - -void* extension_class_base::try_base_class_conversions(instance_holder_base* object) const -{ - for (std::size_t i = 0; i < base_classes().size(); ++i) - { - if (base_classes()[i].convert == 0) - continue; - void* result1 = base_classes()[i].class_object->extract_object_from_holder(object); - if (result1) - return (*base_classes()[i].convert)(result1); - - void* result2 = base_classes()[i].class_object->try_base_class_conversions(object); - if (result2) - return (*base_classes()[i].convert)(result2); - } - return 0; -} - -void* extension_class_base::try_derived_class_conversions(instance_holder_base* object) const -{ - for (std::size_t i = 0; i < derived_classes().size(); ++i) - { - void* result1 = derived_classes()[i].class_object->extract_object_from_holder(object); - if (result1) - return (*derived_classes()[i].convert)(result1); - - void* result2 = derived_classes()[i].class_object->try_derived_class_conversions(object); - if (result2) - return (*derived_classes()[i].convert)(result2); - } - return 0; -} - -void extension_class_base::add_method(function* method, const char* name) -{ - add_method(reference(method), name); -} - -void extension_class_base::add_method(reference method, const char* name) -{ - // Add the attribute to the computed target - function::add_to_namespace(method, name, this->dict().get()); - - // If it is a special member function it should be enabled both here and there. - detail::enable_named_method(this, name); -} - -void extension_class_base::add_constructor_object(function* init_fn) -{ - add_method(init_fn, "__init__"); -} - -void extension_class_base::add_setter_method(function* setter_, const char* name) -{ - reference setter(setter_); - add_method(setter, (detail::setattr_string() + name + "__").c_str()); -} - -void extension_class_base::add_getter_method(function* getter_, const char* name) -{ - reference getter(getter_); - add_method(getter, (detail::getattr_string() + name + "__").c_str()); -} - -void extension_class_base::set_attribute(const char* name, PyObject* x_) -{ - ref x(x_); - set_attribute(name, x); -} - -void extension_class_base::set_attribute(const char* name, ref x) -{ - dict().set_item(string(name), x); - if (PyCallable_Check(x.get())) - detail::enable_named_method(this, name); -} - -operator_dispatcher::operator_dispatcher(const ref& o, const ref& s) - : m_object(o), m_self(s), m_free_list_link(0) - -{ - PyObject* self = this; - PyObject_INIT(self, &type_obj); -} - -operator_dispatcher* -operator_dispatcher::create(const ref& object, const ref& self) -{ - operator_dispatcher* const result = free_list; - if (result == 0) - return new operator_dispatcher(object, self); - - free_list = result->m_free_list_link; - result->m_object = object; - result->m_self = self; - - PyObject* result_as_pyobject = result; - PyObject_INIT(result_as_pyobject, &type_obj); - return result; -} - -extern "C" -{ - -void operator_dispatcher_dealloc(PyObject* self) -{ - operator_dispatcher* obj = static_cast(self); - obj->m_free_list_link = operator_dispatcher::free_list; - operator_dispatcher::free_list = obj; - obj->m_object.reset(); - obj->m_self.reset(); -} - -int operator_dispatcher_coerce(PyObject** l, PyObject** r) -{ - Py_INCREF(*l); - - return handle_exception( - bind_return( - *r - , bind(operator_dispatcher::create, - ref(*r, ref::increment_count), - ref()))) - ? -1 : 0; -} - -#define PY_DEFINE_OPERATOR(id, symbol) \ - PyObject* operator_dispatcher_call_##id(PyObject* left, PyObject* right) \ - { \ - /* unwrap the arguments from their OperatorDispatcher */ \ - PyObject* self; \ - PyObject* other; \ - int reverse = unwrap_args(left, right, self, other); \ - if (reverse == unwrap_exception_code) \ - return 0; \ - \ - /* call the function */ \ - PyObject* result = \ - PyEval_CallMethod(self, \ - const_cast(reverse ? "__r" #id "__" : "__" #id "__"), \ - const_cast("(O)"), \ - other); \ - if (result == 0 && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError)) \ - { \ - PyErr_Clear(); \ - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for " #symbol); \ - } \ - return result; \ - } - -PY_DEFINE_OPERATOR(add, +) -PY_DEFINE_OPERATOR(sub, -) -PY_DEFINE_OPERATOR(mul, *) -PY_DEFINE_OPERATOR(div, /) -PY_DEFINE_OPERATOR(mod, %) -PY_DEFINE_OPERATOR(divmod, divmod) -PY_DEFINE_OPERATOR(lshift, <<) -PY_DEFINE_OPERATOR(rshift, >>) -PY_DEFINE_OPERATOR(and, &) -PY_DEFINE_OPERATOR(xor, ^) -PY_DEFINE_OPERATOR(or, |) - -/* coercion rules for heterogeneous pow(): - pow(Foo, int): left, right coerced; m: None => reverse = 0 - pow(int, Foo): left, right coerced; m: None => reverse = 1 - pow(Foo, int, int): left, right, m coerced => reverse = 0 - pow(int, Foo, int): left, right, m coerced => reverse = 1 - pow(int, int, Foo): left, right, m coerced => reverse = 2 - pow(Foo, Foo, int): left, right coerced; m coerced twice => reverse = 0 - pow(Foo, int, Foo): left, right, m coerced => reverse = 0 - pow(int, Foo, Foo): left, right, m coerced => reverse = 1 -*/ -PyObject* operator_dispatcher_call_pow(PyObject* left, PyObject* right, PyObject* m) -{ - int reverse; - PyObject* self; - PyObject* first; - PyObject* second; - - if (m->ob_type == Py_None->ob_type) - { - reverse = unwrap_args(left, right, self, first); - second = m; - } - else - { - reverse = unwrap_pow_args(left, right, m, self, first, second); - } - - if (reverse == unwrap_exception_code) - return 0; - - // call the function - PyObject* result = - PyEval_CallMethod(self, - const_cast((reverse == 0) - ? "__pow__" - : (reverse == 1) - ? "__rpow__" - : "__rrpow__"), - const_cast("(OO)"), - first, second); - if (result == 0 && - (PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_TypeError) || - PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError))) - { - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for pow()"); - } - return result; -} - -int operator_dispatcher_call_cmp(PyObject* left, PyObject* right) -{ - // unwrap the arguments from their OperatorDispatcher - PyObject* self; - PyObject* other; - int reverse = unwrap_args(left, right, self, other); - if (reverse == unwrap_exception_code) - return -1; - - // call the function - PyObject* result = - PyEval_CallMethod(self, - const_cast(reverse ? "__rcmp__" : "__cmp__"), - const_cast("(O)"), - other); - if (result == 0) - { - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for cmp() or <"); - return -1; - } - else - { - try - { - return BOOST_PYTHON_CONVERSION::from_python(result, type()); - } - catch(...) - { - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, "cmp() didn't return int"); - return -1; - } - } -} - -} // extern "C" - -PyTypeObject operator_dispatcher::type_obj = -{ - PyObject_HEAD_INIT(&PyType_Type) - 0, - const_cast("operator_dispatcher"), - sizeof(operator_dispatcher), - 0, - &operator_dispatcher_dealloc, - 0, - 0, - 0, - &operator_dispatcher_call_cmp, - 0, - &operator_dispatcher::number_methods, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 -}; - -PyNumberMethods operator_dispatcher::number_methods = -{ - &operator_dispatcher_call_add, - &operator_dispatcher_call_sub, - &operator_dispatcher_call_mul, - &operator_dispatcher_call_div, - &operator_dispatcher_call_mod, - &operator_dispatcher_call_divmod, - &operator_dispatcher_call_pow, - 0, - 0, - 0, - 0, - 0, - &operator_dispatcher_call_lshift, - &operator_dispatcher_call_rshift, - &operator_dispatcher_call_and, - &operator_dispatcher_call_xor, - &operator_dispatcher_call_or, - &operator_dispatcher_coerce, - 0, - 0, - 0, - 0, - 0 -}; - -} // namespace detail - -}} // namespace boost::python diff --git a/src/functions.cpp b/src/functions.cpp deleted file mode 100644 index cb9b067d..00000000 --- a/src/functions.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// Revision History: -// Mar 01 01 Use PyObject_INIT() instead of trying to hand-initialize (David Abrahams) - -#define BOOST_PYTHON_SOURCE - -#include -#include -#include -#include -#include - -namespace boost { namespace python { namespace detail { - -struct function::type_object : - singleton > > -{ - type_object() : singleton_base(&PyType_Type) {} -}; - - -void function::add_to_namespace(reference new_function, const char* name, PyObject* dict) -{ - dictionary d(ref(dict, ref::increment_count)); - string key(name); - - ref existing_object = d.get_item(key.reference()); - if (existing_object.get() == 0) - { - d[key] = ref(new_function.get(), ref::increment_count); - } - else - { - if (existing_object->ob_type == type_object::instance()) - { - function* f = static_cast(existing_object.get()); - while (f->m_overloads.get() != 0) - f = f->m_overloads.get(); - f->m_overloads = new_function; - } - else - { - PyErr_SetObject(PyExc_RuntimeError, - (string("Attempt to overload ") + name - + " failed. The existing attribute has type " - + existing_object->ob_type->tp_name).get()); - throw_error_already_set(); - } - } -} - -function::function() - : python_object(type_object::instance()) -{ -} - -PyObject* function::call(PyObject* args, PyObject* keywords) const -{ - // Traverse the linked list of function overloads until we find one that - // matches. - for (const function* f = this; f != 0; f = f->m_overloads.get()) - { - PyErr_Clear(); - try - { - PyObject* const result = f->do_call(args, keywords); - if (result != 0) - return result; - } - catch(const argument_error&) - { - } - } - - // If we get here, no overloads matched the arguments - - // Allow the single-function error-reporting to take effect unless there was - // an overload - if (m_overloads.get() == 0) - return 0; - - // Synthesize a more-explicit error message - PyErr_Clear(); - string message("No overloaded functions match ("); - tuple arguments(ref(args, ref::increment_count)); - for (std::size_t i = 0; i < arguments.size(); ++i) - { - if (i != 0) - message += ", "; - message += arguments[i]->ob_type->tp_name; - } - - message += "). Candidates are:\n"; - for (const function* f1 = this; f1 != 0; f1 = f1->m_overloads.get()) - { - if (f1 != this) - message += "\n"; - message += f1->description(); - } - - PyErr_SetObject(PyExc_TypeError, message.get()); - return 0; -} - -// The instance class whose obj represents the type of bound_function -// objects in Python. bound_functions must be GetAttrable so the __doc__ -// attribute of built-in Python functions can be accessed when bound. -struct bound_function::type_object : - singleton > > > -{ - type_object() : singleton_base(&PyType_Type) {} - -private: // type_object hook override - void dealloc(bound_function*) const; -}; - -bound_function* bound_function::create(const ref& target, const ref& fn) -{ - bound_function* const result = free_list; - if (result == 0) - return new bound_function(target, fn); - - free_list = result->m_free_list_link; - result->m_target = target; - result->m_unbound_function = fn; - - PyObject* self = result; - PyObject_INIT(self, type_object::instance()); - return result; -} - -bound_function::bound_function(const ref& target, const ref& fn) - : python_object(type_object::instance()), - m_target(target), - m_unbound_function(fn), - m_free_list_link(0) -{ -} - -PyObject* -bound_function::call(PyObject* args, PyObject* keywords) const -{ - // Build a new tuple which prepends the target to the arguments - tuple tail_arguments(ref(args, ref::increment_count)); - ref all_arguments(PyTuple_New(tail_arguments.size() + 1)); - - PyTuple_SET_ITEM(all_arguments.get(), 0, m_target.get()); - Py_INCREF(m_target.get()); - for (std::size_t i = 0; i < tail_arguments.size(); ++i) - { - PyTuple_SET_ITEM(all_arguments.get(), i + 1, tail_arguments[i].get()); - Py_INCREF(tail_arguments[i].get()); - } - - return PyEval_CallObjectWithKeywords(m_unbound_function.get(), all_arguments.get(), keywords); -} - -PyObject* bound_function::getattr(const char* name) const -{ - return PyObject_GetAttrString(m_unbound_function.get(), const_cast(name)); -} - -void bound_function::type_object::dealloc(bound_function* obj) const -{ - obj->m_free_list_link = free_list; - free_list = obj; - obj->m_target.reset(); - obj->m_unbound_function.reset(); -} - -bound_function* bound_function::free_list; - -}}} // namespace boost::python::detail diff --git a/src/gen_all.py b/src/gen_all.py deleted file mode 100644 index 3877d181..00000000 --- a/src/gen_all.py +++ /dev/null @@ -1,26 +0,0 @@ -from gen_callback import * -from gen_caller import * -from gen_init_function import * -from gen_signatures import * -from gen_singleton import * -from gen_extclass import * - -def gen_all(args): - open('callback.hpp', 'w').write(gen_callback(args)) - open('caller.hpp', 'w').write(gen_caller(args)) - open('init_function.hpp', 'w').write(gen_init_function(args)) - open('signatures.hpp', 'w').write(gen_signatures(args)) - open('singleton.hpp', 'w').write(gen_singleton(args)) - open('extension_class.hpp', 'w').write(gen_extclass(args)) - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 10 - else: - args = int(sys.argv[1]) - - print gen_all(args) - - diff --git a/src/gen_arg_tuple_size.py b/src/gen_arg_tuple_size.py deleted file mode 100644 index 9de332ab..00000000 --- a/src/gen_arg_tuple_size.py +++ /dev/null @@ -1,139 +0,0 @@ -# (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -# distribute this software is granted provided this copyright notice appears -# in all copies. This software is provided "as is" without express or implied -# warranty, and with no claim as to its suitability for any purpose. -# -# This work was funded in part by Lawrence Berkeley National Labs - -from gen_function import * -import string - -header = '''// (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// This work was funded in part by Lawrence Berkeley National Labs -// -// This file generated for %d-argument member functions and %d-argument free -// functions by gen_arg_tuple_size.python -''' - -_cv_qualifiers = ('', ' const', ' volatile', ' const volatile') - -_suffix = { - '': ''' -// Metrowerks thinks this creates ambiguities -# if !defined(__MWERKS__) || __MWERKS__ > 0x2406 -''', ' const volatile': ''' -# endif // __MWERKS__ -''' - }; - -def gen_arg_tuple_size(member_function_args, free_function_args = None): - if free_function_args is None: - free_function_args = member_function_args + 1 - - return_none = '''; - return detail::none();''' - - return (header % (member_function_args, free_function_args) - + ''' -#ifndef ARG_TUPLE_SIZE_DWA20011201_HPP -# define ARG_TUPLE_SIZE_DWA20011201_HPP - -# include - -namespace boost { namespace python { namespace detail { - -// Computes (at compile-time) the number of elements that a Python -// argument tuple must have in order to be passed to a wrapped C++ -// (member) function of the given type. -template struct arg_tuple_size; - -# if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(__BORLANDC__) - -''' - + gen_functions( -'''template -struct arg_tuple_size -{ - BOOST_STATIC_CONSTANT(std::size_t, value = %n); -}; - -''', free_function_args) - - + '\n' - - + reduce(lambda x,y: x+'\n'+y - , map( - lambda cv: gen_functions( -'''template -struct arg_tuple_size -{ - BOOST_STATIC_CONSTANT(std::size_t, value = %+); -}; - -''' - , member_function_args, cv) + _suffix.get(cv, '') - , _cv_qualifiers)) - - + -'''# else - -// We will use the "sizeof() trick" to work around the lack of -// partial specialization in MSVC6 and its broken-ness in borland. -// See http://opensource.adobe.com or -// http://groups.yahoo.com/group/boost/message/5441 for -// more examples - -// The following helper functions are never actually called, since -// they are only used within a sizeof() expression, but the type of -// their return value is used to discriminate between various free -// and member function pointers at compile-time. - -''' - + gen_functions( -'''template -char_array<%n> arg_tuple_size_helper(R (*)(%(A%+%:, %))); - -''', free_function_args) - - + reduce(lambda x,y: x+'\n'+y - , map( - lambda cv: gen_functions( -'''template -char_array<%+> arg_tuple_size_helper(R (A0::*)(%(A%+%:, %))%1); - -''', member_function_args, cv) - , _cv_qualifiers)) - + ''' -template -struct arg_tuple_size -{ - // The sizeof() magic happens here - BOOST_STATIC_CONSTANT(std::size_t, value - = sizeof(arg_tuple_size_helper(F(0)).elements) - 1); -}; -# endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -}}} // namespace boost::python::detail - -#endif // ARG_TUPLE_SIZE_DWA20011201_HPP -''') - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - member_function_args = 5 - free_function_args = 6 - else: - member_function_args = int(sys.argv[1]) - if len(sys.argv) > 2: - free_function_args = int(sys.argv[2]) - else: - free_function_args = member_function_args - - print gen_arg_tuple_size(member_function_args, free_function_args) - - diff --git a/src/gen_call.py b/src/gen_call.py deleted file mode 100644 index f609c0ae..00000000 --- a/src/gen_call.py +++ /dev/null @@ -1,82 +0,0 @@ -# (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -# distribute this software is granted provided this copyright notice appears -# in all copies. This software is provided "as is" without express or implied -# warranty, and with no claim as to its suitability for any purpose. -# -# This work was funded in part by Lawrence Berkeley National Labs - -from gen_function import * -import string - -header = '''// Copyright David Abrahams 2001. Permission to copy, use, -// modify, sell and distribute this software is granted provided this -// copyright notice appears in all copies. This software is provided -// "as is" without express or implied warranty, and with no claim as -// to its suitability for any purpose. -// -// This work was funded in part by Lawrence Berkeley National Labs -// -// This file generated for %d-argument member functions and %d-argument free -// functions by gen_call.py - -#ifndef CALL_DWA20011214_HPP -# define CALL_DWA20011214_HPP - -# include - -namespace boost { namespace python { - -''' -_cv_qualifiers = ('', ' const', ' volatile', ' const volatile') - -def gen_call(member_function_args, free_function_args = None): - if free_function_args is None: - free_function_args = member_function_args + 1 - - return (header % (member_function_args, free_function_args) - + gen_functions( -'''template -inline PyObject* call(R (*f)(%(A%n%:, %)), PyObject* args, PyObject* keywords) -{ - return detail::returning::call(f, args, keywords); -} - -''', free_function_args) - + -'''// Member functions -''' - + reduce(lambda x,y: x+y - , map(lambda cv: - gen_functions( -'''template -inline PyObject* call(R (A0::*f)(%(A%+%:, %))%1, PyObject* args, PyObject* keywords) -{ - return detail::returning::call(f, args, keywords); -} - -''' - , member_function_args, cv) - , _cv_qualifiers)) - + -''' -}} // namespace boost::python - -#endif // CALL_DWA20011214_HPP -''') - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - member_function_args = 5 - free_function_args = 6 - else: - member_function_args = int(sys.argv[1]) - if len(sys.argv) > 2: - free_function_args = int(sys.argv[2]) - else: - free_function_args = member_function_args - - print gen_call(member_function_args, free_function_args) - - diff --git a/src/gen_callback.py b/src/gen_callback.py deleted file mode 100644 index f178212b..00000000 --- a/src/gen_callback.py +++ /dev/null @@ -1,124 +0,0 @@ -from gen_function import * -import string - -def gen_callback(args): - return ( -"""// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// This file was generated for %d-argument python callbacks by gen_callback.python - -#ifndef CALLBACK_DWA_052100_H_ -# define CALLBACK_DWA_052100_H_ - -# include -# include - -namespace boost { namespace python { - -namespace detail { - template - inline void callback_adjust_refcount(PyObject*, type) {} - - inline void callback_adjust_refcount(PyObject* p, type) - { Py_INCREF(p); } -} - -// Calling Python from C++ -template -struct callback -{""" % args - - + gen_functions(''' -%{ template <%(class A%n%:, %)> -%} static R call_method(PyObject* self, const char* name%(, const A%n& a%n%)) - {%( - ref p%n(to_python(a%n));%) - ref result(PyEval_CallMethod(self, const_cast(name), - const_cast("(%(O%))")%(, - p%n.get()%))); - detail::callback_adjust_refcount(result.get(), type()); - return from_python(result.get(), type()); - } - -%{ template <%(class A%n%:, %)> -%} static R call(PyObject* self%(, const A%n& a%n%)) - {%( - ref p%n(to_python(a%n));%) - ref result(PyEval_CallFunction(self, const_cast("(%(O%))")%(, - p%n.get()%))); - detail::callback_adjust_refcount(result.get(), type()); - return from_python(result.get(), type()); - } -''', args) - + -"""}; - -// This specialization wouldn't be needed, but MSVC6 doesn't correctly allow the following: -// void g(); -// void f() { return g(); } -template <> -struct callback -{ -""" - + gen_functions(''' -%{ template <%(class A%n%:, %)> -%} static void call_method(PyObject* self, const char* name%(, const A%n& a%n%)) - {%( - ref p%n(to_python(a%n));%) - ref result(PyEval_CallMethod(self, const_cast(name), - const_cast("(%(O%))")%(, - p%n.get()%))); - } - -%{ template <%(class A%n%:, %)> -%} static void call(PyObject* self%(, const A%n& a%n%)) - {%( - ref p%n(to_python(a%n));%) - ref result(PyEval_CallFunction(self, const_cast("(%(O%))")%(, - p%n.get()%))); - } -''', args) - + -"""}; - -// Make it a compile-time error to try to return a const char* from a virtual -// function. The standard conversion -// -// from_python(PyObject* string, boost::python::type) -// -// returns a pointer to the character array which is internal to string. The -// problem with trying to do this in a standard callback function is that the -// Python string would likely be destroyed upon return from the calling function -// (boost::python::callback::call[_method]) when its reference count is -// decremented. If you absolutely need to do this and you're sure it's safe (it -// usually isn't), you can use -// -// boost::python::string result(boost::python::callback::call[_method](...args...)); -// ...result.c_str()... // access the char* array -template <> -struct callback -{ - // Try hard to generate a readable error message - typedef struct unsafe_since_python_string_may_be_destroyed {} call, call_method; -}; - -}} // namespace boost::python - -#endif // CALLBACK_DWA_052100_H_ -""") - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 5 - else: - args = int(sys.argv[1]) - - print gen_callback(args) diff --git a/src/gen_caller.py b/src/gen_caller.py deleted file mode 100644 index 26bd88c6..00000000 --- a/src/gen_caller.py +++ /dev/null @@ -1,138 +0,0 @@ -# (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -# distribute this software is granted provided this copyright notice appears -# in all copies. This software is provided "as is" without express or implied -# warranty, and with no claim as to its suitability for any purpose. -# -# The author gratefully acknowleges the support of Dragon Systems, Inc., in -# producing this work. - -from gen_function import * -import string - -header = '''// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// This file generated for %d-argument member functions and %d-argument free -// functions by gen_caller.python -''' - -body_sections = ( -''' -#ifndef CALLER_DWA05090_H_ -# define CALLER_DWA05090_H_ - -# include -# include -# include -# include -# include - -namespace boost { namespace python { - -// Calling C++ from Python -template -struct caller -{ -''', -''' -''', -''' // Free functions -''', -'''}; - -template <> -struct caller -{ -''', -''' -''', -''' - // Free functions -''', -'''}; - -}} // namespace boost::python - -#endif -''') - -#' - -member_function = ''' template - static PyObject* call(%1 (T::*pmf)(%(A%n%:, %))%2, PyObject* args, PyObject* /* keywords */ ) { - PyObject* self; -%( PyObject* a%n; -%) if (!PyArg_ParseTuple(args, const_cast("O%(O%)"), &self%(, &a%n%))) - return 0; - T& target = from_python(self, type()); - %3(target.*pmf)(%(from_python(a%n, type())%:, - %))%4 - } - -''' - -free_function = '''%{ template <%(class A%n%:, %)> -%} static PyObject* call(%1 (*f)(%(A%n%:, %)), PyObject* args, PyObject* /* keywords */ ) { -%( PyObject* a%n; -%) if (!PyArg_ParseTuple(args, const_cast("%(O%)")%(, &a%n%))) - return 0; - %2f(%(from_python(a%n, type())%:, - %))%3 - } - -''' - -def gen_caller(member_function_args, free_function_args = None): - if free_function_args is None: - free_function_args = member_function_args + 1 - - return_none = '''; - return detail::none();''' - - return (header % (member_function_args, free_function_args) - + body_sections[0] - + gen_functions(member_function, member_function_args, - 'R', '', 'return to_python(', ');') - + body_sections[1] - + gen_functions(member_function, member_function_args, - 'R', ' const', 'return to_python(', ');') - + body_sections[2] - - + gen_functions(free_function, free_function_args, - 'R', 'return to_python(', ');') - + body_sections[3] - - # specialized part for void return values begins here - + gen_functions(member_function, member_function_args, - 'void', '', '', return_none) - + body_sections[4] - + gen_functions(member_function, member_function_args, - 'void', ' const', '', return_none) - + body_sections[5] - - + gen_functions(free_function, free_function_args, - 'void', '', return_none) - + body_sections[6] - ) - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - member_function_args = 5 - free_function_args = 6 - else: - member_function_args = int(sys.argv[1]) - if len(sys.argv) > 2: - free_function_args = int(sys.argv[2]) - else: - free_function_args = member_function_args - - print gen_caller(member_function_args, free_function_args) - - diff --git a/src/gen_extclass.py b/src/gen_extclass.py deleted file mode 100644 index 787e262e..00000000 --- a/src/gen_extclass.py +++ /dev/null @@ -1,948 +0,0 @@ -from gen_function import * -import string - -def gen_extclass(args): - return ( -"""// (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// This file automatically generated for %d-argument constructors by -// gen_extclass.python - -// Revision History: -// 17 Apr 01 Comment added with reference to cross_module.hpp (R.W. Grosse-Kunstleve) -// 05 Mar 01 Fixed a bug which prevented auto_ptr values from being converted -// to_python (Dave Abrahams) - -#ifndef EXTENSION_CLASS_DWA052000_H_ -# define EXTENSION_CLASS_DWA052000_H_ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -namespace boost { namespace python { - -// forward declarations -template struct operators; -template struct left_operand; -template struct right_operand; - -enum without_downcast_t { without_downcast }; - -namespace detail -{ - -// forward declarations - class extension_instance; - class extension_class_base; - template class instance_holder; - template class instance_value_holder; - template class instance_ptr_holder; - template struct operand_select; - template struct choose_op; - template struct choose_rop; - template struct choose_unary_op; - template struct define_operator; - - class BOOST_PYTHON_DECL extension_instance : public instance - { - public: - extension_instance(PyTypeObject* class_); - ~extension_instance(); - - void add_implementation(std::auto_ptr holder); - - typedef std::vector held_objects; - const held_objects& wrapped_objects() const - { return m_wrapped_objects; } - private: - held_objects m_wrapped_objects; - }; - -} // namespace detail - -# ifndef BOOST_PYTHON_NO_TEMPLATE_EXPORT -BOOST_PYTHON_EXPORT_TEMPLATE_CLASS class_t; -BOOST_PYTHON_EXPORT_TEMPLATE_CLASS meta_class; -# endif - -namespace detail { - -BOOST_PYTHON_DECL meta_class* extension_meta_class(); -BOOST_PYTHON_DECL extension_instance* get_extension_instance(PyObject* p); -BOOST_PYTHON_DECL void report_missing_instance_data(extension_instance*, class_t*, const std::type_info&); -BOOST_PYTHON_DECL void report_missing_ptr_data(extension_instance*, class_t*, const std::type_info&); -BOOST_PYTHON_DECL void report_missing_class_object(const std::type_info&); -BOOST_PYTHON_DECL void report_released_smart_pointer(const std::type_info&); - -template -T* check_non_null(T* p) -{ - if (p == 0) - report_released_smart_pointer(typeid(T)); - return p; -} - -template class held_instance; - -typedef void* (*conversion_function_ptr)(void*); - -struct BOOST_PYTHON_DECL base_class_info -{ - base_class_info(extension_class_base* t, conversion_function_ptr f) - :class_object(t), convert(f) - {} - - extension_class_base* class_object; - conversion_function_ptr convert; -}; - -typedef base_class_info derived_class_info; - -struct add_operator_base; - -class BOOST_PYTHON_DECL extension_class_base : public class_t -{ - public: - extension_class_base(const char* name); - - public: - // the purpose of try_class_conversions() and its related functions - // is explained in extclass.cpp - void* try_class_conversions(instance_holder_base*) const; - void* try_base_class_conversions(instance_holder_base*) const; - void* try_derived_class_conversions(instance_holder_base*) const; - - void set_attribute(const char* name, PyObject* x); - void set_attribute(const char* name, ref x); - - private: - virtual void* extract_object_from_holder(instance_holder_base* v) const = 0; - virtual std::vector const& base_classes() const = 0; - virtual std::vector const& derived_classes() const = 0; - - protected: - friend struct add_operator_base; - void add_method(reference method, const char* name); - void add_method(function* method, const char* name); - - void add_constructor_object(function*); - void add_setter_method(function*, const char* name); - void add_getter_method(function*, const char* name); -}; - -template -class class_registry -{ - public: - static extension_class_base* class_object() - { return static_class_object; } - - // Register/unregister the Python class object corresponding to T - static void register_class(extension_class_base*); - static void unregister_class(extension_class_base*); - - // Establish C++ inheritance relationships - static void register_base_class(base_class_info const&); - static void register_derived_class(derived_class_info const&); - - // Query the C++ inheritance relationships - static std::vector const& base_classes(); - static std::vector const& derived_classes(); - private: - static extension_class_base* static_class_object; - static std::vector static_base_class_info; - static std::vector static_derived_class_info; -}; - -template -struct is_null_helper -{ - template - static bool test(Ptr x) { return x == 0; } -}; - -template <> -struct is_null_helper -{ - template - static bool test(const Ptr& x) { return x.get() == 0; } -}; - -template -bool is_null(const Ptr& x) -{ - return is_null_helper<(is_pointer::value)>::test(x); -} - -}}} // namespace boost::python::detail - -BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE - -// This class' only job is to define from_python and to_python converters for T -// and U. T is the class the user really intends to wrap. U is a class derived -// from T with some virtual function overriding boilerplate, or if there are no -// virtual functions, U = held_instance. -// -// A look-alike of this class in root/boost/python/cross_module.hpp -// is used for the implementation of the cross-module support -// (export_converters and import_converters). If from_python -// and to_python converters are added or removed from the class -// below, the class python_import_extension_class_converters has -// to be modified accordingly. -// -template > -class python_extension_class_converters -{ - public: - // Get an object which can be used to convert T to/from python. This is used - // as a kind of concept check by the global template - // - // PyObject* to_python(const T& x) - // - // below this class, to prevent the confusing messages that would otherwise - // pop up. Now, if T hasn't been wrapped as an extension class, the user - // will see an error message about the lack of an eligible - // py_extension_class_converters() function. - friend python_extension_class_converters py_extension_class_converters(boost::python::type) - { - return python_extension_class_converters(); - } - - // This is a member function because in a conforming implementation, friend - // funcitons defined inline in the class body are all instantiated as soon - // as the enclosing class is instantiated. If T is not copyable, that causes - // a compiler error. Instead, we access this function through the global - // template - // - // PyObject* to_python(const T& x) - // - // defined below this class. Since template functions are instantiated only - // on demand, errors will be avoided unless T is noncopyable and the user - // writes code which causes us to try to copy a T. - PyObject* to_python(const T& x) const - { - boost::python::reference result(create_instance()); - result->add_implementation( - std::auto_ptr( - new boost::python::detail::instance_value_holder(result.get(), x))); - return result.release(); - } - - friend - T* non_null_from_python(PyObject* obj, boost::python::type) - { - // downcast to an extension_instance, then find the actual T - boost::python::detail::extension_instance* self = boost::python::detail::get_extension_instance(obj); - typedef std::vector::const_iterator iterator; - for (iterator p = self->wrapped_objects().begin(); - p != self->wrapped_objects().end(); ++p) - { - boost::python::detail::instance_holder* held = dynamic_cast*>(*p); - if (held != 0) - return held->target(); - - // see extclass.cpp for an explanation of try_class_conversions() - void* target = boost::python::detail::class_registry::class_object()->try_class_conversions(*p); - if(target) - return static_cast(target); - } - boost::python::detail::report_missing_instance_data(self, boost::python::detail::class_registry::class_object(), typeid(T)); - boost::python::throw_argument_error(); -#if defined(__MWERKS__) && __MWERKS__ <= 0x2406 - return 0; -#endif - } - - // Convert to T* - friend T* from_python(PyObject* obj, boost::python::type) - { - if (obj == Py_None) - return 0; - else - return non_null_from_python(obj, boost::python::type()); - } - - // Extract from obj a mutable reference to the PtrType object which is holding a T. - template - static PtrType& smart_ptr_reference(PyObject* obj, boost::python::type) - { - // downcast to an extension_instance, then find the actual T - boost::python::detail::extension_instance* self = boost::python::detail::get_extension_instance(obj); - typedef std::vector::const_iterator iterator; - for (iterator p = self->wrapped_objects().begin(); - p != self->wrapped_objects().end(); ++p) - { - boost::python::detail::instance_ptr_holder* held = - dynamic_cast*>(*p); - if (held != 0) - return held->ptr(); - } - boost::python::detail::report_missing_ptr_data(self, boost::python::detail::class_registry::class_object(), typeid(T)); - boost::python::throw_argument_error(); -#if defined(__MWERKS__) && __MWERKS__ <= 0x2406 - return *(PtrType*)0; -#endif - } - - // Extract from obj a reference to the PtrType object which is holding a - // T. If it weren't for auto_ptr, it would be a constant reference. Do not - // modify the referent except by copying an auto_ptr! If obj is None, the - // reference denotes a default-constructed PtrType - template - static PtrType& smart_ptr_value(PyObject* obj, boost::python::type) - { - if (obj == Py_None) - { - static PtrType null_ptr; - return null_ptr; - } - return smart_ptr_reference(obj, boost::python::type()); - } - - template - static PyObject* smart_ptr_to_python(PtrType x) - { - if (boost::python::detail::is_null(x)) - { - return boost::python::detail::none(); - } - - boost::python::reference result(create_instance()); - result->add_implementation( - std::auto_ptr( - new boost::python::detail::instance_ptr_holder(x))); - return result.release(); - } - - static boost::python::reference create_instance() - { - PyTypeObject* class_object = boost::python::detail::class_registry::class_object(); - if (class_object == 0) - boost::python::detail::report_missing_class_object(typeid(T)); - - return boost::python::reference( - new boost::python::detail::extension_instance(class_object)); - } - - // Convert to const T* - friend const T* from_python(PyObject* p, boost::python::type) - { return from_python(p, boost::python::type()); } - - // Convert to const T* const& - friend const T* from_python(PyObject* p, boost::python::type) - { return from_python(p, boost::python::type()); } - - // Convert to T* const& - friend T* from_python(PyObject* p, boost::python::type) - { return from_python(p, boost::python::type()); } - - // Convert to T& - friend T& from_python(PyObject* p, boost::python::type) - { return *boost::python::detail::check_non_null(non_null_from_python(p, boost::python::type())); } - - // Convert to const T& - friend const T& from_python(PyObject* p, boost::python::type) - { return from_python(p, boost::python::type()); } - - // Convert to T - friend const T& from_python(PyObject* p, boost::python::type) - { return from_python(p, boost::python::type()); } - - friend std::auto_ptr& from_python(PyObject* p, boost::python::type&>) - { return smart_ptr_reference(p, boost::python::type >()); } - - friend std::auto_ptr from_python(PyObject* p, boost::python::type >) - { return smart_ptr_value(p, boost::python::type >()); } - - friend const std::auto_ptr& from_python(PyObject* p, boost::python::type&>) - { return smart_ptr_value(p, boost::python::type >()); } - - friend PyObject* to_python(std::auto_ptr x) - { return smart_ptr_to_python(x); } - - friend boost::shared_ptr& from_python(PyObject* p, boost::python::type&>) - { return smart_ptr_reference(p, boost::python::type >()); } - - friend const boost::shared_ptr& from_python(PyObject* p, boost::python::type >) - { return smart_ptr_value(p, boost::python::type >()); } - - friend const boost::shared_ptr& from_python(PyObject* p, boost::python::type&>) - { return smart_ptr_value(p, boost::python::type >()); } - - friend PyObject* to_python(boost::shared_ptr x) - { return smart_ptr_to_python(x); } -}; - -// Convert T to_python, instantiated on demand and only if there isn't a -// non-template overload for this function. This version is the one invoked when -// T is a wrapped class. See the first 2 functions declared in -// python_extension_class_converters above for more info. -template -PyObject* to_python(const T& x) -{ - return py_extension_class_converters(boost::python::type()).to_python(x); -} - -BOOST_PYTHON_END_CONVERSION_NAMESPACE - -namespace boost { namespace python { - -BOOST_PYTHON_IMPORT_CONVERSION(python_extension_class_converters); - -namespace detail { - -template class instance_holder; - -class BOOST_PYTHON_DECL read_only_setattr_function : public function -{ - public: - read_only_setattr_function(const char* name); - PyObject* do_call(PyObject* args, PyObject* keywords) const; - const char* description() const; - private: - string m_name; -}; - - template - struct define_conversion - { - static void* upcast_ptr(void* v) - { - return static_cast(static_cast(v)); - } - - static void* downcast_ptr(void* v) - { - return dynamic_cast(static_cast(v)); - } - }; - -// An easy way to make an extension base class which wraps T. Note that Python -// subclasses of this class will simply be class_t objects. -// -// U should be a class derived from T which overrides virtual functions with -// boilerplate code to call back into Python. See extclass_demo.h for examples. -// -// U is optional, but you won't be able to override any member functions in -// Python which are called from C++ if you don't supply it. If you just want to -// be able to use T in python without overriding member functions, you can omit -// U. -template > -class extension_class - : public python_extension_class_converters, // This generates the to_python/from_python functions - public extension_class_base -{ - public: - typedef T wrapped_type; - typedef U callback_type; - - // Construct with a name that comes from typeid(T).name(). The name only - // affects the objects of this class are represented through repr() - extension_class(); - - // Construct with the given name. The name only affects the objects of this - // class are represented through repr() - extension_class(const char* name); - - ~extension_class(); - - // define constructors -""" % args - + gen_function( -""" template <%(class A%n%:, %)> - inline void def(constructor<%(A%n%:, %)>) - // The following incantation builds a signature1, signature2,... object. It - // should _all_ get optimized away. - { add_constructor( - %(prepend(type::id(), - %) signature0()%()%)); - } -""", args) - + -""" - - // export homogeneous operators (type of both lhs and rhs is 'operator') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>()); - - // export homogeneous operators (type of both lhs and rhs is 'T const&') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>()); - template - inline void def(operators) - { - typedef typename operand_select::template wrapped::type true_operand; - def_operators(operators()); - } - - // export heterogeneous operators (type of lhs: 'left', of rhs: 'right') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>(), - // boost::python::right_operand()); - - // export heterogeneous operators (type of lhs: 'T const&', of rhs: 'right') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>(), - // boost::python::right_operand()); - template - inline void def(operators, right_operand r) - { - typedef typename operand_select::template wrapped::type true_left; - def_operators(operators(), r); - } - - // export heterogeneous reverse-argument operators - // (type of lhs: 'left', of rhs: 'right') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub), Foo>(), - // boost::python::left_operand()); - - // export heterogeneous reverse-argument operators - // (type of lhs: 'left', of rhs: 'T const&') - // usage: foo_class.def(boost::python::operators<(boost::python::op_add | boost::python::op_sub)>(), - // boost::python::left_operand()); - template - inline void def(operators, left_operand l) - { - typedef typename operand_select::template wrapped::type true_right; - def_operators(operators(), l); - } - - // define a function that passes Python arguments and keywords - // to C++ verbatim (as a 'tuple const&' and 'dictionary const&' - // respectively). This is useful for manual argument passing. - // It's also the only possibility to pass keyword arguments to C++. - // Fn must have a signatur that is compatible to - // PyObject* (*)(PyObject* aTuple, PyObject* aDictionary) - template - inline void def_raw(Fn fn, const char* name) - { - this->add_method(new_raw_arguments_function(fn), name); - } - - // define member functions. In fact this works for free functions, too - - // they act like static member functions, or if they start with the - // appropriate self argument (as a pointer), they can be used just like - // ordinary member functions -- just like Python! - template - inline void def(Fn fn, const char* name) - { - this->add_method(new_wrapped_function(fn), name); - } - - // Define a virtual member function with a default implementation. - // default_fn should be a function which provides the default implementation. - // Be careful that default_fn does not in fact call fn virtually! - template - inline void def(Fn fn, const char* name, DefaultFn default_fn) - { - this->add_method(new_virtual_function(type(), fn, default_fn), name); - } - - // Provide a function which implements x., reading from the given - // member (pm) of the T obj - template - inline void def_getter(MemberType T::*pm, const char* name) - { - this->add_getter_method(new getter_function(pm), name); - } - - // Provide a function which implements assignment to x., writing to - // the given member (pm) of the T obj - template - inline void def_setter(MemberType T::*pm, const char* name) - { - this->add_setter_method(new setter_function(pm), name); - } - - // Expose the given member (pm) of the T obj as a read-only attribute - template - inline void def_readonly(MemberType T::*pm, const char* name) - { - this->add_setter_method(new read_only_setattr_function(name), name); - this->def_getter(pm, name); - } - - // Expose the given member (pm) of the T obj as a read/write attribute - template - inline void def_read_write(MemberType T::*pm, const char* name) - { - this->def_getter(pm, name); - this->def_setter(pm, name); - } - - // define the standard coercion needed for operator overloading - void def_standard_coerce(); - - // declare the given class a base class of this one and register - // up and down conversion functions - template - void declare_base(extension_class* base) - { - // see extclass.cpp for an explanation of why we need to register - // conversion functions - base_class_info baseInfo(base, - &define_conversion::downcast_ptr); - class_registry::register_base_class(baseInfo); - add_base(ref(as_object(base), ref::increment_count)); - - derived_class_info derivedInfo(this, - &define_conversion::upcast_ptr); - class_registry::register_derived_class(derivedInfo); - } - - // declare the given class a base class of this one and register - // only up conversion function - template - void declare_base(extension_class* base, without_downcast_t) - { - // see extclass.cpp for an explanation of why we need to register - // conversion functions - base_class_info baseInfo(base, 0); - class_registry::register_base_class(baseInfo); - add_base(ref(as_object(base), ref::increment_count)); - - derived_class_info derivedInfo(this, - &define_conversion::upcast_ptr); - class_registry::register_derived_class(derivedInfo); - } - - private: // types - typedef instance_value_holder holder; - - private: // extension_class_base virtual function implementations - std::vector const& base_classes() const; - std::vector const& derived_classes() const; - void* extract_object_from_holder(instance_holder_base* v) const; - - private: // Utility functions - template - inline void def_operators(operators) - { - def_standard_coerce(); - - // for some strange reason, this prevents MSVC from having an - // "unrecoverable block scoping error"! - typedef choose_op<(which & op_add)> choose_add; - - choose_op<(which & op_add)>::template args::add(this); - choose_op<(which & op_sub)>::template args::add(this); - choose_op<(which & op_mul)>::template args::add(this); - choose_op<(which & op_div)>::template args::add(this); - choose_op<(which & op_mod)>::template args::add(this); - choose_op<(which & op_divmod)>::template args::add(this); - choose_op<(which & op_pow)>::template args::add(this); - choose_op<(which & op_lshift)>::template args::add(this); - choose_op<(which & op_rshift)>::template args::add(this); - choose_op<(which & op_and)>::template args::add(this); - choose_op<(which & op_xor)>::template args::add(this); - choose_op<(which & op_or)>::template args::add(this); - choose_op<(which & op_gt)>::template args::add(this); - choose_op<(which & op_ge)>::template args::add(this); - choose_op<(which & op_lt)>::template args::add(this); - choose_op<(which & op_le)>::template args::add(this); - choose_op<(which & op_eq)>::template args::add(this); - choose_op<(which & op_ne)>::template args::add(this); - choose_unary_op<(which & op_neg)>::template args::add(this); - choose_unary_op<(which & op_pos)>::template args::add(this); - choose_unary_op<(which & op_abs)>::template args::add(this); - choose_unary_op<(which & op_invert)>::template args::add(this); - choose_unary_op<(which & op_int)>::template args::add(this); - choose_unary_op<(which & op_long)>::template args::add(this); - choose_unary_op<(which & op_float)>::template args::add(this); - choose_op<(which & op_cmp)>::template args::add(this); - choose_unary_op<(which & op_str)>::template args::add(this); - } - - template - inline void def_operators(operators, right_operand) - { - def_standard_coerce(); - - choose_op<(which & op_add)>::template args::add(this); - choose_op<(which & op_sub)>::template args::add(this); - choose_op<(which & op_mul)>::template args::add(this); - choose_op<(which & op_div)>::template args::add(this); - choose_op<(which & op_mod)>::template args::add(this); - choose_op<(which & op_divmod)>::template args::add(this); - choose_op<(which & op_pow)>::template args::add(this); - choose_op<(which & op_lshift)>::template args::add(this); - choose_op<(which & op_rshift)>::template args::add(this); - choose_op<(which & op_and)>::template args::add(this); - choose_op<(which & op_xor)>::template args::add(this); - choose_op<(which & op_or)>::template args::add(this); - choose_op<(which & op_cmp)>::template args::add(this); - choose_op<(which & op_gt)>::template args::add(this); - choose_op<(which & op_ge)>::template args::add(this); - choose_op<(which & op_lt)>::template args::add(this); - choose_op<(which & op_le)>::template args::add(this); - choose_op<(which & op_eq)>::template args::add(this); - choose_op<(which & op_ne)>::template args::add(this); - } - - template - inline void def_operators(operators, left_operand) - { - def_standard_coerce(); - - choose_rop<(which & op_add)>::template args::add(this); - choose_rop<(which & op_sub)>::template args::add(this); - choose_rop<(which & op_mul)>::template args::add(this); - choose_rop<(which & op_div)>::template args::add(this); - choose_rop<(which & op_mod)>::template args::add(this); - choose_rop<(which & op_divmod)>::template args::add(this); - choose_rop<(which & op_pow)>::template args::add(this); - choose_rop<(which & op_lshift)>::template args::add(this); - choose_rop<(which & op_rshift)>::template args::add(this); - choose_rop<(which & op_and)>::template args::add(this); - choose_rop<(which & op_xor)>::template args::add(this); - choose_rop<(which & op_or)>::template args::add(this); - choose_rop<(which & op_cmp)>::template args::add(this); - } - - template - void add_constructor(signature sig) - { - this->add_constructor_object(init_function::create(sig)); - } -}; - -// A simple wrapper over a T which allows us to use extension_class with a -// single template parameter only. See extension_class, above. -template -class held_instance : public Held -{ - // There are no member functions: we want to avoid inadvertently overriding - // any virtual functions in Held. -public:""" - + gen_functions("""%{ - template <%(class A%n%:, %)>%} - held_instance(PyObject*%(, A%n% a%n%)) : Held( - %(typename unwrap_parameter::type(a%n)%: - , %)) {}""", args) - + """ -}; - -// Abstract base class for all obj holders. Base for template class -// instance_holder<>, below. -class BOOST_PYTHON_DECL instance_holder_base -{ -public: - virtual ~instance_holder_base() {} - virtual bool held_by_value() = 0; -}; - -// Abstract base class which holds a Held, somehow. Provides a uniform way to -// get a pointer to the held object -template -class instance_holder : public instance_holder_base -{ -public: - virtual Held*target() = 0; -}; - -// Concrete class which holds a Held by way of a wrapper class Wrapper. If Held -// can be constructed with arguments (A1...An), Wrapper must have a -// corresponding constructor for arguments (PyObject*, A1...An). Wrapper is -// neccessary to implement virtual function callbacks (there must be a -// back-pointer to the actual Python object so that we can call any -// overrides). held_instance (above) is used as a default Wrapper class when -// there are no virtual functions. -template -class instance_value_holder : public instance_holder -{ -public: - Held* target() { return &m_held; } - Wrapper* value_target() { return &m_held; } - - instance_value_holder(extension_instance* p) : - m_held(p) {} - template - instance_value_holder(extension_instance* p, A1 a1) : - m_held(p, a1) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2) : - m_held(p, a1, a2) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3) : - m_held(p, a1, a2, a3) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4) : - m_held(p, a1, a2, a3, a4) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) : - m_held(p, a1, a2, a3, a4, a5) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) : - m_held(p, a1, a2, a3, a4, a5, a6) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) : - m_held(p, a1, a2, a3, a4, a5, a6, a7) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) : - m_held(p, a1, a2, a3, a4, a5, a6, a7, a8) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) : - m_held(p, a1, a2, a3, a4, a5, a6, a7, a8, a9) {} - template - instance_value_holder(extension_instance* p, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) : - m_held(p, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {} - - public: // implementation of instance_holder_base required interface - bool held_by_value() { return true; } - - private: - Wrapper m_held; -}; - -// Concrete class which holds a HeldType by way of a (possibly smart) pointer -// PtrType. By default, these are only generated for PtrType == -// std::auto_ptr and PtrType == boost::shared_ptr. -template -class instance_ptr_holder : public instance_holder -{ - public: - HeldType* target() { return &*m_ptr; } - PtrType& ptr() { return m_ptr; } - - instance_ptr_holder(PtrType ptr) : m_ptr(ptr) {} - - public: // implementation of instance_holder_base required interface - bool held_by_value() { return false; } - private: - PtrType m_ptr; -}; - -// -// Template function implementations -// - -template -extension_class::extension_class() - : extension_class_base(typeid(T).name()) -{ - class_registry::register_class(this); -} - -template -extension_class::extension_class(const char* name) - : extension_class_base(name) -{ - class_registry::register_class(this); -} - -template -void extension_class::def_standard_coerce() -{ - ref coerce_fct = dict().get_item(string("__coerce__")); - - if(coerce_fct.get() == 0) // not yet defined - this->def(&standard_coerce, "__coerce__"); -} - -template -inline -std::vector const& -extension_class::base_classes() const -{ - return class_registry::base_classes(); -} - -template -inline -std::vector const& -extension_class::derived_classes() const -{ - return class_registry::derived_classes(); -} - -template -void* extension_class::extract_object_from_holder(instance_holder_base* v) const -{ - instance_holder* held = dynamic_cast*>(v); - if(held) - return held->target(); - return 0; -} - -template -extension_class::~extension_class() -{ - class_registry::unregister_class(this); -} - -template -inline void class_registry::register_class(extension_class_base* p) -{ - // You're not expected to create more than one of these! - assert(static_class_object == 0); - static_class_object = p; -} - -template -inline void class_registry::unregister_class(extension_class_base* p) -{ - // The user should be destroying the same object they created. - assert(static_class_object == p); - (void)p; // unused in shipping version - static_class_object = 0; -} - -template -void class_registry::register_base_class(base_class_info const& i) -{ - static_base_class_info.push_back(i); -} - -template -void class_registry::register_derived_class(derived_class_info const& i) -{ - static_derived_class_info.push_back(i); -} - -template -std::vector const& class_registry::base_classes() -{ - return static_base_class_info; -} - -template -std::vector const& class_registry::derived_classes() -{ - return static_derived_class_info; -} - -// -// Static data member declaration. -// -template -extension_class_base* class_registry::static_class_object; -template -std::vector class_registry::static_base_class_info; -template -std::vector class_registry::static_derived_class_info; - -}}} // namespace boost::python::detail - -#endif // EXTENSION_CLASS_DWA052000_H_ -""") - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 5 - else: - args = int(sys.argv[1]) - - print gen_extclass(args) diff --git a/src/gen_function.py b/src/gen_function.py deleted file mode 100644 index dba53c3b..00000000 --- a/src/gen_function.py +++ /dev/null @@ -1,243 +0,0 @@ -r""" ->>> template = ''' template -... static PyObject* call( %1(T::*pmf)(%(A%+%:, %))%2, PyObject* args, PyObject* ) { -... PyObject* self; -... %( PyObject* a%+; -... %) if (!PyArg_ParseTuple(args, const_cast("O%(O%)"), &self%(, &a%+%))) -... return 0; -... T& target = from_python(self, type()); -... %3to_python((target.*pmf)(%( -... from_python(a%+, type())%:,%) -... ));%4 -... }''' - ->>> print gen_function(template, 0, 'R ', '', 'return ', '') - template - static PyObject* call( R (T::*pmf)(), PyObject* args, PyObject* ) { - PyObject* self; - if (!PyArg_ParseTuple(args, const_cast("O"), &self)) - return 0; - T& target = from_python(self, type()); - return to_python((target.*pmf)( - )); - } - ->>> print gen_function(template, 2, 'R ', '', 'return ', '') - template - static PyObject* call( R (T::*pmf)(A1, A2), PyObject* args, PyObject* ) { - PyObject* self; - PyObject* a1; - PyObject* a2; - if (!PyArg_ParseTuple(args, const_cast("OOO"), &self, &a1, &a2)) - return 0; - T& target = from_python(self, type()); - return to_python((target.*pmf)( - from_python(a1, type()), - from_python(a2, type()) - )); - } - ->>> print gen_function(template, 3, 'void ', ' const', '', '\n'+8*' ' + 'return none();') - template - static PyObject* call( void (T::*pmf)(A1, A2, A3) const, PyObject* args, PyObject* ) { - PyObject* self; - PyObject* a1; - PyObject* a2; - PyObject* a3; - if (!PyArg_ParseTuple(args, const_cast("OOOO"), &self, &a1, &a2, &a3)) - return 0; - T& target = from_python(self, type()); - to_python((target.*pmf)( - from_python(a1, type()), - from_python(a2, type()), - from_python(a3, type()) - )); - return none(); - } -""" -import string - -def _find(s, sub, start=0, end=None): - """Just like string.find, except it returns end or len(s) when not found. - """ - if end == None: - end = len(s) - - pos = string.find(s, sub, start, end) - if pos < 0: - return end - else: - return pos - -def _raise_no_argument(key, n, args): - raise IndexError(str(key) + " extra arg(s) not passed to gen_function") - -def _gen_common_key(key, n, args, fill = _raise_no_argument): - # import sys - # print >> sys.stderr, "_gen_common_key(", repr(key), ",", repr(n), ',', repr(args), ',', fill, ')' - # sys.stderr.flush() - if len(key) > 0 and key in '123456789': - index = int(key) - 1; - - if index >= len(args): - return fill(key, n, args) - - arg = args[index] - if callable(arg): - return str(arg(key, n, args)) - else: - return str(arg) - elif key in ('x','n','-','+'): - return str(n + {'-':-1,'+':+1,'x':0,'n':0}[key]) - else: - return key - -def _gen_arg(template, n, args, fill = _raise_no_argument): - - result = '' - i = 0 - while i < len(template): # until the template is consumed - # consume everything up to the first '%' - delimiter_pos = _find(template, '%', i) - result = result + template[i:delimiter_pos] - - # The start position of whatever comes after the '%'+key - start = delimiter_pos + 2 - key = template[start - 1 : start] # the key character. If there were no - # '%'s left, key will be empty - - if 0 and key == 'n': - result = result + `n` - else: - result = result + _gen_common_key(key, n, args, fill) - - i = start - - return result - -def gen_function(template, n, *args, **keywords): - r"""gen_function(template, n, [args...] ) -> string - - Generate a function declaration based on the given template. - - Sections of the template between '%(', '%)' pairs are repeated n times. If '%:' - appears in the middle, it denotes the beginning of a '%'. - - Sections of the template between '%{', '%}' pairs are ommitted if n == 0. - - %n is transformed into the string representation of 1..n for each - repetition within %(...%). Elsewhere, %n is transformed into the - string representation of n - - %- is transformed into the string representation of 0..n-1 for - each repetition within %(...%). Elsewhere, %- is transformed into the - string representation of n-1. - - %+ is transformed into the string representation of 2..n+1 for - each repetition within %(...%). Elsewhere, %- is transformed into the - string representation of n+1. - - %x is always transformed into the string representation of n - - %z, where z is a digit, selects the corresponding additional - argument. If that argument is callable, it is called with three - arguments: - key - the string representation of 'z' - n - the iteration number - args - a tuple consisting of all the additional arguments to - this function - otherwise, the selected argument is converted to a string representation - - - for example, - - >>> gen_function('%1 abc%x(%(int a%n%:, %));%{ // all args are ints%}', 2, 'void') - 'void abc2(int a0, int a1); // all args are ints' - - >>> gen_function('%1 abc(%(int a%n%:, %));%{ // all args are ints%}', 0, 'x') - 'x abc();' - - >>> gen_function('%1 abc(%(int a%n%:, %));%{ // all args are ints%}', 0, lambda key, n, args: 'abcd'[n]) - 'a abc();' - - >>> gen_function('%2 %1 abc(%(int a%n%:, %));%{ // all args are ints%}', 0, 'x', fill = lambda key, n, args: 'const') - 'const x abc();' - - >>> gen_function('abc%[k%:v%]', 0, fill = lambda key, n, args, value = None: '<' + key + ',' + value + '>') - 'abc' - -""" - expand = (lambda s, n = n: - apply(gen_function, (s, n) + args, keywords)) - - fill = keywords.get('fill', _raise_no_argument); - result = '' - i = 0 - while i < len(template): # until the template is consumed - # consume everything up to the first '%' - delimiter_pos = _find(template, '%', i) - result = result + template[i:delimiter_pos] - - # The start position of whatever comes after the '%'+key - start = delimiter_pos + 2 - key = template[start - 1 : start] # the key character. If there were no - # '%'s left, key will be empty - - pairs = { '(':')', '{':'}', '[':']' } - - if key in pairs.keys(): - end = string.find(template, '%' + pairs[key], start) - assert end >= 0, "Matching '" + '%' + pairs[key] +"' not found!" - delimiter_pos = end - - if key == '{': - if n > 0: - result = result + expand(template[start:end]) - else: - separator_pos = _find(template, '%:', start, end) - remainder = template[separator_pos+2 : end] - - if key == '(': - for x in range(n): - - iteration = expand( - template[start:separator_pos], x) - - result = result + expand(iteration, x) - - if x != n - 1: - result = result + expand(remainder, x) - else: - function_result = fill( - template[start:separator_pos], n, args, value = remainder) - result = result + expand(function_result) - - else: - result = result + expand(_gen_common_key(key, n, args, fill)) - - i = delimiter_pos + 2 - - return result - -def gen_functions(template, n, *args, **keywords): - r"""gen_functions(template, n, [args...]) -> string - - Call gen_function repeatedly with from 0..n and the given optional - arguments. - - >>> print gen_functions('%1 abc(%(int a%n%:, %));%{ // all args are ints%}\n', 2, 'void'), - void abc(); - void abc(int a0); // all args are ints - void abc(int a0, int a1); // all args are ints - - """ - fill = keywords.get('fill', _raise_no_argument); - result = '' - for x in range(n + 1): - result = result + apply(gen_function, (template, x) + args, keywords) - return result - -if __name__ == '__main__': - import doctest - import sys - doctest.testmod(sys.modules.get(__name__)) diff --git a/src/gen_init_function.py b/src/gen_init_function.py deleted file mode 100644 index 69c772c5..00000000 --- a/src/gen_init_function.py +++ /dev/null @@ -1,215 +0,0 @@ -from gen_function import * -import string - -def gen_init_function(args): - - return ( -"""// (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// This file was generated for %d-argument constructors by gen_init_function.python - -#ifndef INIT_FUNCTION_DWA052000_H_ -# define INIT_FUNCTION_DWA052000_H_ - -# include -# include -# include -# include - -namespace boost { namespace python { - -namespace detail { - - // parameter_traits - so far, this is a way to pass a const T& when we can be - // sure T is not a reference type, and a raw T otherwise. This should be - // rolled into boost::call_traits. Ordinarily, parameter_traits would be - // written: - // - // template struct parameter_traits - // { - // typedef const T& const_reference; - // }; - // - // template struct parameter_traits - // { - // typedef T& const_reference; - // }; - // - // template <> struct parameter_traits - // { - // typedef void const_reference; - // }; - // - // ...but since we can't partially specialize on reference types, we need this - // long-winded but equivalent incantation. - - // const_ref_selector -- an implementation detail of parameter_traits (below). This uses - // the usual "poor man's partial specialization" hack for MSVC. - template - struct const_ref_selector - { - template - struct const_ref - { - typedef const T& type; - }; - }; - - template <> - struct const_ref_selector - { - template - struct const_ref - { - typedef T type; - }; - }; - -# ifdef BOOST_MSVC -# pragma warning(push) -# pragma warning(disable: 4181) -# endif // BOOST_MSVC - template - struct parameter_traits - { - private: - enum { is_ref = boost::is_reference::value }; - typedef const_ref_selector selector; - public: - typedef typename selector::template const_ref::type const_reference; - }; -# ifdef BOOST_MSVC -# pragma warning(pop) -# endif // BOOST_MSVC - - // Full spcialization for void - template <> - struct parameter_traits - { - typedef void const_reference; - }; - - struct reference_parameter_base {}; - - template - class reference_parameter - : public reference_parameter_base - { - public: - typedef typename parameter_traits::const_reference const_reference; - reference_parameter(const_reference value) - : value(value) {} - operator const_reference() { return value; } - private: - const_reference value; - }; - -# ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION - template - struct unwrap_parameter - { - typedef typename boost::add_reference::type type; - }; - - template - struct unwrap_parameter > - { - typedef typename reference_parameter::const_reference type; - }; -# else - template - struct unwrap_parameter_helper - { - template - struct apply - { - typedef typename T::const_reference type; - }; - }; - - template <> - struct unwrap_parameter_helper - { - template - struct apply - { - typedef typename add_reference::type type; - }; - }; - - template - struct unwrap_parameter - { - BOOST_STATIC_CONSTANT( - bool, is_wrapped = (is_base_and_derived::value)); - - typedef typename unwrap_parameter_helper< - is_wrapped - >::template apply::type type; - }; -# endif - -class extension_instance; -class instance_holder_base; - -class init; -""" - + gen_functions('template struct init%x;\n', args) - + """ -template -struct init_function -{ -""" + gen_functions("""%{ - template <%(class A%n%:, %)> -%} static init* create(signature%x%{<%(A%n%:, %)>%}) { - return new init%x::const_reference%)>; - } -""", args)+"""}; - -class init : public function -{ -private: // override function hook - PyObject* do_call(PyObject* args, PyObject* keywords) const; -private: - virtual instance_holder_base* create_holder(extension_instance* self, PyObject* tail_args, PyObject* keywords) const = 0; -}; -""" + gen_functions(""" - -template -struct init%x : init -{ - virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const - { - %(PyObject* a%n; - %)if (!PyArg_ParseTuple(args, const_cast("%(O%)")%(, &a%n%))) - throw_argument_error(); - return new T(self%(, - boost::python::detail::reference_parameter(from_python(a%n, type()))%) - ); - } - const char* description() const - { return typeid(void (*)(T&%(, A%n%%))).name(); } -};""", args) + """ - -}}} // namespace boost::python::detail - -#endif // INIT_FUNCTION_DWA052000_H_ -""") - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 5 - else: - args = int(sys.argv[1]) - - print gen_init_function(args) - diff --git a/src/gen_py_api.py b/src/gen_py_api.py deleted file mode 100644 index bc965d8f..00000000 --- a/src/gen_py_api.py +++ /dev/null @@ -1,776 +0,0 @@ -# Copyright David Hawkes 2002. -# Permission is hereby granted to copy, use and modify this software -# for any purpose, including commercial distribution, provided this -# copyright notice is not removed. No warranty WHATSOEVER is provided with this -# software. Any user(s) accepts this software "as is" and as such they will not -# bind the author(s) to any claim of suitabilty for any purpose. - -# Build python API wrappers for boost python - -import re - -API_List = [ -'PyObject*{new} abs{direct}(int{template})', -'PyObject*{new} abs{direct}(PyObject*)', -'PyObject*{new} abs{direct}(short)', -'PyObject*{new} abs{direct}(int)', -'PyObject*{new} abs{direct}(long)', -'PyObject*{new} abs{direct}(double const &)', -'PyObject*{new,err=NULL} PyObject_CallObject{decl=apply}(PyObject*,PyObject*)', -'PyObject*{new,err=NULL} PyObject_Call{decl=apply}(PyObject*,PyObject*,PyObject*)', -'bool PyCallable_Check{decl=callable}(PyObject*)', -'PyObject*{new} chr{direct}(int{template})', -'PyObject*{new} chr{direct}(PyObject*)', -'PyObject*{new} chr{direct}(short)', -'PyObject*{new} chr{direct}(int)', -'PyObject*{new} chr{direct}(long)', -'int{err=-1} PyObject_Cmp{decl=cmp}(PyObject*{template},PyObject*{template},int{result})', -'int{err=-1} PyObject_Cmp{decl=cmp}(PyObject*,PyObject*,int{result})', -'PyObject*{new} coerce{direct}(PyObject*,PyObject*)', -'PyObject*{new} compile{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} compile{direct}(const char*,const char*,const char*)', -'PyObject*{new} compile{direct}(PyObject*,PyObject*,PyObject*,PyObject*)', -'PyObject*{new} compile{direct}(const char*,const char*,const char*,int)', -'PyObject*{new} compile{direct}(PyObject*,PyObject*,PyObject*,PyObject*,PyObject*)', -'PyObject*{new} compile{direct}(const char*,const char*,const char*,int,int)', -'PyObject*{new} complex{direct}(int{template})', -'PyObject*{new} complex{direct}(PyObject*)', -'PyObject*{new} complex{direct}(double const&)', -'PyObject*{new} complex{direct}(int{template},int{template})', -'PyObject*{new} complex{direct}(PyObject*,PyObject*)', -'PyObject*{new} complex{direct}(double const&,double const&)', -'PyObject*{new} dict{direct}()', -'PyObject*{new} dict{direct}(PyObject*)', -'PyObject*{new} PyObject_Dir{decl=dir}(PyObject*{value=NULL})', -'PyObject*{new} PyObject_Dir{decl=dir}(PyObject*)', -'PyObject*{new} divmod{direct}(int{template},int{template})', -'PyObject*{new} divmod{direct}(PyObject*,PyObject*)', -'PyObject*{new} divmod{direct}(int,int)', -'PyObject*{new} divmod{direct}(long,long)', -'PyObject*{new} divmod{direct}(double const&,double const&)', -'PyObject*{new} PyRun_String{decl=eval}(char*{const},int{value=Py_eval_input},PyObject*{value=globals().ptr()},PyObject*{value=globals().ptr()})', -'PyObject*{new} PyRun_String{decl=eval}(char*{const},int{value=Py_eval_input},PyObject*,PyObject*{value=globals().ptr()})', -'PyObject*{new} PyRun_String{decl=eval}(char*{const},int{value=Py_eval_input},PyObject*,PyObject*)', -'PyObject*{new} PyRun_String{decl=exec}(char*{const},int{value=Py_file_input},PyObject*{value=globals().ptr()},PyObject*{value=globals().ptr()})', -'PyObject*{new} PyRun_String{decl=exec}(char*{const},int{value=Py_file_input},PyObject*,PyObject*{value=globals().ptr()})', -'PyObject*{new} PyRun_String{decl=exec}(char*{const},int{value=Py_file_input},PyObject*,PyObject*)', -'PyObject*{new} execfile{direct}(PyObject*)', -'PyObject*{new} execfile{direct}(PyObject*,PyObject*)', -'PyObject*{new} execfile{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} file{direct}(PyObject*)', -'PyObject*{new} file{direct}(const char*)', -'PyObject*{new} file{direct}(PyObject*,PyObject*)', -'PyObject*{new} file{direct}(const char*,const char*)', -'PyObject*{new} file{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} file{direct}(const char*,const char*,int)', -'PyObject*{new} filter{direct}(PyObject*,PyObject*)', -'PyObject*{new} float{direct,decl=float_}(PyObject*)', -'PyObject*{new} float{direct,decl=float_}(const char*)', -'PyObject*{new} float{direct,decl=float_}(double const&)', -'PyObject*{new} getattr{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} getattr{direct}(PyObject*,const char *,PyObject*)', -'PyObject*{borrowed,err=NULL} PyModule_GetDict{decl=globals}(PyObject*{value=PyImport_AddModule("__main__")})', -'bool PyObject_HasAttr{decl=hasattr}(PyObject*,PyObject*)', -'bool PyObject_HasAttrString{decl=hasattr}(PyObject*,char*{const})', -'long{err=-1} PyObject_Hash{decl=hash}(PyObject*)', -'PyObject*{new} hex{direct}(int{template})', -'PyObject*{new} hex{direct}(PyObject*)', -'PyObject*{new} hex{direct}(char)', -'PyObject*{new} hex{direct}(short)', -'PyObject*{new} hex{direct}(int)', -'PyObject*{new} hex{direct}(long)', -'long id{direct}(PyObject*)', -'PyObject*{new} input{direct}()', -'PyObject*{new} input{direct}(PyObject*)', -'PyObject*{new} input{direct}(const char*)', -'PyObject*{new} int{direct,decl=int_}(PyObject*)', -'PyObject*{new} int{direct,decl=int_}(long)', -'PyObject*{new} int{direct,decl=int_}(const char*)', -'PyObject*{new} intern{direct}(PyObject*)', -'PyObject*{new} intern{direct}(const char*)', -'bool PyObject_IsInstance{decl=isinstance}(PyObject*,PyObject*)', -'bool PyObject_IsSubclass{decl=issubclass}(PyObject*,PyObject*)', -'PyObject*{new} PyObject_GetIter{decl=iter}(PyObject*)', -'PyObject*{new} iter{direct}(PyObject*,PyObject*)', -'long{err=-1} PyObject_Length{decl=len}(PyObject*)', -'PyObject*{new} list{direct}()', -'PyObject*{new} list{direct}(PyObject*)', -'PyObject*{new} long{direct,decl=long_}(PyObject*)', -'PyObject*{new} long{direct,decl=long_}(long)', -'PyObject*{new} long{direct,decl=long_}(const char*)', -'PyObject*{new} map{direct,argrepeat}(PyObject*)', -'PyObject*{new} max{direct,argrepeat}(PyObject*{template})', -'PyObject*{new} max{direct,argrepeat}(PyObject*)', -'PyObject*{new} min{direct,argrepeat}(PyObject*{template})', -'PyObject*{new} min{direct,argrepeat}(PyObject*)', -'PyObject*{new} oct{direct}(int{template})', -'PyObject*{new} oct{direct}(PyObject*)', -'PyObject*{new} oct{direct}(char)', -'PyObject*{new} oct{direct}(short)', -'PyObject*{new} oct{direct}(int)', -'PyObject*{new} oct{direct}(long)', -'PyObject*{new} open{direct}(PyObject*)', -'PyObject*{new} open{direct}(const char*)', -'PyObject*{new} open{direct}(PyObject*,PyObject*)', -'PyObject*{new} open{direct}(const char*,const char*)', -'PyObject*{new} open{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} open{direct}(const char*,const char*,int)', -'long ord{direct}(PyObject*)', -'long ord{direct}(const char*)', -'PyObject*{new} pow{direct}(int{template},int{template})', -'PyObject*{new} pow{direct}(PyObject*,PyObject*)', -'PyObject*{new} pow{direct}(double const&,double const&)', -'PyObject*{new} pow{direct}(double const&,double const&,double const&)', -'PyObject*{new} print{direct,statement=print _1,argrepeat}(int{template})', -'PyObject*{new} print{direct,statement=print _1,argrepeat}(PyObject*)', -'PyObject*{new} print{decl=print_file,direct,statement="print >>_1, _2",argrepeat}(PyObject*,int{template})', -'PyObject*{new} print{decl=print_file,direct,statement="print >>_1, _2",argrepeat}(PyObject*,PyObject*)', -'PyObject*{new} range{direct}(int{template})', -'PyObject*{new} range{direct}(PyObject*)', -'PyObject*{new} range{direct}(int)', -'PyObject*{new} range{direct}(int{template},int{template})', -'PyObject*{new} range{direct}(PyObject*,PyObject*)', -'PyObject*{new} range{direct}(int,int)', -'PyObject*{new} range{direct}(int{template},int{template},int{template})', -'PyObject*{new} range{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} range{direct}(int,int,int)', -'PyObject*{new} raw_input{direct}()', -'PyObject*{new} raw_input{direct}(PyObject*)', -'PyObject*{new} raw_input{direct}(const char*)', -'PyObject*{new} reduce{direct}(PyObject*,PyObject*)', -'PyObject*{new} reduce{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new,err=NULL} PyImport_ReloadModule{decl=reload}(PyObject*)', -'PyObject*{new} PyObject_Repr{decl=repr}(PyObject*)', -'PyObject*{new} round{direct}(int{template})', -'PyObject*{new} round{direct}(PyObject*)', -'PyObject*{new} round{direct}(double const&)', -'PyObject*{new} round{direct}(int{template},int{template})', -'PyObject*{new} round{direct}(PyObject*,PyObject*)', -'PyObject*{new} round{direct}(double const&,double const&)', -'PyObject*{new} slice{direct}(int{template})', -'PyObject*{new} slice{direct}(PyObject*)', -'PyObject*{new} slice{direct}(int)', -'PyObject*{new} slice{direct}(int{template},int{template})', -'PyObject*{new} slice{direct}(PyObject*,PyObject*)', -'PyObject*{new} slice{direct}(int,int)', -'PyObject*{new} slice{direct}(int{template},int{template},int{template})', -'PyObject*{new} slice{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} slice{direct}(int,int,int)', -'PyObject*{new} PyObject_Str{decl=str}(PyObject*)', -'PyObject*{new} tuple{direct}()', -'PyObject*{new} tuple{direct}(PyObject*)', -'PyObject*{new,err=NULL} PyObject_Type{decl=type_}(PyObject*)', -'PyObject*{new} unichr{direct}(int{template})', -'PyObject*{new} unichr{direct}(PyObject*)', -'PyObject*{new} unichr{direct}(short)', -'PyObject*{new} unichr{direct}(int)', -'PyObject*{new} unichr{direct}(long)', -'PyObject*{new} PyObject_Unicode{decl=unicode}(PyObject*)', -'PyObject*{new} unicode{direct}(PyObject*,PyObject*)', -'PyObject*{new} unicode{direct}(PyObject*,const char*)', -'PyObject*{new} unicode{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} unicode{direct}(PyObject*,const char*,const char*)', -'PyObject*{new} vars{direct}()', -'PyObject*{new} vars{direct}(PyObject*)', -'PyObject*{new} xrange{direct}(int{template})', -'PyObject*{new} xrange{direct}(PyObject*)', -'PyObject*{new} xrange{direct}(int)', -'PyObject*{new} xrange{direct}(int{template},int{template})', -'PyObject*{new} xrange{direct}(PyObject*,PyObject*)', -'PyObject*{new} xrange{direct}(int,int)', -'PyObject*{new} xrange{direct}(int{template},int{template},int{template})', -'PyObject*{new} xrange{direct}(PyObject*,PyObject*,PyObject*)', -'PyObject*{new} xrange{direct}(int,int,int)', -'PyObject*{new} zip{direct,argrepeat}(PyObject*)', -'PyObject*{new,err=NULL} Py_CompileString{decl=compile_string}(char*{const},char*{const},int)', -'int{err=-1} PyImport_AppendInittab{decl=import_append_inittab}(char*{const},void(*arg)(void))', -'PyObject*{borrowed,err=NULL} PyImport_AddModule{decl=import_add_module}(char*{const})', -'PyObject*{borrowed,err=NULL} PyImport_GetModuleDict{decl=import_get_module_dict}()', -'PyObject*{new,err=NULL} PyImport_Import{decl=import_import}(PyObject*)', -'PyObject*{new,err=NULL} PyImport_Import{decl=import_import}(const char*{object})', -'PyObject*{new,err=NULL} PyImport_ImportModule{decl=import_import_module}(char*{const})', -'PyObject*{new,err=NULL} PyImport_ImportModuleEx{decl=import_import_module_ex}(char*{const},PyObject*,PyObject*,PyObject*)', -'PyObject*{borrowed,err=NULL} PyModule_GetDict{decl=module_get_dict}(PyObject*)', -'int{err=-1} PyObject_Print{decl=object_print}(PyObject*,FILE*,int)', -'PyObject*{new,err=NULL} PyRun_File{decl=run_file}(FILE*,char*{const},int,PyObject*,PyObject*)', -'int{err=-1} PyRun_SimpleFile{decl=run_simple_file}(FILE*,char*{const})', -'int{err=-1} PyRun_SimpleString{decl=run_simple_string}(char*{const})', -'PyObject*{new,err=NULL} PyRun_String{decl=run_string}(char*{const},int,PyObject*,PyObject*)', -'PyObject*{new} call_statement{statement,direct}(const char*{statement})', -'PyObject*{new} call_statement{statement,direct}(const char*{statement},call_dict_usage{use_gd})', -'PyObject*{new} call_statement{argrepeat,statement,direct}(const char*{statement},int{template})', -'PyObject*{new} call_statement{argrepeat,statement,direct}(const char*{statement},PyObject*)', -'PyObject*{new} call_statement{argrepeat,statement,direct}(const char*{statement},call_dict_usage{use_gd},int{template})', -'PyObject*{new} call_statement{argrepeat,statement,direct}(const char*{statement},call_dict_usage{use_gd},PyObject*)', -] - -DeclFile = '../../../boost/python/py_interface.hpp' -ImplFile = 'py_interface.cpp' - -DeclFileHeader = '''\ -// Automatically generated from py_api_gen.py -#ifndef PY_INTERFACE_HPP -#define PY_INTERFACE_HPP - -#include -#include - -namespace boost { namespace python { namespace api { - -enum call_dict_usage { use_new_dict, use_local_dict, use_global_dict }; - -namespace api_detail { - -BOOST_PYTHON_DECL object get_func(const char* name); -BOOST_PYTHON_DECL object call_statement(const char *stmt, int n, ...); -BOOST_PYTHON_DECL object call_statement_du(const char *stmt, call_dict_usage cdu, int n, ...); - -template -struct get_arg -{ - get_arg(A const &a) : h(a) {} - object h; - operator object const& () { return h; } - operator object const* () { return &h; } -}; - -template<> -struct get_arg -{ - get_arg(object const &a) : h(a) {} - object const &h; - operator object const& () { return h; } - operator object const* () { return &h; } -}; - -template<> -struct get_arg -{ - get_arg(PyObject* a) : h((python::detail::borrowed_reference)a) {} - object h; - operator object const& () { return h; } - operator object const* () { return &h; } -}; - -} - -BOOST_PYTHON_DECL object locals(); - -''' - -DeclFileTrailer = '''\ -}}} - -#endif // PY_INTERFACE_HPP -''' - -ImplFileHeader = '''\ -// Automatically generated from py_api_gen.py - -#include - -namespace boost { namespace python { namespace api { - -namespace api_detail { - -BOOST_PYTHON_DECL object get_func(const char* name) { - object __builtin__((python::detail::borrowed_reference)::PyImport_AddModule(const_cast("__builtin__"))); - return object(__builtin__.attr(name)); -} - -inline handle<> get_current_frame() -{ - return handle<>(allow_null(borrowed((PyObject*)(PyThreadState_Get()->frame)))); -} - -inline object get_global_dict(call_dict_usage cdu, handle<> const& frame) -{ - if(frame.get()) - return object(object(frame).attr("f_globals")); - else - return api::globals(); -} - -object get_local_dict(call_dict_usage cdu, handle<> const& frame, object const& global_dict) -{ - switch(cdu) { - case use_new_dict: - return api::dict(); - case use_global_dict: - return global_dict; - default: - if(frame.get()) - return object(object(frame).attr("f_locals")); - else - return api::dict(); - } -} - -inline object call_statement(const char *stmt, object const& global_dict, object& local_dict) -{ - local_dict["_0"] = object((python::detail::borrowed_reference)Py_None); - api::run_string(stmt, Py_file_input, global_dict, local_dict); - return object(local_dict["_0"]); -} - -object call_statement(const char *stmt) -{ - handle<> frame(get_current_frame()); - if(frame.get()) { - object f(frame); - object gd(f.attr("f_globals")); - object ld(f.attr("f_locals")); - return call_statement(stmt, gd, ld); - } else { - object gd(api::globals()); - object ld(api::dict()); - return call_statement(stmt, gd, ld); - } -} - -object call_statement_du(const char *stmt, call_dict_usage cdu) -{ - handle<> frame(get_current_frame()); - object gd(get_global_dict(cdu, frame)); - return call_statement(stmt, gd, get_local_dict(cdu, frame, gd)); -} - -inline object call_statement(const char *stmt, object const& global_dict, object& local_dict, int n, va_list mk) -{ - static const char *(idx[]) = { "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9", "_10" }; - local_dict["_0"] = object((python::detail::borrowed_reference)Py_None); - for(int i = 0; i < n; ++i) - { - object const* p_arg = va_arg(mk, object const*); - object const& arg = *p_arg; - if(i < (int) (sizeof(idx) / sizeof(idx[0]))) - local_dict[idx[i]] = arg; - else { - local_dict[object("_") + object((python::detail::new_reference)PyObject_Str(object(i + 1).ptr()))] = arg; - } - } - va_end(mk); - api::run_string(stmt, Py_file_input, global_dict, local_dict); - return object(local_dict["_0"]); -} - -BOOST_PYTHON_DECL object call_statement(const char *stmt, int n, ...) -{ - va_list mk; - va_start(mk, n); - handle<> frame(get_current_frame()); - if(frame.get()) { - object f(frame); - object gd(f.attr("f_globals")); - object ld(f.attr("f_locals")); - return call_statement(stmt, gd, ld, n, mk); - } else { - object gd(api::globals()); - object ld(api::dict()); - return call_statement(stmt, gd, ld, n, mk); - } -} - -BOOST_PYTHON_DECL object call_statement_du(const char *stmt, call_dict_usage cdu, int n, ...) -{ - handle<> frame(get_current_frame()); - object gd(get_global_dict(cdu, frame)); - va_list mk; - va_start(mk, n); - return call_statement(stmt, gd, get_local_dict(cdu, frame, gd), n, mk); -} - -} - -BOOST_PYTHON_DECL object locals() -{ - handle<> frame(api_detail::get_current_frame()); - if(frame.get()) - return object(object(frame).attr("f_locals")); - else - return api::dict(); -} - -''' - -ImplFileTrailer = '''\ -}}} -''' - -def SplitOutList(l): - vals_list = [] - if l == None: - return vals_list - vals_list = re.findall(r'((?:[^,{}]|(?:{[^{}]*}))+),?\s*', l) - return vals_list - -def SplitOutListDict(l): - vals_dict = {} - if l == None: - return vals_dict - vals = re.findall(r'((?:"[^"]+"|[^,"]+)+)\s*,?', l) - for val in vals: - m = re.match(r'(?P[^\s=]+)\s*(=\s*(?P"?)(?P.+)(?P=qt))?', val).groupdict() - vals_dict[m['aname']] = m['aval'] - return vals_dict - -def SplitOutAttrs(a): - soa = {} - m = re.match(r'(?P[^{]+)({(?P[^}]+)})?', a).groupdict() - soa['name'] = m['name'] - soa.update(SplitOutListDict(m['attrs'])) - return soa - -def is_object(name): - if re.match(r'PyObject\s*\*', name['name']): - return 1 - return 0 - -def is_arg_really_const(arg): - return arg.has_key('const') - -def get_actual_rtn_type(rtn, args): - i = 0 - for a in args: - if a.has_key('result'): - true_rtn = dict(rtn) - true_rtn['name'] = a['name'] - true_rtn['arg_number'] = i - return true_rtn - i += 1 - return rtn - -def is_template(name): - return name.has_key('template') - -def decl_func_arg(arg, p): - if arg.has_key('value'): - return '' - elif arg.has_key('result'): - return '' - elif is_object(arg): - if is_template(arg): - sn = str(p) - return 'A' + sn +' const& a' + sn - else: - return 'object const& a' + str(p) - elif is_arg_really_const(arg): - return 'const ' + arg['name'] + ' a' + str(p) - elif re.search(r'arg', arg['name']): - return re.sub(r'arg', 'a' + str(p), arg['name']) - else: - if is_template(arg): - sn = str(p) - return 'A' + sn +' const& a' + sn - else: - return arg['name'] + ' a' + str(p) - -def decl_func_args(name, args): - if not len(args): - return '' - d_args = reduce(lambda x,y : x + (y and (', ' + y) or ''), map(decl_func_arg, args, xrange(len(args)))) - return d_args - -def call_func_arg(arg, p): - if arg.has_key('value'): - return arg['value'] - elif arg.has_key('result'): - return '&rslt' - elif arg.has_key('template'): - sn = str(p) - return 'api_detail::get_arg(a%s)' % (sn, sn) - elif arg.has_key('object'): - return 'object(a%s).ptr()' % str(p) - elif is_object(arg): - return 'a' + str(p) + '.ptr()' - elif is_arg_really_const(arg): - return 'const_cast<%s>(%s)' % (arg['name'], 'a' + str(p)) - else: - return 'a' + str(p) - -def call_func_args(args): - if not len(args): - return '' - d_args = reduce(lambda x,y : x + (y and ((x and ', ' or '') + y) or ''), map(call_func_arg, args, xrange(len(args)))) - return d_args - -def call_func(name, args): - return '::%s(%s)' % (name['name'], call_func_args(args)) - -def call_func_direct_arg(arg, p): - if arg.has_key('use_gd'): - return '' - elif arg.has_key('statement'): - return '' - elif arg.has_key('value'): - return arg['value'] - elif arg.has_key('template'): - sn = str(p) - if arg.has_key('addr'): - return '(object const*)api_detail::get_arg(a%s)' % (sn, sn) - else: - return 'api_detail::get_arg(a%s)' % (sn, sn) - elif is_object(arg): - if arg.has_key('addr'): - return '&a' + str(p) - else: - return 'a' + str(p) - else: - if arg.has_key('addr'): - return '&object(a%s)' % str(p) - else: - return 'object(a%s)' % str(p) - -def call_func_direct_args(args): - if not len(args): - return '' - d_args = reduce(lambda x,y : x + (y and ((x and ', ' or '') + y) or ''), map(call_func_direct_arg, args, xrange(len(args)))) - return d_args - -def get_statement_arg(args): - i = 0 - for arg in args: - if arg.has_key('statement'): - return i - i = i + 1 - return -1 - -def get_use_gd_arg(args): - i = 0 - for arg in args: - if arg.has_key('use_gd'): - return i - i = i + 1 - return -1 - -def call_func_direct(name, args): - if name.has_key('statement'): - na = len(args) - ugd = get_use_gd_arg(args) - sa = get_statement_arg(args) - if ugd >= 0: - ugd = 'a' + str(ugd) - na = na - 1 - else: - if (sa < 0) and (na > 0): - ugd = 'use_new_dict' - else: - ugd = None - if sa >= 0: - na = na - 1 - if na > 0: - if ugd: - return 'api_detail::call_statement_du(%s, %s, %s, %s)' % ('a' + str(sa), ugd, na, call_func_direct_args(args)) - else: - return 'api_detail::call_statement(%s, %s, %s)' % ('a' + str(sa), na, call_func_direct_args(args)) - else: - if ugd: - return 'api_detail::call_statement_du(%s, %s)' % ('a' + str(sa), ugd) - else: - return 'api_detail::call_statement(%s)' % ('a' + str(sa)) - else: - if na > 0: - if ugd: - return 'api_detail::call_statement_du("%s", %s, %s, %s)' % (name['statement'], ugd, na, call_func_direct_args(args)) - else: - return 'api_detail::call_statement("%s", %s, %s)' % (name['statement'], na, call_func_direct_args(args)) - else: - if ugd: - return 'api_detail::call_statement_du("%s", %s)' % (name['statement'], ugd) - else: - return 'api_detail::call_statement("%s")' % (name['statement']) - else: - return 'api_detail::get_func("%s")(%s)' % (name['name'], call_func_direct_args(args)) - -def decl_template_arg(arg, p): - if arg.has_key('value'): - return '' - elif arg.has_key('result'): - return '' - elif is_template(arg): - return 'class A' + str(p) - else: - return '' - -def decl_template_args(args): - if not len(args): - return '' - d_args = reduce(lambda x,y : x + (y and ((x and ', ' or '') + y) or ''), map(decl_template_arg, args, xrange(len(args)))) - return d_args - -def is_rtn_borrowed_object(rtn): - if is_object(rtn): - return rtn.has_key('borrowed') - else: - return 0 - -def is_rtn_new_object(rtn): - if is_object(rtn): - return not rtn.has_key('borrowed') - else: - return 0 - -def is_func_direct(name): - return name.has_key('direct') - -def rtn_call_func_direct(rtn, name, args): - if rtn['name'] == 'void': - direct_code = ' %s;' % call_func_direct(name, args) - elif is_object(rtn): - direct_code = ' return %s;' % call_func_direct(name, args) - else: - r = '''\ - object r(%s); - return boost::python::arg_from_python<%s>(r.ptr())(r.ptr());''' - direct_code = r % (call_func_direct(name, args), rtn['name']) - return direct_code - -def rtn_call_func(rtn, name, args): - if is_func_direct(name): - return rtn_call_func_direct(rtn, name, args) - true_rtn = get_actual_rtn_type(rtn, args) - err = true_rtn.get('err') - arg_number = true_rtn.get('arg_number') - if rtn['name'] == 'void': - return ' %s;' % call_func(name, args) - elif is_rtn_new_object(rtn): - if err and (err != 'NULL'): - r = '''\ - PyObject* r = %s; - if(r == %s) - throw_error_already_set(); - return object((python::detail::new_reference)r);''' - return r % (call_func(name, args), err) - else: - return ' return object((python::detail::new_reference)%s);' % call_func(name, args) - elif is_rtn_borrowed_object(rtn): - if err and (err != 'NULL'): - r = '''\ - PyObject* r = %s; - if(r == %s) - throw_error_already_set(); - return object((python::detail::borrowed_reference)r);''' - return r % (call_func(name, args), err) - else: - return ' return object((python::detail::borrowed_reference)%s);' % call_func(name, args) - else: - if err: - if arg_number == None: - r = '''\ - %s r = %s; - if(r == %s) - throw_error_already_set(); - return r;''' - return r % (rtn['name'], call_func(name, args), err) - else: - r = '''\ - %s rslt; - %s r = %s; - if(r == %s) - throw_error_already_set(); - return rslt;''' - return r % (true_rtn['name'], rtn['name'], call_func(name, args), err) - else: - return ' return %s;' % call_func(name, args) - -def decl_func(name, args): - return '%s(%s)' % (name.get('decl', name['name']), decl_func_args(name, args)) - -def rtn_decl_func(rtn, name, args): - true_rtn = get_actual_rtn_type(rtn, args) - ta = decl_template_args(args) - if ta: - decl = 'template<%s>\n' % ta - else: - decl = 'BOOST_PYTHON_DECL ' - if is_object(true_rtn): - return decl + 'object %s' % decl_func(name, args) - else: - return decl + '%s %s' % (true_rtn['name'], decl_func(name, args)) - -def is_info_template(fn_info): - for arg in fn_info['args']: - if is_template(arg): - return 1 - return 0 - -def parse_func(func): - fn_info = {} - fnm = re.match(r'(?P\S+)\s+(?P[^\s\(\){}]+({[^{}]*})?)\s*\((?P(({[^{}]*})+|(\([^\(\)]*\))+|[^\(\)]+)*)\)', func).groupdict() - fn_info['fname'] = SplitOutAttrs(fnm['fname']) - fn_info['rtn'] = SplitOutAttrs(fnm['rtn']) - fn_info['args'] = map(SplitOutAttrs, SplitOutList(fnm['args'])) - if fn_info['fname'].has_key('statement'): - if is_info_template(fn_info): - for arg in fn_info['args']: - if is_template(arg): - arg['addr'] = None - else: - for arg in fn_info['args']: - if is_object(arg): - arg['addr'] = None - return fn_info - -def get_argrepeat(fn_info): - if fn_info['fname'].has_key('argrepeat'): - argrepeat = fn_info['fname']['argrepeat'] - if argrepeat == None: - argrepeat = 10 - else: - argrepeat = 1 - return argrepeat - -def do_arg_repeat(fn_info): - fn_info['args'] = fn_info['args'] + [fn_info['args'][len(fn_info['args']) - 1],] - if fn_info['fname'].has_key('statement'): - stmt = fn_info['fname']['statement'] - if stmt: - s_args = re.findall(r'[\s,\(](?:_([0-9]+))(?=$|[\s,\)])', stmt) - if s_args: - mx = reduce(max, map(int, s_args), 0) - mx_arg = '_' + str(mx) - next_arg = '_' + str(mx + 1) - stmt = re.sub(r'(?<=[\s,\(])' + mx_arg + '(?=$|[\s,\)])', mx_arg + ', ' + next_arg, stmt, 1) - fn_info['fname']['statement'] = stmt - -def decl_funcs(fn_list): - fn_defs = '' - for fn in fn_list: - fn_info = parse_func(fn) - argrepeat = get_argrepeat(fn_info) - for ar in xrange(argrepeat): - fn_defs += rtn_decl_func(fn_info['rtn'], fn_info['fname'], fn_info['args']) - if is_info_template(fn_info): - fn_defs += '\n{\n' + rtn_call_func(fn_info['rtn'], fn_info['fname'], fn_info['args']) + '\n}\n' - else: - fn_defs += ';\n' - if ar != (argrepeat - 1): - do_arg_repeat(fn_info) - return fn_defs - -def impl_funcs(fn_list): - fn_defs = '' - for fn in fn_list: - fn_info = parse_func(fn) - if is_info_template(fn_info): - continue - argrepeat = get_argrepeat(fn_info) - for ar in xrange(argrepeat): - fn_defs += rtn_decl_func(fn_info['rtn'], fn_info['fname'], fn_info['args']) + ' {\n' - fn_defs += rtn_call_func(fn_info['rtn'], fn_info['fname'], fn_info['args']) + '\n}\n\n' - if ar != (argrepeat - 1): - do_arg_repeat(fn_info) - return fn_defs - -if __name__ == '__main__': - f = file(DeclFile, 'w') - print >>f, DeclFileHeader - print >>f, decl_funcs(API_List) - print >>f, DeclFileTrailer - f.close() - - f = file(ImplFile, 'w') - print >>f, ImplFileHeader - print >>f, impl_funcs(API_List) - print >>f, ImplFileTrailer - f.close() diff --git a/src/gen_returning.py b/src/gen_returning.py deleted file mode 100644 index 8f7c866c..00000000 --- a/src/gen_returning.py +++ /dev/null @@ -1,201 +0,0 @@ -# (C) Copyright David Abrahams 2001,2002. Permission to copy, use, modify, sell and -# distribute this software is granted provided this copyright notice appears -# in all copies. This software is provided "as is" without express or implied -# warranty, and with no claim as to its suitability for any purpose. -# -# This work was funded in part by Lawrence Berkeley National Labs - -from gen_function import * -import string - -header = '''// (C) Copyright David Abrahams 2001,2002. Permission to copy, use, modify, sell -// and distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// This work was funded in part by Lawrence Berkeley National Labs -// -// This file generated for %d-argument member functions and %d-argument free -// functions by gen_returning.py -''' - -body_sections = ( -''' -#ifndef RETURNING_DWA20011201_HPP -# define RETURNING_DWA20011201_HPP - -# include -# include -# include -# include - -namespace boost { namespace python { namespace detail { - -// Calling C++ from Python -template -struct returning -{ -''', -''' -''', -''' // Free functions -''', -'''}; - -template <> -struct returning -{ - typedef void R; -''', -''' -''', -''' - // Free functions -''', -'''}; - -}}} // namespace boost::python::detail - -#endif // RETURNING_DWA20011201_HPP -''') - -#' - -member_function = ''' template - static PyObject* call(R (A0::*pmf)(%(A%+%:, %))%1, PyObject* args_, PyObject*, P const& policies) - { - // check that each of the arguments is convertible - from_python c0(PyTuple_GET_ITEM(args_, 0)); - if (!c0.convertible()) return 0; -%( from_python c%+(PyTuple_GET_ITEM(args_, %+)); - if (!c%+.convertible()) return 0; -%) -%[r%: // find the result converter - typedef typename P::result_converter result_converter; - typename eval::type cr; - if (!cr.convertible()) return 0; - -%] if (!policies.precall(args_)) return 0; - - %[r%:PyObject* result = cr( %]((c0(PyTuple_GET_ITEM(args_, 0)))->*pmf)( - %(c%+(PyTuple_GET_ITEM(args_, %+))%: - , %))%[r%: )%]; - - return policies.postcall(args_, %[r%:result%]%[v%:detail::none()%]); - } -''' - -free_function = ''' template - static PyObject* call(R (*pf)(%(A%n%:, %)), PyObject* args_, PyObject*, P const& policies) - {%{ - // check that each of the arguments is convertible -%}%( from_python c%n(PyTuple_GET_ITEM(args_, %n)); - if (!c%n.convertible()) return 0; -%) -%[r%: // find the result converter - typedef typename P::result_converter result_converter; - typename eval::type cr; - if (!cr.convertible()) return 0; - -%]%[not-void-and-0-arg%: if (!policies.precall(args_)) return 0; - -%] %[r%:PyObject* result = cr( %](*pf)( - %(c%n(PyTuple_GET_ITEM(args_, %n))%: - , %))%[r%: )%]; - - return policies.postcall(args_, %[r%:result%]%[v%:detail::none()%]); - } -''' - -def _returns_value(key, n, args, value): - if key != 'v': - return value - else: - return '' - -def _returns_void(key, n, args, value): - if key == 'v' or key == 'not-void-and-0-arg' and n != 0: - return value - else: - return '' - -_cv_qualifiers = ('', ' const', ' volatile', ' const volatile') - -_prefix = { -# ' const': ''' - -# // missing cv-qualified -> cv-unqualified member pointer conversions -# # if defined(__MWERKS__) && __MWERKS__ <=0x2406 || defined(BOOST_MSVC) && BOOST_MSVC <= 1200 || defined(__BORLANDC__) -# ''', - ' const volatile': ''' -// missing const volatile type traits -# ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -'''}; - -def gen_returning(member_function_args, free_function_args = None): - if free_function_args is None: - free_function_args = member_function_args + 1 - - return_none = '''; - return detail::none();''' - - return (header % (member_function_args, free_function_args) - + body_sections[0] - # - # functions returning results - # - - + reduce(lambda x,y: x+y - , map(lambda cv: - _prefix.get(cv,'') - + gen_functions(member_function, - member_function_args, cv, - fill = _returns_value) + '\n' - , _cv_qualifiers)) - + '''# endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION - -''' -## endif // missing cv-qualified -> cv-unqualified member pointer conversions -#''' - # free functions - + gen_functions(free_function, free_function_args, fill = _returns_value) - + body_sections[3] - - # - # functions returning void - # - - + reduce(lambda x,y: x+y - , map(lambda cv: - _prefix.get(cv,'') - + gen_functions(member_function, - member_function_args, cv, fill = - _returns_void) + '\n' - , _cv_qualifiers)) - - + '''# endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION - -''' -## endif // missing cv-qualified -> cv-unqualified member pointer conversions -#''' - # free functions - + gen_functions(free_function, free_function_args, fill = _returns_void) - + body_sections[6] - ) - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - member_function_args = 5 - free_function_args = 6 - else: - member_function_args = int(sys.argv[1]) - if len(sys.argv) > 2: - free_function_args = int(sys.argv[2]) - else: - free_function_args = member_function_args - - print gen_returning(member_function_args, free_function_args) - - diff --git a/src/gen_signature.py b/src/gen_signature.py deleted file mode 100644 index 1af3437d..00000000 --- a/src/gen_signature.py +++ /dev/null @@ -1,90 +0,0 @@ -# (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and -# distribute this software is granted provided this copyright notice appears -# in all copies. This software is provided "as is" without express or implied -# warranty, and with no claim as to its suitability for any purpose. -# -# This work was funded in part by Lawrence Berkeley National Labs - -from gen_function import * -import string - -header = '''// (C) Copyright David Abrahams 2002. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// This work was funded in part by Lawrence Berkeley and Lawrence -// Livermore National Labs -// -// This file generated for %d-argument member functions and %d-argument free -// functions by gen_signature.py -''' - -_cv_qualifiers = ('', ' const', ' volatile', ' const volatile') - -_suffix = { - '': ''' -// Metrowerks thinks this creates ambiguities -# if !defined(__MWERKS__) || __MWERKS__ > 0x2406 -''', ' const volatile': ''' -# endif // __MWERKS__ -''' - }; - -def gen_arg_tuple_size(member_function_args, free_function_args = None): - if free_function_args is None: - free_function_args = member_function_args + 1 - - return_none = '''; - return detail::none();''' - - return (header % (member_function_args, free_function_args) - + ''' -#ifndef SIGNATURE_DWA2002128_HPP -# define SIGNATURE_DWA2002128_HPP - -# include - -namespace boost { namespace python { namespace detail { -''' - - + gen_functions(''' -template -mpl::type_list -signature(R (*)(%(A%n%:, %))) -{ - return mpl::type_list() -} -''', free_function_args) - - + reduce(lambda x,y: x+'\n'+y - , map( - lambda cv: gen_functions( -'''template -mpl::type_list signature(R (A0::*)(%(A%+%:, %))%1) -{ - return mpl::type_list(); -} - -''', member_function_args, cv) - , _cv_qualifiers)) + '''}}} // namespace boost::python::detail - -#endif // SIGNATURE_DWA2002128_HPP -''') - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - member_function_args = 5 - free_function_args = 6 - else: - member_function_args = int(sys.argv[1]) - if len(sys.argv) > 2: - free_function_args = int(sys.argv[2]) - else: - free_function_args = member_function_args - - print gen_arg_tuple_size(member_function_args, free_function_args) - - diff --git a/src/gen_signatures.py b/src/gen_signatures.py deleted file mode 100644 index f5a97b17..00000000 --- a/src/gen_signatures.py +++ /dev/null @@ -1,158 +0,0 @@ -from gen_function import * -import string - -def gen_struct_signatures(args): - result = '' - for n in range(args, -1, -1): - result = ( - result + gen_function("""%{template <%(class T%n%:, %)> -%}struct signature%x {}; - -""", n) -# + ((n == args) and [""] or -# [gen_function(""" -# template -# static inline signature%1 prepend(type) -# { return signature%1(); }""", -# n, (str(n+1),)) -# ] -# )[0] -# -# + ((n != 0) and [""] or -# [""" -# // This one terminates the chain. Prepending void_t to the head of a void_t -# // signature results in a void_t signature again. -# static inline signature0 prepend(void_t) { return signature0(); }"""] -# )[0] -# + """ -#}; -# -#""" - + ((n == args) and [""] or - [gen_function( -"""template <%(class T%n%, %)class X> -inline signature%1 prepend(type, signature%x%{<%(T%n%:, %)>%}) - { return signature%1(); } - -""", n, str(n+1)) - ] - )[0] - ) - return result - -def gen_signatures(args): - return ( -"""// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. -// -// This file automatically generated by gen_signatures.python for %d arguments. -#ifndef SIGNATURES_DWA050900_H_ -# define SIGNATURES_DWA050900_H_ - -# include - -namespace boost { namespace python { - -namespace detail { -// A stand-in for the built-in void. This one can be passed to functions and -// (under MSVC, which has a bug, be used as a default template type parameter). -struct void_t {}; -} - -// An envelope in which type information can be delivered for the purposes -// of selecting an overloaded from_python() function. This is needed to work -// around MSVC's lack of partial specialiation/ordering. Where normally we'd -// want to form a function call like void f(), We instead pass -// type as one of the function parameters to select a particular -// overload. -// -// The id typedef helps us deal with the lack of partial ordering by generating -// unique types for constructor signatures. In general, type::id is type, -// but type::id is just void_t. -template -struct type -{ - typedef type id; -}; - -template <> -struct type -{ - typedef boost::python::detail::void_t id; -}; - -namespace detail { -// These basically encapsulate a chain of types, , used to make the syntax of -// add(constructor()) work. We need to produce a unique type for each number -// of non-default parameters to constructor<>. Q: why not use a recursive -// formulation for infinite extensibility? A: MSVC6 seems to choke on constructs -// that involve recursive template nesting. -// -// signature chaining -""" % args - + gen_struct_signatures(args) - + """ -// This one terminates the chain. Prepending void_t to the head of a void_t -// signature results in a void_t signature again. -inline signature0 prepend(void_t, signature0) { return signature0(); } - -} // namespace detail -""" - + gen_function(""" -template <%(class A%n% = detail::void_t%:, %)> -struct constructor -{ -}; -""", args) - + """ -namespace detail { -// Return value extraction: - -// This is just another little envelope for carrying a typedef (see type, -// above). I could have re-used type, but that has a very specific purpose. I -// thought this would be clearer. -template -struct return_value_select { typedef T type; }; - -// free functions""" - + gen_functions(""" -template -return_value_select return_value(R (*)(%(A%n%:, %))) { return return_value_select(); } -""", args) - - + -""" -// TODO(?): handle 'const void' - -// member functions""" - + gen_functions(""" -template -return_value_select return_value(R (T::*)(%(A%n%:, %))) { return return_value_select(); } -""", args) - - + gen_functions(""" -template -return_value_select return_value(R (T::*)(%(A%n%:, %)) const) { return return_value_select(); } -""", args) - - + """ -}}} // namespace boost::python::detail - -#endif -""") - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 5 - else: - args = int(sys.argv[1]) - - print gen_signatures(args) - diff --git a/src/gen_singleton.py b/src/gen_singleton.py deleted file mode 100644 index 3a5ca7e3..00000000 --- a/src/gen_singleton.py +++ /dev/null @@ -1,58 +0,0 @@ -from gen_function import * -import string - -def gen_singleton(args): - return ( -"""// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. - -#ifndef SINGLETON_DWA051900_H_ -# define SINGLETON_DWA051900_H_ - -# include - -namespace boost { namespace python { namespace detail { - -struct empty {}; -template -struct singleton : Base -{ - typedef singleton singleton_base; // Convenience type for derived class constructors - - static Derived* instance(); - - // Pass-through constructors -""" - + gen_functions("""%{ - template <%(class A%n%:, %)> -%} singleton(%(const A%n& a%n%:, %)) : Base(%(a%n%:, %)) {} -""", args) - + """ -}; - -template -Derived* singleton::instance() -{ - static Derived x; - return &x; -} - -}}} // namespace boost::python::detail - -#endif -""") - -if __name__ == '__main__': - import sys - - if len(sys.argv) == 1: - args = 5 - else: - args = int(sys.argv[1]) - - print gen_singleton(args) diff --git a/src/gen_value_holder.py b/src/gen_value_holder.py deleted file mode 100644 index b01e2c0e..00000000 --- a/src/gen_value_holder.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright David Abrahams 2002. Permission to copy, use, modify, -# sell and distribute this software is granted provided this -# copyright notice appears in all copies. This software is provided -# "as is" without express or implied warranty, and with no claim as -# to its suitability for any purpose. -# -# This work was funded in part by Lawrence Livermore National Labs - -from gen_function import * -import string - -def _generate(member_function_args, free_function_args = None): - return ('''// Copyright David Abrahams 2001. Permission to copy, use, -// modify, sell and distribute this software is granted provided this -// copyright notice appears in all copies. This software is provided -// "as is" without express or implied warranty, and with no claim as -// to its suitability for any purpose. -#ifndef VALUE_HOLDER_DWA20011215_HPP -# define VALUE_HOLDER_DWA20011215_HPP - -# include -# include -# include -# include -# include - -namespace boost { namespace python { namespace objects { - -template -struct value_holder : instance_holder -{ - // Forward construction to the held object -''' - + - gen_functions( diff --git a/src/init_function.cpp b/src/init_function.cpp deleted file mode 100644 index 1ebfa501..00000000 --- a/src/init_function.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. - -#define BOOST_PYTHON_SOURCE - -#include -#include -#include -#include - -namespace boost { namespace python { namespace detail { - - PyObject* init::do_call(PyObject* args_, PyObject* keywords) const - { - tuple args(ref(args_, ref::increment_count)); - if (args[0]->ob_type->ob_type != extension_meta_class()) - { - PyErr_SetString(PyExc_TypeError, "argument 1 to __init__ must be an ExtensionInstance"); - return 0; - } - - extension_instance *self = static_cast(args[0].get()); - - tuple ctor_args = args.slice(1, args.size()); - - std::auto_ptr result( - create_holder(self, ctor_args.get(), keywords)); - - self->add_implementation(result); - return none(); - } - -}}} // namespace boost::python::detail diff --git a/src/module.cpp b/src/module.cpp index 2dd476d1..d81e626a 100644 --- a/src/module.cpp +++ b/src/module.cpp @@ -6,8 +6,8 @@ // The author gratefully acknowleges the support of Dragon Systems, Inc., in // producing this work. +#include #include -#include #include #include #include @@ -35,7 +35,7 @@ void module_base::setattr_doc(const char* name, python::object const& x, char co { // Use function::add_to_namespace to achieve overloading if // appropriate. - objects::function::add_to_namespace(python::object(m_module), name, x, doc); + objects::add_to_namespace(python::object(m_module), name, x, doc); } void BOOST_PYTHON_DECL scope_setattr_doc(char const* name, object const& x, char const* doc) @@ -43,7 +43,7 @@ void BOOST_PYTHON_DECL scope_setattr_doc(char const* name, object const& x, char // Use function::add_to_namespace to achieve overloading if // appropriate. scope current; - objects::function::add_to_namespace(current, name, x, doc); + objects::add_to_namespace(current, name, x, doc); } void module_base::add(type_handle const& x) diff --git a/src/module_builder.cpp b/src/module_builder.cpp deleted file mode 100644 index 1e47badb..00000000 --- a/src/module_builder.cpp +++ /dev/null @@ -1,64 +0,0 @@ - // (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. - -#define BOOST_PYTHON_SOURCE - -#include - -namespace boost { namespace python { - -namespace { - ref name_holder; -} - -bool module_builder_base::initializing() -{ - return name_holder.get() != 0; -} - -string module_builder_base::name() -{ - // If this fails, you haven't created a module_builder object - assert(initializing()); - return string(name_holder); -} - -module_builder_base::module_builder_base(const char* name) - : m_module(Py_InitModule(const_cast(name), initial_methods)) -{ - // If this fails, you've created more than 1 module_builder object in your module - assert(name_holder.get() == 0); - name_holder = ref(PyObject_GetAttrString(m_module, const_cast("__name__"))); -} - -module_builder_base::~module_builder_base() -{ - name_holder.reset(); -} - -void -module_builder_base::add(detail::function* x, const char* name) -{ - reference f(x); // First take possession of the object. - detail::function::add_to_namespace(f, name, PyModule_GetDict(m_module)); -} - -void module_builder_base::add(ref x, const char* name) -{ - PyObject* dictionary = PyModule_GetDict(m_module); - PyDict_SetItemString(dictionary, const_cast(name), x.get()); -} - -void module_builder_base::add(PyTypeObject* x, const char* name /*= 0*/) -{ - this->add(ref(as_object(x)), name ? name : x->tp_name); -} - -PyMethodDef module_builder_base::initial_methods[] = { { 0, 0, 0, 0 } }; - -}} // namespace boost::python diff --git a/src/object/function.cpp b/src/object/function.cpp index 6d013b3a..259bfb86 100644 --- a/src/object/function.cpp +++ b/src/object/function.cpp @@ -7,22 +7,54 @@ #include #include #include -#include #include #include +#include +#include +#include + #include #include -#include namespace boost { namespace python { namespace objects { extern PyTypeObject function_type; -function::function(py_function const& implementation, unsigned min_args, unsigned max_args) +function::function( + py_function const& implementation + , unsigned min_arity + , unsigned max_arity + , python::detail::keyword const* names_and_defaults + , unsigned num_keywords + ) : m_fn(implementation) - , m_min_args(min_args) - , m_max_args(std::max(max_args,min_args)) + , m_min_arity(min_arity) + // was using std::max here, but a problem with MinGW-2.95 and + // our directory prevents it. + , m_max_arity(max_arity > min_arity ? max_arity : min_arity) { + if (names_and_defaults != 0) + { + unsigned keyword_offset + = m_max_arity > num_keywords ? m_max_arity - num_keywords : 0; + + + m_arg_names = object(handle<>(PyTuple_New(m_max_arity))); + for (unsigned j = 0; j < keyword_offset; ++j) + PyTuple_SET_ITEM(m_arg_names.ptr(), j, incref(Py_None)); + + for (unsigned i = 0; i < num_keywords; ++i) + { + PyTuple_SET_ITEM( + m_arg_names.ptr() + , i + keyword_offset + , expect_non_null( + PyString_FromString(const_cast(names_and_defaults[i].name)) + ) + ); + } + } + PyObject* p = this; if (function_type.ob_type == 0) { @@ -39,14 +71,51 @@ function::~function() PyObject* function::call(PyObject* args, PyObject* keywords) const { std::size_t nargs = PyTuple_GET_SIZE(args); + std::size_t nkeywords = keywords ? PyDict_Size(keywords) : 0; + std::size_t total_args = nargs + nkeywords; + function const* f = this; do { // Check for a plausible number of arguments - if (nargs >= f->m_min_args && nargs <= f->m_max_args) + if (total_args >= f->m_min_arity && total_args <= f->m_max_arity) { + handle<> args2(allow_null(borrowed(args))); + if (nkeywords > 0) + { + if (!f->m_arg_names + || static_cast(PyTuple_Size(f->m_arg_names.ptr())) < total_args) + { + args2 = handle<>(); // signal failure + } + else + { + // build a new arg tuple + args2 = handle<>(PyTuple_New(total_args)); + + // Fill in the positional arguments + for (std::size_t i = 0; i < nargs; ++i) + PyTuple_SET_ITEM(args2.get(), i, incref(PyTuple_GET_ITEM(args, i))); + + // Grab remaining arguments by name from the keyword dictionary + for (std::size_t j = nargs; j < total_args; ++j) + { + PyObject* value = PyDict_GetItem( + keywords, PyTuple_GET_ITEM(f->m_arg_names.ptr(), j)); + + if (!value) + { + PyErr_Clear(); + args2 = handle<>(); + break; + } + PyTuple_SET_ITEM(args2.get(), j, incref(value)); + } + } + } + // Call the function - PyObject* result = f->m_fn(args, keywords); + PyObject* result = args2 ? f->m_fn(args2.get(), 0) : 0; // If the result is NULL but no error was set, m_fn failed // the argument-matching test. @@ -154,7 +223,10 @@ namespace handle not_implemented_function() { - static object keeper(function_object(¬_implemented_impl, 2, 3)); + static object keeper( + function_object(¬_implemented_impl, 2, 3 + , python::detail::keyword_range()) + ); return handle(borrowed(downcast(keeper.ptr()))); } } @@ -222,6 +294,19 @@ void function::add_to_namespace( } } +BOOST_PYTHON_DECL void add_to_namespace( + object const& name_space, char const* name, object const& attribute) +{ + function::add_to_namespace(name_space, name, attribute); +} + +BOOST_PYTHON_DECL void add_to_namespace( + object const& name_space, char const* name, object const& attribute, char const* doc) +{ + function::add_to_namespace(name_space, name, attribute, doc); +} + + namespace { struct bind_return @@ -350,31 +435,35 @@ PyTypeObject function_type = { 0 /* tp_new */ }; -object function_object_impl(py_function const& f, unsigned min_args, unsigned max_args) +object function_object( + py_function const& f, unsigned min_arity, unsigned max_arity + , python::detail::keyword_range const& keywords) { return python::object( python::detail::new_non_null_reference( - new function(f, min_args, max_args))); + new function( + f, min_arity, max_arity, keywords.first, keywords.second - keywords.first))); } -handle<> function_handle_impl(py_function const& f, unsigned min_args, unsigned max_args) +object function_object( + py_function const& f + , unsigned arity + , python::detail::keyword_range const& kw) +{ + return function_object(f, arity, arity, kw); +} + +object function_object(py_function const& f, unsigned arity) +{ + return function_object(f, arity, arity, python::detail::keyword_range()); +} + + +handle<> function_handle_impl(py_function const& f, unsigned min_arity, unsigned max_arity) { return python::handle<>( allow_null( - new function(f, min_args, max_args))); + new function(f, min_arity, max_arity, 0, 0))); } -BOOST_PYTHON_DECL void add_to_namespace( - object const& name_space, char const* name, object const& attribute) -{ - function::add_to_namespace(name_space, name, attribute); -} - -BOOST_PYTHON_DECL void add_to_namespace( - object const& name_space, char const* name, object const& attribute, char const* doc) -{ - function::add_to_namespace(name_space, name, attribute, doc); -} - - }}} // namespace boost::python::objects diff --git a/src/object/iterator.cpp b/src/object/iterator.cpp index 384d6845..1718ee59 100644 --- a/src/object/iterator.cpp +++ b/src/object/iterator.cpp @@ -5,7 +5,6 @@ // to its suitability for any purpose. #include -#include #include #include diff --git a/src/objects.cpp b/src/objects.cpp deleted file mode 100644 index f446919d..00000000 --- a/src/objects.cpp +++ /dev/null @@ -1,488 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. - -// TODO: Move inline implementations from objects.cpp here - -#ifndef BOOST_PYTHON_SOURCE -# define BOOST_PYTHON_SOURCE -#endif - -#include -#include - -namespace boost { namespace python { - -template -T object_from_python(PyObject* p, type) -{ - ref x(p, ref::increment_count); - if (!T::accepts(x)) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - throw_error_already_set(); - } - return T(x); -} - -inline PyObject* object_to_python(const object& x) -{ - return x.reference().release(); -} - -object::object(ref p) - : m_p(p) {} - -// Return a reference to the held object -ref object::reference() const -{ - return m_p; -} - -// Return a raw pointer to the held object -PyObject* object::get() const -{ - return m_p.get(); -} - -}} // namespace boost::python - -BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE - -BOOST_PYTHON_DECL PyObject* to_python(const boost::python::tuple& x) -{ - return object_to_python(x); -} - -BOOST_PYTHON_DECL boost::python::tuple from_python(PyObject* p, boost::python::type type) -{ - return boost::python::object_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(const boost::python::list& x) -{ - return object_to_python(x); -} - -BOOST_PYTHON_DECL boost::python::list from_python(PyObject* p, boost::python::type type) -{ - return boost::python::object_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(const boost::python::dictionary& x) -{ - return object_to_python(x); -} - -BOOST_PYTHON_DECL boost::python::dictionary from_python(PyObject* p, boost::python::type type) -{ - return boost::python::object_from_python(p, type); -} - -BOOST_PYTHON_DECL PyObject* to_python(const boost::python::string& x) -{ - return object_to_python(x); -} - -BOOST_PYTHON_DECL boost::python::string from_python(PyObject* p, boost::python::type type) -{ - return boost::python::object_from_python(p, type); -} - -BOOST_PYTHON_END_CONVERSION_NAMESPACE - -namespace boost { namespace python { - -tuple_base::tuple_base(std::size_t n) - : object(ref(PyTuple_New(n))) -{ - for (std::size_t i = 0; i < n; ++i) - PyTuple_SET_ITEM(get(), i, detail::none()); -} - -tuple_base::tuple_base(ref p) - : object(p) -{ - assert(accepts(p)); - if (!accepts(p)) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - throw_error_already_set(); - } -} - -PyTypeObject* tuple_base::type_obj() -{ - return &PyTuple_Type; -} - -bool tuple_base::accepts(ref p) -{ - return PyTuple_Check(p.get()); -} - -std::size_t tuple_base::size() const -{ - return PyTuple_Size(get()); -} - -ref tuple_base::operator[](std::size_t pos) const -{ - return ref(PyTuple_GetItem(get(), static_cast(pos)), - ref::increment_count); -} - -void tuple_base::set_item(std::size_t pos, const ref& rhs) -{ - int failed = PyTuple_SetItem( - get(), static_cast(pos), ref(rhs).release()); // A reference is stolen here. - (void)failed; - assert(failed == 0); -} - -tuple tuple_base::slice(int low, int high) const -{ - return tuple(ref(PyTuple_GetSlice(get(), low, high))); -} - -BOOST_PYTHON_DECL tuple& operator+=(tuple& self, const tuple& rhs) -{ - return self = self + rhs; -} - - -// Construct from an owned PyObject*. -// Precondition: p must point to a python string. -string::string(ref p) - : object(p) -{ - assert(accepts(p)); - if (!accepts(p)) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - throw_error_already_set(); - } -} - -string::string(const char* s) - : object(ref(PyString_FromString(s))) {} - -string::string(const char* s, std::size_t length) - : object(ref(PyString_FromStringAndSize(s, length))) {} - -string::string(const char* s, interned_t) - : object(ref(PyString_InternFromString(s))) {} - -#if 0 -string::string(const char* s, std::size_t length, interned_t) - : object(ref(PyString_InternFromStringAndSize(s, length))) {} -#endif - -string::string(const string& rhs) - : object(rhs.reference()) {} - -// Get the type object for Strings -PyTypeObject* string::type_obj() -{ return &PyString_Type; } - -// Return true if the given object is a python string -bool string::accepts(ref o) -{ return PyString_Check(o.get()); } - -// Return the length of the string. -std::size_t string::size() const -{ - int size = PyString_GET_SIZE(get()); - assert(size >= 0); - return static_cast(size); -} - -// Returns a null-terminated representation of the contents of string. -// The pointer refers to the internal buffer of string, not a copy. -// The data must not be modified in any way. It must not be de-allocated. -const char* string::c_str() const -{ return PyString_AS_STRING(get()); } - -void string::intern() -{ // UNTESTED!! - *this = string(ref(PyString_InternFromString(c_str()), ref::increment_count)); -} - -string& string::operator*=(unsigned int repeat_count) -{ - *this = string(ref(PySequence_Repeat(get(), repeat_count))); - return *this; -} - -dictionary_base::dictionary_base(ref p) - : object(p) -{ - assert(accepts(p)); - if (!accepts(p)) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - throw_error_already_set(); - } -} - -dictionary_base::dictionary_base() - : object(ref(PyDict_New())) {} - -PyTypeObject* dictionary_base::type_obj() -{ return &PyDict_Type; } - -bool dictionary_base::accepts(ref p) -{ return PyDict_Check(p.get()); } - -void dictionary_base::clear() -{ PyDict_Clear(get()); } - -const ref& dictionary_proxy::operator=(const ref& rhs) -{ - if (PyDict_SetItem(m_dict.get(), m_key.get(), rhs.get()) == -1) - throw_error_already_set(); - return rhs; -} - -dictionary_proxy::operator ref() const -{ - return ref(m_dict->ob_type->tp_as_mapping->mp_subscript(m_dict.get(), m_key.get())); -} - -dictionary_proxy::dictionary_proxy(const ref& dict, const ref& key) - : m_dict(dict), m_key(key) {} - -dictionary_proxy dictionary_base::operator[](ref key) -{ return proxy(reference(), key); } - -ref dictionary_base::operator[](ref key) const { - // An odd MSVC bug causes the ".operator Ptr()" to be needed - return proxy(reference(), key).operator ref(); -} - - -ref dictionary_base::get_item(const ref& key) const -{ - return get_item(key, ref()); -} - -ref dictionary_base::get_item(const ref& key, const ref& default_) const -{ - PyObject* value_or_null = PyDict_GetItem(get(), key.get()); - if (value_or_null == 0 && !PyErr_Occurred()) - return default_; - else - return ref(value_or_null, ref::increment_count); // Will throw if there was another error -} - -void dictionary_base::set_item(const ref& key, const ref& value) -{ - if (PyDict_SetItem(get(), key.get(), value.get()) == -1) - throw_error_already_set(); -} - -void dictionary_base::erase(ref key) { - if (PyDict_DelItem(get(), key.get()) == -1) - throw_error_already_set(); -} - -list dictionary_base::items() const { return list(ref(PyDict_Items(get()))); } -list dictionary_base::keys() const { return list(ref(PyDict_Keys(get()))); } -list dictionary_base::values() const { return list(ref(PyDict_Values(get()))); } - -std::size_t dictionary_base::size() const { return static_cast(PyDict_Size(get())); } - -string operator+(string x, string y) -{ - PyObject* io_string = x.reference().release(); - PyString_Concat(&io_string, y.get()); - return string(ref(io_string)); -} - -string& string::operator+=(const string& rhs) -{ - return *this = *this + rhs; -} - -string& string::operator+=(const char* y) -{ - return *this += string(y); -} - -string operator%(const string& format, const tuple& args) -{ - return string(ref(PyString_Format(format.get(), args.reference().get()))); -} - -string operator+(string x, const char* y) -{ - return x + string(y); -} - -string operator+(const char* x, string y) -{ - return string(x) + y; -} - -tuple operator+(const tuple& x, const tuple& y) -{ - tuple result(x.size() + y.size()); - for (std::size_t xi = 0; xi < x.size(); ++xi) - result.set_item(xi, x[xi]); - for (std::size_t yi = 0; yi < y.size(); ++yi) - result.set_item(yi + x.size(), y[yi]); - return result; -} - - -list_base::list_base(ref p) - : object(p) -{ - assert(accepts(p)); - if (!accepts(p)) - { - PyErr_SetString(PyExc_TypeError, p->ob_type->tp_name); - throw_error_already_set(); - } -} - -list_base::list_base(std::size_t sz) - : object(ref(PyList_New(sz))) -{ -} - -PyTypeObject* list_base::type_obj() -{ - return &PyList_Type; -} - -bool list_base::accepts(ref p) -{ - return PyList_Check(p.get()); -} - -std::size_t list_base::size() const -{ - return PyList_Size(get()); -} - -ref list_base::operator[](std::size_t pos) const -{ - return ref(PyList_GetItem(get(), pos), ref::increment_count); -} - -list_proxy list_base::operator[](std::size_t pos) -{ - return proxy(reference(), pos); -} - -void list_base::insert(std::size_t index, const ref& item) -{ - if (PyList_Insert(get(), index, item.get()) == -1) - throw_error_already_set(); -} - -void list_base::push_back(const ref& item) -{ - if (PyList_Append(get(), item.get()) == -1) - throw_error_already_set(); -} - -void list_base::append(const ref& item) -{ - this->push_back(item); -} - -list list_base::slice(int low, int high) const -{ - return list(ref(PyList_GetSlice(get(), low, high))); -} - -list_slice_proxy list_base::slice(int low, int high) -{ - return list_slice_proxy(reference(), low, high); -} - -void list_base::sort() -{ - if (PyList_Sort(get()) == -1) - throw_error_already_set(); -} - -void list_base::reverse() -{ - if (PyList_Reverse(get()) == -1) - throw_error_already_set(); -} - -tuple list_base::as_tuple() const -{ - return tuple(ref(PyList_AsTuple(get()))); -} - -const ref& list_proxy::operator=(const ref& rhs) -{ - m_list.set_item(m_index, rhs); - return rhs; -} - -list_proxy::operator ref() const -{ - return ref(PyList_GetItem(m_list.get(), m_index), ref::increment_count); -} - -ref list_base::get_item(std::size_t pos) const -{ - return ref(PyList_GetItem(this->get(), pos), ref::increment_count); -} - -void list_base::set_item(std::size_t pos, const ref& rhs) -{ - int result = PyList_SetItem(this->get(), pos, rhs.get()); - if (result == -1) - throw_error_already_set(); - Py_INCREF(rhs.get()); -} - -list_proxy::list_proxy(const ref& list, std::size_t index) - : m_list(list), m_index(index) -{ -} - -const list& list_slice_proxy::operator=(const list& rhs) -{ - if (PyList_SetSlice(m_list.get(), m_low, m_high, rhs.get()) == -1) - throw_error_already_set(); - return rhs; -} - -list_slice_proxy::operator ref() const -{ - return ref(PyList_GetSlice(m_list.get(), m_low, m_high)); -} - -list_slice_proxy::operator list() const -{ - return list(this->operator ref()); -} - -std::size_t list_slice_proxy::size() const -{ - return this->operator list().size(); -} - -ref list_slice_proxy::operator[](std::size_t pos) const -{ - return this->operator list()[pos].operator ref(); -} - -list_slice_proxy::list_slice_proxy(const ref& list, int low, int high) - : m_list(list), m_low(low), m_high(high) -{ -} - -}} // namespace boost::python diff --git a/src/py_interface.cpp b/src/py_interface.cpp deleted file mode 100644 index e34bf6f9..00000000 --- a/src/py_interface.cpp +++ /dev/null @@ -1,1103 +0,0 @@ -// Automatically generated from py_api_gen.py - -#include - -namespace boost { namespace python { namespace api { - -namespace api_detail { - -BOOST_PYTHON_DECL object get_func(const char* name) { - object __builtin__((python::detail::borrowed_reference)::PyImport_AddModule(const_cast("__builtin__"))); - return object(__builtin__.attr(name)); -} - -inline handle<> get_current_frame() -{ - return handle<>(allow_null(borrowed((PyObject*)(PyThreadState_Get()->frame)))); -} - -inline object get_global_dict(call_dict_usage cdu, handle<> const& frame) -{ - if(frame.get()) - return object(object(frame).attr("f_globals")); - else - return api::globals(); -} - -object get_local_dict(call_dict_usage cdu, handle<> const& frame, object const& global_dict) -{ - switch(cdu) { - case use_new_dict: - return api::dict(); - case use_global_dict: - return global_dict; - default: - if(frame.get()) - return object(object(frame).attr("f_locals")); - else - return api::dict(); - } -} - -inline object call_statement(const char *stmt, object const& global_dict, object& local_dict) -{ - local_dict["_0"] = object((python::detail::borrowed_reference)Py_None); - api::run_string(stmt, Py_file_input, global_dict, local_dict); - return object(local_dict["_0"]); -} - -object call_statement(const char *stmt) -{ - handle<> frame(get_current_frame()); - if(frame.get()) { - object f(frame); - object gd(f.attr("f_globals")); - object ld(f.attr("f_locals")); - return call_statement(stmt, gd, ld); - } else { - object gd(api::globals()); - object ld(api::dict()); - return call_statement(stmt, gd, ld); - } -} - -object call_statement_du(const char *stmt, call_dict_usage cdu) -{ - handle<> frame(get_current_frame()); - object gd(get_global_dict(cdu, frame)); - return call_statement(stmt, gd, get_local_dict(cdu, frame, gd)); -} - -inline object call_statement(const char *stmt, object const& global_dict, object& local_dict, int n, va_list mk) -{ - static const char *(idx[]) = { "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9", "_10" }; - local_dict["_0"] = object((python::detail::borrowed_reference)Py_None); - for(int i = 0; i < n; ++i) - { - object const* p_arg = va_arg(mk, object const*); - object const& arg = *p_arg; - if(i < (int) (sizeof(idx) / sizeof(idx[0]))) - local_dict[idx[i]] = arg; - else { - local_dict[object("_") + object((python::detail::new_reference)PyObject_Str(object(i + 1).ptr()))] = arg; - } - } - va_end(mk); - api::run_string(stmt, Py_file_input, global_dict, local_dict); - return object(local_dict["_0"]); -} - -BOOST_PYTHON_DECL object call_statement(const char *stmt, int n, ...) -{ - va_list mk; - va_start(mk, n); - handle<> frame(get_current_frame()); - if(frame.get()) { - object f(frame); - object gd(f.attr("f_globals")); - object ld(f.attr("f_locals")); - return call_statement(stmt, gd, ld, n, mk); - } else { - object gd(api::globals()); - object ld(api::dict()); - return call_statement(stmt, gd, ld, n, mk); - } -} - -BOOST_PYTHON_DECL object call_statement_du(const char *stmt, call_dict_usage cdu, int n, ...) -{ - handle<> frame(get_current_frame()); - object gd(get_global_dict(cdu, frame)); - va_list mk; - va_start(mk, n); - return call_statement(stmt, gd, get_local_dict(cdu, frame, gd), n, mk); -} - -} - -BOOST_PYTHON_DECL object locals() -{ - handle<> frame(api_detail::get_current_frame()); - if(frame.get()) - return object(object(frame).attr("f_locals")); - else - return api::dict(); -} - - -BOOST_PYTHON_DECL object abs(object const& a0) { - return api_detail::get_func("abs")(a0); -} - -BOOST_PYTHON_DECL object abs(short a0) { - return api_detail::get_func("abs")(object(a0)); -} - -BOOST_PYTHON_DECL object abs(int a0) { - return api_detail::get_func("abs")(object(a0)); -} - -BOOST_PYTHON_DECL object abs(long a0) { - return api_detail::get_func("abs")(object(a0)); -} - -BOOST_PYTHON_DECL object abs(double const & a0) { - return api_detail::get_func("abs")(object(a0)); -} - -BOOST_PYTHON_DECL object apply(object const& a0, object const& a1) { - return object((python::detail::new_reference)::PyObject_CallObject(a0.ptr(), a1.ptr())); -} - -BOOST_PYTHON_DECL object apply(object const& a0, object const& a1, object const& a2) { - return object((python::detail::new_reference)::PyObject_Call(a0.ptr(), a1.ptr(), a2.ptr())); -} - -BOOST_PYTHON_DECL bool callable(object const& a0) { - return ::PyCallable_Check(a0.ptr()); -} - -BOOST_PYTHON_DECL object chr(object const& a0) { - return api_detail::get_func("chr")(a0); -} - -BOOST_PYTHON_DECL object chr(short a0) { - return api_detail::get_func("chr")(object(a0)); -} - -BOOST_PYTHON_DECL object chr(int a0) { - return api_detail::get_func("chr")(object(a0)); -} - -BOOST_PYTHON_DECL object chr(long a0) { - return api_detail::get_func("chr")(object(a0)); -} - -BOOST_PYTHON_DECL int cmp(object const& a0, object const& a1) { - int rslt; - int r = ::PyObject_Cmp(a0.ptr(), a1.ptr(), &rslt); - if(r == -1) - throw_error_already_set(); - return rslt; -} - -BOOST_PYTHON_DECL object coerce(object const& a0, object const& a1) { - return api_detail::get_func("coerce")(a0, a1); -} - -BOOST_PYTHON_DECL object compile(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("compile")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object compile(const char* a0, const char* a1, const char* a2) { - return api_detail::get_func("compile")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object compile(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::get_func("compile")(a0, a1, a2, a3); -} - -BOOST_PYTHON_DECL object compile(const char* a0, const char* a1, const char* a2, int a3) { - return api_detail::get_func("compile")(object(a0), object(a1), object(a2), object(a3)); -} - -BOOST_PYTHON_DECL object compile(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::get_func("compile")(a0, a1, a2, a3, a4); -} - -BOOST_PYTHON_DECL object compile(const char* a0, const char* a1, const char* a2, int a3, int a4) { - return api_detail::get_func("compile")(object(a0), object(a1), object(a2), object(a3), object(a4)); -} - -BOOST_PYTHON_DECL object complex(object const& a0) { - return api_detail::get_func("complex")(a0); -} - -BOOST_PYTHON_DECL object complex(double const& a0) { - return api_detail::get_func("complex")(object(a0)); -} - -BOOST_PYTHON_DECL object complex(object const& a0, object const& a1) { - return api_detail::get_func("complex")(a0, a1); -} - -BOOST_PYTHON_DECL object complex(double const& a0, double const& a1) { - return api_detail::get_func("complex")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object dict() { - return api_detail::get_func("dict")(); -} - -BOOST_PYTHON_DECL object dict(object const& a0) { - return api_detail::get_func("dict")(a0); -} - -BOOST_PYTHON_DECL object dir() { - return object((python::detail::new_reference)::PyObject_Dir(NULL)); -} - -BOOST_PYTHON_DECL object dir(object const& a0) { - return object((python::detail::new_reference)::PyObject_Dir(a0.ptr())); -} - -BOOST_PYTHON_DECL object divmod(object const& a0, object const& a1) { - return api_detail::get_func("divmod")(a0, a1); -} - -BOOST_PYTHON_DECL object divmod(int a0, int a1) { - return api_detail::get_func("divmod")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object divmod(long a0, long a1) { - return api_detail::get_func("divmod")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object divmod(double const& a0, double const& a1) { - return api_detail::get_func("divmod")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object eval(const char* a0) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_eval_input, globals().ptr(), globals().ptr())); -} - -BOOST_PYTHON_DECL object eval(const char* a0, object const& a2) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_eval_input, a2.ptr(), globals().ptr())); -} - -BOOST_PYTHON_DECL object eval(const char* a0, object const& a2, object const& a3) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_eval_input, a2.ptr(), a3.ptr())); -} - -BOOST_PYTHON_DECL object exec(const char* a0) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_file_input, globals().ptr(), globals().ptr())); -} - -BOOST_PYTHON_DECL object exec(const char* a0, object const& a2) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_file_input, a2.ptr(), globals().ptr())); -} - -BOOST_PYTHON_DECL object exec(const char* a0, object const& a2, object const& a3) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), Py_file_input, a2.ptr(), a3.ptr())); -} - -BOOST_PYTHON_DECL object execfile(object const& a0) { - return api_detail::get_func("execfile")(a0); -} - -BOOST_PYTHON_DECL object execfile(object const& a0, object const& a1) { - return api_detail::get_func("execfile")(a0, a1); -} - -BOOST_PYTHON_DECL object execfile(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("execfile")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object file(object const& a0) { - return api_detail::get_func("file")(a0); -} - -BOOST_PYTHON_DECL object file(const char* a0) { - return api_detail::get_func("file")(object(a0)); -} - -BOOST_PYTHON_DECL object file(object const& a0, object const& a1) { - return api_detail::get_func("file")(a0, a1); -} - -BOOST_PYTHON_DECL object file(const char* a0, const char* a1) { - return api_detail::get_func("file")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object file(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("file")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object file(const char* a0, const char* a1, int a2) { - return api_detail::get_func("file")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object filter(object const& a0, object const& a1) { - return api_detail::get_func("filter")(a0, a1); -} - -BOOST_PYTHON_DECL object float_(object const& a0) { - return api_detail::get_func("float")(a0); -} - -BOOST_PYTHON_DECL object float_(const char* a0) { - return api_detail::get_func("float")(object(a0)); -} - -BOOST_PYTHON_DECL object float_(double const& a0) { - return api_detail::get_func("float")(object(a0)); -} - -BOOST_PYTHON_DECL object getattr(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("getattr")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object getattr(object const& a0, const char * a1, object const& a2) { - return api_detail::get_func("getattr")(a0, object(a1), a2); -} - -BOOST_PYTHON_DECL object globals() { - return object((python::detail::borrowed_reference)::PyModule_GetDict(PyImport_AddModule("__main__"))); -} - -BOOST_PYTHON_DECL bool hasattr(object const& a0, object const& a1) { - return ::PyObject_HasAttr(a0.ptr(), a1.ptr()); -} - -BOOST_PYTHON_DECL bool hasattr(object const& a0, const char* a1) { - return ::PyObject_HasAttrString(a0.ptr(), const_cast(a1)); -} - -BOOST_PYTHON_DECL long hash(object const& a0) { - long r = ::PyObject_Hash(a0.ptr()); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL object hex(object const& a0) { - return api_detail::get_func("hex")(a0); -} - -BOOST_PYTHON_DECL object hex(char a0) { - return api_detail::get_func("hex")(object(a0)); -} - -BOOST_PYTHON_DECL object hex(short a0) { - return api_detail::get_func("hex")(object(a0)); -} - -BOOST_PYTHON_DECL object hex(int a0) { - return api_detail::get_func("hex")(object(a0)); -} - -BOOST_PYTHON_DECL object hex(long a0) { - return api_detail::get_func("hex")(object(a0)); -} - -BOOST_PYTHON_DECL long id(object const& a0) { - object r(api_detail::get_func("id")(a0)); - return boost::python::arg_from_python(r.ptr())(r.ptr()); -} - -BOOST_PYTHON_DECL object input() { - return api_detail::get_func("input")(); -} - -BOOST_PYTHON_DECL object input(object const& a0) { - return api_detail::get_func("input")(a0); -} - -BOOST_PYTHON_DECL object input(const char* a0) { - return api_detail::get_func("input")(object(a0)); -} - -BOOST_PYTHON_DECL object int_(object const& a0) { - return api_detail::get_func("int")(a0); -} - -BOOST_PYTHON_DECL object int_(long a0) { - return api_detail::get_func("int")(object(a0)); -} - -BOOST_PYTHON_DECL object int_(const char* a0) { - return api_detail::get_func("int")(object(a0)); -} - -BOOST_PYTHON_DECL object intern(object const& a0) { - return api_detail::get_func("intern")(a0); -} - -BOOST_PYTHON_DECL object intern(const char* a0) { - return api_detail::get_func("intern")(object(a0)); -} - -BOOST_PYTHON_DECL bool isinstance(object const& a0, object const& a1) { - return ::PyObject_IsInstance(a0.ptr(), a1.ptr()); -} - -BOOST_PYTHON_DECL bool issubclass(object const& a0, object const& a1) { - return ::PyObject_IsSubclass(a0.ptr(), a1.ptr()); -} - -BOOST_PYTHON_DECL object iter(object const& a0) { - return object((python::detail::new_reference)::PyObject_GetIter(a0.ptr())); -} - -BOOST_PYTHON_DECL object iter(object const& a0, object const& a1) { - return api_detail::get_func("iter")(a0, a1); -} - -BOOST_PYTHON_DECL long len(object const& a0) { - long r = ::PyObject_Length(a0.ptr()); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL object list() { - return api_detail::get_func("list")(); -} - -BOOST_PYTHON_DECL object list(object const& a0) { - return api_detail::get_func("list")(a0); -} - -BOOST_PYTHON_DECL object long_(object const& a0) { - return api_detail::get_func("long")(a0); -} - -BOOST_PYTHON_DECL object long_(long a0) { - return api_detail::get_func("long")(object(a0)); -} - -BOOST_PYTHON_DECL object long_(const char* a0) { - return api_detail::get_func("long")(object(a0)); -} - -BOOST_PYTHON_DECL object map(object const& a0) { - return api_detail::get_func("map")(a0); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1) { - return api_detail::get_func("map")(a0, a1); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("map")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::get_func("map")(a0, a1, a2, a3); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4, a5); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4, a5, a6); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4, a5, a6, a7); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4, a5, a6, a7, a8); -} - -BOOST_PYTHON_DECL object map(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::get_func("map")(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); -} - -BOOST_PYTHON_DECL object max(object const& a0) { - return api_detail::get_func("max")(a0); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1) { - return api_detail::get_func("max")(a0, a1); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("max")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::get_func("max")(a0, a1, a2, a3); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4, a5); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4, a5, a6); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4, a5, a6, a7); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4, a5, a6, a7, a8); -} - -BOOST_PYTHON_DECL object max(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::get_func("max")(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); -} - -BOOST_PYTHON_DECL object min(object const& a0) { - return api_detail::get_func("min")(a0); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1) { - return api_detail::get_func("min")(a0, a1); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("min")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::get_func("min")(a0, a1, a2, a3); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4, a5); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4, a5, a6); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4, a5, a6, a7); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4, a5, a6, a7, a8); -} - -BOOST_PYTHON_DECL object min(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::get_func("min")(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); -} - -BOOST_PYTHON_DECL object oct(object const& a0) { - return api_detail::get_func("oct")(a0); -} - -BOOST_PYTHON_DECL object oct(char a0) { - return api_detail::get_func("oct")(object(a0)); -} - -BOOST_PYTHON_DECL object oct(short a0) { - return api_detail::get_func("oct")(object(a0)); -} - -BOOST_PYTHON_DECL object oct(int a0) { - return api_detail::get_func("oct")(object(a0)); -} - -BOOST_PYTHON_DECL object oct(long a0) { - return api_detail::get_func("oct")(object(a0)); -} - -BOOST_PYTHON_DECL object open(object const& a0) { - return api_detail::get_func("open")(a0); -} - -BOOST_PYTHON_DECL object open(const char* a0) { - return api_detail::get_func("open")(object(a0)); -} - -BOOST_PYTHON_DECL object open(object const& a0, object const& a1) { - return api_detail::get_func("open")(a0, a1); -} - -BOOST_PYTHON_DECL object open(const char* a0, const char* a1) { - return api_detail::get_func("open")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object open(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("open")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object open(const char* a0, const char* a1, int a2) { - return api_detail::get_func("open")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL long ord(object const& a0) { - object r(api_detail::get_func("ord")(a0)); - return boost::python::arg_from_python(r.ptr())(r.ptr()); -} - -BOOST_PYTHON_DECL long ord(const char* a0) { - object r(api_detail::get_func("ord")(object(a0))); - return boost::python::arg_from_python(r.ptr())(r.ptr()); -} - -BOOST_PYTHON_DECL object pow(object const& a0, object const& a1) { - return api_detail::get_func("pow")(a0, a1); -} - -BOOST_PYTHON_DECL object pow(double const& a0, double const& a1) { - return api_detail::get_func("pow")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object pow(double const& a0, double const& a1, double const& a2) { - return api_detail::get_func("pow")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object print(object const& a0) { - return api_detail::call_statement_du("print _1", use_new_dict, 1, &a0); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1) { - return api_detail::call_statement_du("print _1, _2", use_new_dict, 2, &a0, &a1); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2) { - return api_detail::call_statement_du("print _1, _2, _3", use_new_dict, 3, &a0, &a1, &a2); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::call_statement_du("print _1, _2, _3, _4", use_new_dict, 4, &a0, &a1, &a2, &a3); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5", use_new_dict, 5, &a0, &a1, &a2, &a3, &a4); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5, _6", use_new_dict, 6, &a0, &a1, &a2, &a3, &a4, &a5); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5, _6, _7", use_new_dict, 7, &a0, &a1, &a2, &a3, &a4, &a5, &a6); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5, _6, _7, _8", use_new_dict, 8, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5, _6, _7, _8, _9", use_new_dict, 9, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8); -} - -BOOST_PYTHON_DECL object print(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::call_statement_du("print _1, _2, _3, _4, _5, _6, _7, _8, _9, _10", use_new_dict, 10, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1) { - return api_detail::call_statement_du("print >>_1, _2", use_new_dict, 2, &a0, &a1); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2) { - return api_detail::call_statement_du("print >>_1, _2, _3", use_new_dict, 3, &a0, &a1, &a2); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4", use_new_dict, 4, &a0, &a1, &a2, &a3); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5", use_new_dict, 5, &a0, &a1, &a2, &a3, &a4); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6", use_new_dict, 6, &a0, &a1, &a2, &a3, &a4, &a5); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6, _7", use_new_dict, 7, &a0, &a1, &a2, &a3, &a4, &a5, &a6); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6, _7, _8", use_new_dict, 8, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6, _7, _8, _9", use_new_dict, 9, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6, _7, _8, _9, _10", use_new_dict, 10, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9); -} - -BOOST_PYTHON_DECL object print_file(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9, object const& a10) { - return api_detail::call_statement_du("print >>_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11", use_new_dict, 11, &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10); -} - -BOOST_PYTHON_DECL object range(object const& a0) { - return api_detail::get_func("range")(a0); -} - -BOOST_PYTHON_DECL object range(int a0) { - return api_detail::get_func("range")(object(a0)); -} - -BOOST_PYTHON_DECL object range(object const& a0, object const& a1) { - return api_detail::get_func("range")(a0, a1); -} - -BOOST_PYTHON_DECL object range(int a0, int a1) { - return api_detail::get_func("range")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object range(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("range")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object range(int a0, int a1, int a2) { - return api_detail::get_func("range")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object raw_input() { - return api_detail::get_func("raw_input")(); -} - -BOOST_PYTHON_DECL object raw_input(object const& a0) { - return api_detail::get_func("raw_input")(a0); -} - -BOOST_PYTHON_DECL object raw_input(const char* a0) { - return api_detail::get_func("raw_input")(object(a0)); -} - -BOOST_PYTHON_DECL object reduce(object const& a0, object const& a1) { - return api_detail::get_func("reduce")(a0, a1); -} - -BOOST_PYTHON_DECL object reduce(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("reduce")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object reload(object const& a0) { - return object((python::detail::new_reference)::PyImport_ReloadModule(a0.ptr())); -} - -BOOST_PYTHON_DECL object repr(object const& a0) { - return object((python::detail::new_reference)::PyObject_Repr(a0.ptr())); -} - -BOOST_PYTHON_DECL object round(object const& a0) { - return api_detail::get_func("round")(a0); -} - -BOOST_PYTHON_DECL object round(double const& a0) { - return api_detail::get_func("round")(object(a0)); -} - -BOOST_PYTHON_DECL object round(object const& a0, object const& a1) { - return api_detail::get_func("round")(a0, a1); -} - -BOOST_PYTHON_DECL object round(double const& a0, double const& a1) { - return api_detail::get_func("round")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object slice(object const& a0) { - return api_detail::get_func("slice")(a0); -} - -BOOST_PYTHON_DECL object slice(int a0) { - return api_detail::get_func("slice")(object(a0)); -} - -BOOST_PYTHON_DECL object slice(object const& a0, object const& a1) { - return api_detail::get_func("slice")(a0, a1); -} - -BOOST_PYTHON_DECL object slice(int a0, int a1) { - return api_detail::get_func("slice")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object slice(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("slice")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object slice(int a0, int a1, int a2) { - return api_detail::get_func("slice")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object str(object const& a0) { - return object((python::detail::new_reference)::PyObject_Str(a0.ptr())); -} - -BOOST_PYTHON_DECL object tuple() { - return api_detail::get_func("tuple")(); -} - -BOOST_PYTHON_DECL object tuple(object const& a0) { - return api_detail::get_func("tuple")(a0); -} - -BOOST_PYTHON_DECL object type_(object const& a0) { - return object((python::detail::new_reference)::PyObject_Type(a0.ptr())); -} - -BOOST_PYTHON_DECL object unichr(object const& a0) { - return api_detail::get_func("unichr")(a0); -} - -BOOST_PYTHON_DECL object unichr(short a0) { - return api_detail::get_func("unichr")(object(a0)); -} - -BOOST_PYTHON_DECL object unichr(int a0) { - return api_detail::get_func("unichr")(object(a0)); -} - -BOOST_PYTHON_DECL object unichr(long a0) { - return api_detail::get_func("unichr")(object(a0)); -} - -BOOST_PYTHON_DECL object unicode(object const& a0) { - return object((python::detail::new_reference)::PyObject_Unicode(a0.ptr())); -} - -BOOST_PYTHON_DECL object unicode(object const& a0, object const& a1) { - return api_detail::get_func("unicode")(a0, a1); -} - -BOOST_PYTHON_DECL object unicode(object const& a0, const char* a1) { - return api_detail::get_func("unicode")(a0, object(a1)); -} - -BOOST_PYTHON_DECL object unicode(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("unicode")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object unicode(object const& a0, const char* a1, const char* a2) { - return api_detail::get_func("unicode")(a0, object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object vars() { - return api_detail::get_func("vars")(); -} - -BOOST_PYTHON_DECL object vars(object const& a0) { - return api_detail::get_func("vars")(a0); -} - -BOOST_PYTHON_DECL object xrange(object const& a0) { - return api_detail::get_func("xrange")(a0); -} - -BOOST_PYTHON_DECL object xrange(int a0) { - return api_detail::get_func("xrange")(object(a0)); -} - -BOOST_PYTHON_DECL object xrange(object const& a0, object const& a1) { - return api_detail::get_func("xrange")(a0, a1); -} - -BOOST_PYTHON_DECL object xrange(int a0, int a1) { - return api_detail::get_func("xrange")(object(a0), object(a1)); -} - -BOOST_PYTHON_DECL object xrange(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("xrange")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object xrange(int a0, int a1, int a2) { - return api_detail::get_func("xrange")(object(a0), object(a1), object(a2)); -} - -BOOST_PYTHON_DECL object zip(object const& a0) { - return api_detail::get_func("zip")(a0); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1) { - return api_detail::get_func("zip")(a0, a1); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2) { - return api_detail::get_func("zip")(a0, a1, a2); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3) { - return api_detail::get_func("zip")(a0, a1, a2, a3); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4, a5); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4, a5, a6); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4, a5, a6, a7); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4, a5, a6, a7, a8); -} - -BOOST_PYTHON_DECL object zip(object const& a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::get_func("zip")(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); -} - -BOOST_PYTHON_DECL object compile_string(const char* a0, const char* a1, int a2) { - return object((python::detail::new_reference)::Py_CompileString(const_cast(a0), const_cast(a1), a2)); -} - -BOOST_PYTHON_DECL int import_append_inittab(const char* a0, void(*a1)(void)) { - int r = ::PyImport_AppendInittab(const_cast(a0), a1); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL object import_add_module(const char* a0) { - return object((python::detail::borrowed_reference)::PyImport_AddModule(const_cast(a0))); -} - -BOOST_PYTHON_DECL object import_get_module_dict() { - return object((python::detail::borrowed_reference)::PyImport_GetModuleDict()); -} - -BOOST_PYTHON_DECL object import_import(object const& a0) { - return object((python::detail::new_reference)::PyImport_Import(a0.ptr())); -} - -BOOST_PYTHON_DECL object import_import(const char* a0) { - return object((python::detail::new_reference)::PyImport_Import(object(a0).ptr())); -} - -BOOST_PYTHON_DECL object import_import_module(const char* a0) { - return object((python::detail::new_reference)::PyImport_ImportModule(const_cast(a0))); -} - -BOOST_PYTHON_DECL object import_import_module_ex(const char* a0, object const& a1, object const& a2, object const& a3) { - return object((python::detail::new_reference)::PyImport_ImportModuleEx(const_cast(a0), a1.ptr(), a2.ptr(), a3.ptr())); -} - -BOOST_PYTHON_DECL object module_get_dict(object const& a0) { - return object((python::detail::borrowed_reference)::PyModule_GetDict(a0.ptr())); -} - -BOOST_PYTHON_DECL int object_print(object const& a0, FILE* a1, int a2) { - int r = ::PyObject_Print(a0.ptr(), a1, a2); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL object run_file(FILE* a0, const char* a1, int a2, object const& a3, object const& a4) { - return object((python::detail::new_reference)::PyRun_File(a0, const_cast(a1), a2, a3.ptr(), a4.ptr())); -} - -BOOST_PYTHON_DECL int run_simple_file(FILE* a0, const char* a1) { - int r = ::PyRun_SimpleFile(a0, const_cast(a1)); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL int run_simple_string(const char* a0) { - int r = ::PyRun_SimpleString(const_cast(a0)); - if(r == -1) - throw_error_already_set(); - return r; -} - -BOOST_PYTHON_DECL object run_string(const char* a0, int a1, object const& a2, object const& a3) { - return object((python::detail::new_reference)::PyRun_String(const_cast(a0), a1, a2.ptr(), a3.ptr())); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0) { - return api_detail::call_statement(a0); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1) { - return api_detail::call_statement_du(a0, a1); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1) { - return api_detail::call_statement(a0, 1, &a1); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2) { - return api_detail::call_statement(a0, 2, &a1, &a2); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3) { - return api_detail::call_statement(a0, 3, &a1, &a2, &a3); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4) { - return api_detail::call_statement(a0, 4, &a1, &a2, &a3, &a4); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::call_statement(a0, 5, &a1, &a2, &a3, &a4, &a5); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::call_statement(a0, 6, &a1, &a2, &a3, &a4, &a5, &a6); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::call_statement(a0, 7, &a1, &a2, &a3, &a4, &a5, &a6, &a7); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::call_statement(a0, 8, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::call_statement(a0, 9, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, object const& a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9, object const& a10) { - return api_detail::call_statement(a0, 10, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2) { - return api_detail::call_statement_du(a0, a1, 1, &a2); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3) { - return api_detail::call_statement_du(a0, a1, 2, &a2, &a3); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4) { - return api_detail::call_statement_du(a0, a1, 3, &a2, &a3, &a4); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5) { - return api_detail::call_statement_du(a0, a1, 4, &a2, &a3, &a4, &a5); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6) { - return api_detail::call_statement_du(a0, a1, 5, &a2, &a3, &a4, &a5, &a6); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7) { - return api_detail::call_statement_du(a0, a1, 6, &a2, &a3, &a4, &a5, &a6, &a7); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8) { - return api_detail::call_statement_du(a0, a1, 7, &a2, &a3, &a4, &a5, &a6, &a7, &a8); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9) { - return api_detail::call_statement_du(a0, a1, 8, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9, object const& a10) { - return api_detail::call_statement_du(a0, a1, 9, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10); -} - -BOOST_PYTHON_DECL object call_statement(const char* a0, call_dict_usage a1, object const& a2, object const& a3, object const& a4, object const& a5, object const& a6, object const& a7, object const& a8, object const& a9, object const& a10, object const& a11) { - return api_detail::call_statement_du(a0, a1, 10, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11); -} - - -}}} - diff --git a/src/types.cpp b/src/types.cpp deleted file mode 100644 index eae9adff..00000000 --- a/src/types.cpp +++ /dev/null @@ -1,1272 +0,0 @@ -// (C) Copyright David Abrahams 2000. Permission to copy, use, modify, sell and -// distribute this software is granted provided this copyright notice appears -// in all copies. This software is provided "as is" without express or implied -// warranty, and with no claim as to its suitability for any purpose. -// -// The author gratefully acknowleges the support of Dragon Systems, Inc., in -// producing this work. - -#define BOOST_PYTHON_SOURCE - -#include -#include -#include // for handle_exception() -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { namespace python { - -namespace -{ - using detail::type_object_base; - using detail::call_object; - - - // Define a family of forwarding functions that can be called from a - // PyTypeObject's slots. These functions dispatch through a (virtual) member - // function pointer in the type_object_base, and handle exceptions in a - // uniform way, preventing us from having to rewrite the dispatching code over - // and over. - - // Given a function object f with signature - // - // PyObject* f(PyTypeObject*,PyObject*) - // - // calls f inside of handle_exception, and returns the result. If an exception - // is thrown by f, returns 0. - template - PyObject* obj_call(PyObject* obj, F f) - { - PyObject* result; - return call_object(result, obj, f) ? 0 : result; - } - - // Call the given integer-returning function object inside of - // handle_exception, returning a value_holder. F is a function - // object with "signature" - // - // R F(PyTypeObject*, PyObject*) - // - // where R is an integer type. - template - R int_call(PyObject* obj, F f, R* = 0) - { - R result; - return call_object(result, obj, f) ? -1 : result; - } - - // Implemented in terms of obj_call, above - PyObject* call(PyObject* obj, PyObject* (type_object_base::*f)(PyObject*) const) - { - return obj_call(obj, bind(f, _1, _2)); - } - - // Implemented in terms of int_call, above - int call(PyObject* obj, int (type_object_base::*f)(PyObject*) const) - { - return int_call(obj, bind(f, _1, _2)); - } - - template - PyObject* call(PyObject* obj, PyObject* (type_object_base::*f)(PyObject*, A1) const, A1 a1) - { - return obj_call(obj, bind(f, _1, _2, a1)); - } - - template - int call(PyObject* obj, int (type_object_base::*f)(PyObject*, A1) const, A1 a1) - { - return int_call(obj, bind(f, _1, _2, a1)); - } - - template - PyObject* call(PyObject* obj, PyObject* (type_object_base::*f)(PyObject*, A1, A2) const, A1 a1, A2 a2) - { - return obj_call(obj, bind(f, _1, _2, a1, a2)); - } - - template - int call(PyObject* obj, int (type_object_base::*f)(PyObject*, A1, A2) const, A1 a1, A2 a2) - { - return int_call(obj, bind(f, _1, _2, a1, a2)); - } - - template - int call(PyObject* obj, int (type_object_base::*f)(PyObject*, A1, A2, A3) const, A1 a1, A2 a2, A3 a3) - { - return int_call(obj, bind(f, _1, _2, a1, a2, a3)); - } - - int call_length_function(PyObject* obj, int (type_object_base::*f)(PyObject*) const) - { - int result; - if (call_object(result, obj, bind(f, _1, _2))) - return -1; - - if (result >= 0) - return result; - - PyErr_SetString(PyExc_ValueError, "__len__() should return >= 0"); - return -1; - } -} // anonymous namespace - -extern "C" { - -// -// These functions actually go into the type object's slots, and dispatch to the -// "call" wrappers defined above. -// -static PyObject* do_instance_repr(PyObject* obj) -{ - return call(obj, &type_object_base::instance_repr); -} - -static PyObject* do_instance_richcompare(PyObject* obj, PyObject* other, int d) -{ -#if PYTHON_API_VERSION >= 1010 - switch(d) - { - case Py_LT: - return call(obj, &type_object_base::instance_lt, other); - case Py_LE: - return call(obj, &type_object_base::instance_le, other); - case Py_EQ: - return call(obj, &type_object_base::instance_eq, other); - case Py_NE: - return call(obj, &type_object_base::instance_ne, other); - case Py_GT: - return call(obj, &type_object_base::instance_gt, other); - case Py_GE: - return call(obj, &type_object_base::instance_ge, other); - } -#endif - return 0; -} - -static int do_instance_compare(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_compare, other); -} - -static PyObject* do_instance_str(PyObject* obj) -{ - return call(obj, &type_object_base::instance_str); -} - -static long do_instance_hash(PyObject* obj) -{ - return int_call(obj, bind(&type_object_base::instance_hash, _1, _2)); -} - -static PyObject* do_instance_call(PyObject* obj, PyObject* args, PyObject* keywords) -{ - return call(obj, &type_object_base::instance_call, args, keywords); -} - -static void do_instance_dealloc(PyObject* obj) -{ - if (handle_exception( - bind(&type_object_base::instance_dealloc - , static_cast(obj->ob_type) - , obj)) - ) - { - assert(!"exception during destruction!"); - } -} - -static PyObject* do_instance_getattr(PyObject* obj, char* name) -{ - const char* name_ = name; - return call(obj, &type_object_base::instance_getattr, name_); -} - -static int do_instance_setattr(PyObject* obj, char* name, PyObject* value) -{ - const char* name_ = name; - return call(obj, &type_object_base::instance_setattr, name_, value); -} - -static int do_instance_mp_length(PyObject* obj) -{ - return call_length_function(obj, &type_object_base::instance_mapping_length); -} - -static int do_instance_sq_length(PyObject* obj) -{ - return call_length_function(obj, &type_object_base::instance_sequence_length); -} - -static PyObject* do_instance_mp_subscript(PyObject* obj, PyObject* index) -{ - return call(obj, &type_object_base::instance_mapping_subscript, index); -} - -static PyObject* do_instance_sq_item(PyObject* obj, int index) -{ - // This is an extension to standard class behavior. If sequence_length - // is implemented and n >= sequence_length(), raise an IndexError. That - // keeps users from having to worry about raising it themselves - const PyTypeObject* const type = obj->ob_type; - if (type->tp_as_sequence != 0 && type->tp_as_sequence->sq_length != 0 - && index >= type->tp_as_sequence->sq_length(obj)) - { - PyErr_SetString(PyExc_IndexError, type->tp_name); - return 0; - } - - return obj_call( - obj - , bind(&type_object_base::instance_sequence_item, _1, _2, index)); -} - -static int do_instance_mp_ass_subscript(PyObject* obj, PyObject* index, PyObject* value) -{ - return call(obj, &type_object_base::instance_mapping_ass_subscript, index, value); -} - -static int do_instance_sq_ass_item(PyObject* obj, int index, PyObject* value) -{ - return call(obj, &type_object_base::instance_sequence_ass_item, index, value); -} - -static PyObject* do_instance_sq_concat(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_sequence_concat, other); -} - -static PyObject* do_instance_sq_repeat(PyObject* obj, int n) -{ - return call(obj, &type_object_base::instance_sequence_repeat, n); -} - -static PyObject* do_instance_sq_slice( - PyObject* obj, int start, int finish) -{ - return call(obj, &type_object_base::instance_sequence_slice, start, finish); -} - -static int do_instance_sq_ass_slice( - PyObject* obj, int start, int finish, PyObject* value) -{ - return call(obj, &type_object_base::instance_sequence_ass_slice, start, finish, value); -} - -static PyObject* do_instance_nb_add(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_add, other); -} - -static PyObject* do_instance_nb_subtract(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_subtract, other); -} - -static PyObject* do_instance_nb_multiply(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_multiply, other); -} - -static PyObject* do_instance_nb_divide(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_divide, other); -} - -static PyObject* do_instance_nb_remainder(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_remainder, other); -} - -static PyObject* do_instance_nb_divmod(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_divmod, other); -} - -static PyObject* do_instance_nb_power(PyObject* obj, PyObject* exponent, PyObject* modulus) -{ - return call(obj, &type_object_base::instance_number_power, exponent, modulus); -} - -static PyObject* do_instance_nb_negative(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_negative); -} - -static PyObject* do_instance_nb_positive(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_positive); -} - -static PyObject* do_instance_nb_absolute(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_absolute); -} - -static int do_instance_nb_nonzero(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_nonzero); -} - -static PyObject* do_instance_nb_invert(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_invert); -} - - -static PyObject* do_instance_nb_lshift(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_lshift, other); -} - -static PyObject* do_instance_nb_rshift(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_rshift, other); -} - -static PyObject* do_instance_nb_and(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_and, other); -} - -static PyObject* do_instance_nb_xor(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_xor, other); -} - -static PyObject* do_instance_nb_or(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_or, other); -} - -static int do_instance_nb_coerce(PyObject**obj, PyObject**other) -{ - // no call() overload for this oddball function, so we'll do it manually - return int_call( - *obj, bind( - &type_object_base::instance_number_coerce, _1, _2, obj, other)); -} -static PyObject* do_instance_nb_int(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_int); -} - -static PyObject* do_instance_nb_long(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_long); -} - -static PyObject* do_instance_nb_float(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_float); -} - -static PyObject* do_instance_nb_oct(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_oct); -} - -static PyObject* do_instance_nb_hex(PyObject* obj) -{ - return call(obj, &type_object_base::instance_number_hex); -} - -static PyObject* do_instance_nb_inplace_add(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_add, other); -} - -static PyObject* do_instance_nb_inplace_subtract(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_subtract, other); -} - -static PyObject* do_instance_nb_inplace_multiply(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_multiply, other); -} - -static PyObject* do_instance_nb_inplace_divide(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_divide, other); -} - -static PyObject* do_instance_nb_inplace_remainder(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_remainder, other); -} - -static PyObject* do_instance_nb_inplace_power(PyObject* obj, PyObject* exponent, PyObject* modulus) -{ - return call(obj, &type_object_base::instance_number_inplace_power, exponent, modulus); -} - -static PyObject* do_instance_nb_inplace_lshift(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_lshift, other); -} - -static PyObject* do_instance_nb_inplace_rshift(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_rshift, other); -} - -static PyObject* do_instance_nb_inplace_and(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_and, other); -} - -static PyObject* do_instance_nb_inplace_or(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_or, other); -} - -static PyObject* do_instance_nb_inplace_xor(PyObject* obj, PyObject* other) -{ - return call(obj, &type_object_base::instance_number_inplace_xor, other); -} - -} // extern "C" - -namespace -{ - -#define ENABLE_GENERAL_CAPABILITY(field) \ - case type_object_base::field: \ - dest->tp_##field = &do_instance_##field; \ - return true - -bool add_capability_general(type_object_base::capability capability, PyTypeObject* dest) -{ - assert(dest != 0); - - switch(capability) - { - ENABLE_GENERAL_CAPABILITY(hash); - ENABLE_GENERAL_CAPABILITY(call); - ENABLE_GENERAL_CAPABILITY(str); - ENABLE_GENERAL_CAPABILITY(getattr); - ENABLE_GENERAL_CAPABILITY(setattr); - ENABLE_GENERAL_CAPABILITY(compare); - ENABLE_GENERAL_CAPABILITY(repr); - default: - return false; - } -} - - -template -void create_method_table_if_null(T*& table) -{ - if(table == 0) - { - detail::shared_pod_manager::create(table); - } - else - { - detail::shared_pod_manager::make_unique_copy(table); - } -} - -bool add_capability_richcompare(type_object_base::capability capability, PyTypeObject* dest) -{ - assert(dest != 0); - if (capability == type_object_base::richcompare) { -#if PYTHON_API_VERSION >= 1010 - dest->tp_richcompare = &do_instance_richcompare; - dest->tp_flags |= Py_TPFLAGS_HAVE_RICHCOMPARE; -#endif - return true; - } - - return false; -} - -#define ENABLE_INPLACE_CAPABILITY(field) \ - case type_object_base::number_##field: \ - create_method_table_if_null(dest->tp_as_number); \ - dest->tp_as_number->nb_##field = &do_instance_nb_##field; \ - detail::shared_pod_manager::replace_if_equal(dest->tp_as_number); \ - dest->tp_flags |= Py_TPFLAGS_HAVE_INPLACEOPS; \ - return true - -bool add_capability_inplace(type_object_base::capability capability, PyTypeObject* dest) -{ - assert(dest != 0); - switch (capability) - { -#if PYTHON_API_VERSION >= 1010 - ENABLE_INPLACE_CAPABILITY (inplace_add); - ENABLE_INPLACE_CAPABILITY (inplace_subtract); - ENABLE_INPLACE_CAPABILITY (inplace_multiply); - ENABLE_INPLACE_CAPABILITY (inplace_divide); - ENABLE_INPLACE_CAPABILITY (inplace_remainder); - ENABLE_INPLACE_CAPABILITY (inplace_power); - ENABLE_INPLACE_CAPABILITY (inplace_lshift); - ENABLE_INPLACE_CAPABILITY (inplace_rshift); - ENABLE_INPLACE_CAPABILITY (inplace_and); - ENABLE_INPLACE_CAPABILITY (inplace_or); - ENABLE_INPLACE_CAPABILITY (inplace_xor); -#endif - default: - return false; - } -} - -#define ENABLE_MAPPING_CAPABILITY(field) \ - case type_object_base::mapping_##field: \ - create_method_table_if_null(dest); \ - dest->mp_##field = &do_instance_mp_##field; \ - detail::shared_pod_manager::replace_if_equal(dest); \ - return true - -bool add_capability_mapping(type_object_base::capability capability, PyMappingMethods*& dest) -{ - switch(capability) - { - ENABLE_MAPPING_CAPABILITY(length); - ENABLE_MAPPING_CAPABILITY(subscript); - ENABLE_MAPPING_CAPABILITY(ass_subscript); - default: - return false; - } -} - -#define ENABLE_SEQUENCE_CAPABILITY(field) \ - case type_object_base::sequence_##field: \ - create_method_table_if_null(dest); \ - dest->sq_##field = &do_instance_sq_##field; \ - detail::shared_pod_manager::replace_if_equal(dest); \ - return true - -bool add_capability_sequence(type_object_base::capability capability, PySequenceMethods*& dest) -{ - switch(capability) - { - ENABLE_SEQUENCE_CAPABILITY(length); - ENABLE_SEQUENCE_CAPABILITY(item); - ENABLE_SEQUENCE_CAPABILITY(ass_item); - ENABLE_SEQUENCE_CAPABILITY(concat); - ENABLE_SEQUENCE_CAPABILITY(repeat); - ENABLE_SEQUENCE_CAPABILITY(slice); - ENABLE_SEQUENCE_CAPABILITY(ass_slice); - default: - return false; - } -} - -#define ENABLE_NUMBER_CAPABILITY(field) \ - case type_object_base::number_##field: \ - create_method_table_if_null(dest); \ - dest->nb_##field = &do_instance_nb_##field; \ - detail::shared_pod_manager::replace_if_equal(dest); \ - return true - -bool add_capability_number(type_object_base::capability capability, PyNumberMethods*& dest) -{ - switch(capability) - { - ENABLE_NUMBER_CAPABILITY(add); - ENABLE_NUMBER_CAPABILITY(subtract); - ENABLE_NUMBER_CAPABILITY(multiply); - ENABLE_NUMBER_CAPABILITY(divide); - ENABLE_NUMBER_CAPABILITY(remainder); - ENABLE_NUMBER_CAPABILITY(divmod); - ENABLE_NUMBER_CAPABILITY(power); - ENABLE_NUMBER_CAPABILITY(negative); - ENABLE_NUMBER_CAPABILITY(positive); - ENABLE_NUMBER_CAPABILITY(absolute); - ENABLE_NUMBER_CAPABILITY(nonzero); - ENABLE_NUMBER_CAPABILITY(invert); - ENABLE_NUMBER_CAPABILITY(lshift); - ENABLE_NUMBER_CAPABILITY(rshift); - ENABLE_NUMBER_CAPABILITY(and); - ENABLE_NUMBER_CAPABILITY(xor); - ENABLE_NUMBER_CAPABILITY(or); - ENABLE_NUMBER_CAPABILITY(coerce); - ENABLE_NUMBER_CAPABILITY(int); - ENABLE_NUMBER_CAPABILITY(long); - ENABLE_NUMBER_CAPABILITY(float); - ENABLE_NUMBER_CAPABILITY(oct); - ENABLE_NUMBER_CAPABILITY(hex); - default: - return false; - } -} - -#define ENABLE_BUFFER_CAPABILITY(field) \ - case type_object_base::buffer_##field: \ - create_method_table_if_null(dest); \ - dest->bf_##field = &do_instance_bf_##field; \ - detail::shared_pod_manager::replace_if_equal(dest); \ - return true - -bool add_capability_buffer(type_object_base::capability capability, PyBufferProcs*& dest) -{ - (void)dest; // suppress unused argument warning - (void)capability; // likwise -#if 0 - switch(capability) - { - // nothing defined yet - default: - return false; - } -#endif - return false; -} - -} // anonymous namespace - -namespace detail { - - void add_capability( - type_object_base::capability capability, - PyTypeObject* dest_) - { - if(add_capability_general(capability, dest_)) - return; - if(add_capability_richcompare(capability, dest_)) - return; - if(add_capability_inplace(capability, dest_)) - return; - if(add_capability_mapping(capability, dest_->tp_as_mapping)) - return; - if(add_capability_sequence(capability, dest_->tp_as_sequence)) - return; - if(add_capability_number(capability, dest_->tp_as_number)) - return; - if(add_capability_buffer(capability, dest_->tp_as_buffer)) - return; - - // no one recognized the capability - throw std::runtime_error("py::detail::add_capability(): unknown capability"); - } -} // namespace detail - -type_object_base::~type_object_base() -{ - detail::shared_pod_manager::dispose(tp_as_mapping); - detail::shared_pod_manager::dispose(tp_as_sequence); - detail::shared_pod_manager::dispose(tp_as_number); - detail::shared_pod_manager::dispose(tp_as_buffer); -} - -void type_object_base::enable(type_object_base::capability capability) -{ - detail::add_capability(capability, this); -} - -type_object_base::type_object_base(PyTypeObject* t) - : python_type(t) -{ - this->tp_dealloc = do_instance_dealloc; -} - -namespace -{ - typedef long pod_refcount; - - inline pod_refcount pod_refcount_offset(std::size_t size) - { - const std::size_t alignment = boost::alignment_of::value; - return (size + alignment - 1) / alignment * alignment; - } - - inline pod_refcount* counted_pod_refcount(char* pod, std::size_t size) - { - if(pod == 0) - return 0; - - return reinterpret_cast(pod + pod_refcount_offset(size)); - } - - #ifdef TYPE_OBJECT_BASE_STANDALONE_TEST - int pod_instance_counter = 0; - #endif - - inline pod_refcount counted_pod_getref(char* pod, std::size_t size) - { - pod_refcount* ref_count = counted_pod_refcount(pod, size); - return ref_count == 0 ? -1 : *ref_count; - } - - inline pod_refcount counted_pod_decref(char* pod, std::size_t size) - { - pod_refcount* const ref_count = counted_pod_refcount(pod, size); - if (ref_count == 0) - return -1; - --(*ref_count); - if (*ref_count <= 0) - { - #ifdef TYPE_OBJECT_BASE_STANDALONE_TEST - --pod_instance_counter; - #endif - ::operator delete(pod); - return 0; - } - return *ref_count; - } - - pod_refcount counted_pod_incref(char* pod, std::size_t size) - { - pod_refcount* ref_count = counted_pod_refcount(pod, size); - return ref_count == 0 ? -1 : ++(*ref_count); - } - -} // anonymous namespace - -namespace detail -{ - struct shared_pod_manager::compare - { - bool operator()(const std::pair& x1, - const std::pair& x2) const - { - const std::size_t n1 = x1.second; - const std::size_t n2 = x2.second; - return n1 < n2 || n1 == n2 && BOOST_CSTD_::memcmp(x1.first, x2.first, n1) < 0; - } - }; - - struct shared_pod_manager::identical - { - identical(char* p) : pod(p) {} - - bool operator()(const std::pair& x) const - { - return pod == x.first; - } - - char* pod; - }; - - shared_pod_manager& shared_pod_manager::obj() - { - static shared_pod_manager spm; - return spm; - } - - shared_pod_manager::~shared_pod_manager() - { - } - - void* shared_pod_manager::replace_if_equal(void* pod, std::size_t size) - { - if(pod == 0) - return 0; - - const holder element(static_cast(pod), size); - - const storage::iterator found - = std::lower_bound(m_storage.begin(), m_storage.end(), element, compare()); - - if (found != m_storage.end() && pod == found->first) - { - // pod already in list => do nothing - return pod; - } - else if (found != m_storage.end() && !compare()(element, *found)) - { - // equal element in list => replace - void* replacement = found->first; - counted_pod_incref(found->first, size); - dec_ref(element.first, size); // invalidates iterator 'found' - return replacement; - } - else - { - // new element => insert - m_storage.insert(found, element); - return pod; - } - } - - void* shared_pod_manager::make_unique_copy(void* pod, std::size_t size) - { - if(pod == 0) - return 0; - if(counted_pod_getref(static_cast(pod), size) == 1) - { - erase_from_list(pod); - return pod; - } - else - { - void* copy = create(size); - memmove(copy, pod, size); - dec_ref(pod, size); - return copy; - } - } - - void* shared_pod_manager::create(std::size_t size) - { - std::size_t total_size = pod_refcount_offset(size) + sizeof(pod_refcount); - char* pod = static_cast(::operator new(total_size)); - #ifdef TYPE_OBJECT_BASE_STANDALONE_TEST - ++pod_instance_counter; - #endif - memset(pod, 0, total_size); - - *counted_pod_refcount(pod, size) = 1; - - return pod; - } - - void shared_pod_manager::dec_ref(void* pod, std::size_t size) - { - if(pod == 0) - return; - - int ref_count = counted_pod_decref(static_cast(pod), size); - - if(ref_count <= 0) - erase_from_list(pod); - } - - void shared_pod_manager::erase_from_list(void* pod) - { - if(pod == 0) - return; - - const storage::iterator found = - std::find_if(m_storage.begin(), m_storage.end(), - identical(static_cast(pod))); - - if(found != m_storage.end()) - { - m_storage.erase(found); - } - } -} // namespace detail - -namespace { - struct error_type { - operator PyObject*() const { return 0; } - operator int() const { return -1; } - }; - - error_type unimplemented(const char* name) - { - assert(!"Control should never reach here"); - string s("Unimplemented "); - s += string(name); - PyErr_SetObject(PyExc_RuntimeError, s.get()); - return error_type(); - } -} - -PyObject* type_object_base::instance_repr(PyObject*) const -{ - return unimplemented("instance_repr"); -} - -int type_object_base::instance_compare(PyObject*, PyObject*) const -{ - return unimplemented("instance_compare"); -} - -PyObject* type_object_base::instance_str(PyObject*) const -{ - return unimplemented("instance_str"); -} - -long type_object_base::instance_hash(PyObject* /* obj */) const -{ - return unimplemented("instance_hash"); -} - -PyObject* type_object_base::instance_call(PyObject* /*obj*/, PyObject* /*args*/, PyObject* /*kw*/) const -{ - return unimplemented("instance_call"); -} - -PyObject* type_object_base::instance_getattr(PyObject* /*obj*/, const char* /*name*/) const -{ - return unimplemented("instance_getattr"); -} - -int type_object_base::instance_setattr(PyObject* /*obj*/, const char* /*name*/, PyObject* /*value*/) const -{ - return unimplemented("instance_setattr"); -} - -int type_object_base::instance_mapping_length(PyObject*) const -{ - return unimplemented("instance_mapping_length"); -} - -int type_object_base::instance_sequence_length(PyObject*) const -{ - return unimplemented("instance_sequence_length"); -} - -PyObject* type_object_base::instance_mapping_subscript(PyObject*, PyObject*) const -{ - return unimplemented("instance_mapping_subscript"); -} - -PyObject* type_object_base::instance_sequence_item(PyObject*, int) const -{ - return unimplemented("instance_sequence_item"); -} - -int type_object_base::instance_mapping_ass_subscript(PyObject*, PyObject*, PyObject*) const -{ - return unimplemented("instance_mapping_ass_subscript"); -} - -int type_object_base::instance_sequence_ass_item(PyObject*, int, PyObject*) const -{ - return unimplemented("instance_sequence_ass_item"); -} - -PyObject* type_object_base::instance_sequence_concat(PyObject*, PyObject*) const -{ - return unimplemented("instance_sequence_concat"); -} - -PyObject* type_object_base::instance_sequence_repeat(PyObject*, int) const -{ - return unimplemented("instance_sequence_repeat"); -} - -PyObject* type_object_base::instance_sequence_slice(PyObject*, int, int) const -{ - return unimplemented("instance_sequence_slice"); -} - -int type_object_base::instance_sequence_ass_slice(PyObject*, int, int, PyObject*) const -{ - return unimplemented("instance_sequence_ass_slice"); -} - -PyObject* type_object_base::instance_number_add(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_add"); -} - -PyObject* type_object_base::instance_number_subtract(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_subtract"); -} - -PyObject* type_object_base::instance_number_multiply(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_multiply"); -} - -PyObject* type_object_base::instance_number_divide(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_divide"); -} - -PyObject* type_object_base::instance_number_remainder(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_remainder"); -} - -PyObject* type_object_base::instance_number_divmod(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_divmod"); -} - -PyObject* type_object_base::instance_number_power(PyObject*, PyObject*, PyObject*) const -{ - return unimplemented("instance_number_power"); -} - -PyObject* type_object_base::instance_number_negative(PyObject*) const -{ - return unimplemented("instance_number_negative"); -} - -PyObject* type_object_base::instance_number_positive(PyObject*) const -{ - return unimplemented("instance_number_positive"); -} - -PyObject* type_object_base::instance_number_absolute(PyObject*) const -{ - return unimplemented("instance_number_absolute"); -} - -int type_object_base::instance_number_nonzero(PyObject*) const -{ - return unimplemented("instance_number_nonzero"); -} - -PyObject* type_object_base::instance_number_invert(PyObject*) const -{ - return unimplemented("instance_number_invert"); -} - -PyObject* type_object_base::instance_number_lshift(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_lshift"); -} - -PyObject* type_object_base::instance_number_rshift(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_rshift"); -} - -PyObject* type_object_base::instance_number_and(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_and"); -} - -PyObject* type_object_base::instance_number_xor(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_xor"); -} - -PyObject* type_object_base::instance_number_or(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_or"); -} - -int type_object_base::instance_number_coerce(PyObject*, PyObject**, PyObject**) const -{ - return unimplemented("instance_number_coerce"); -} - -PyObject* type_object_base::instance_number_int(PyObject*) const -{ - return unimplemented("instance_number_int"); -} - -PyObject* type_object_base::instance_number_long(PyObject*) const -{ - return unimplemented("instance_number_long"); -} - -PyObject* type_object_base::instance_number_float(PyObject*) const -{ - return unimplemented("instance_number_float"); -} - -PyObject* type_object_base::instance_number_oct(PyObject*) const -{ - return unimplemented("instance_number_oct"); -} - -PyObject* type_object_base::instance_number_hex(PyObject*) const -{ - return unimplemented("instance_number_hex"); -} - -PyObject* type_object_base::instance_number_inplace_add(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_add"); -} - -PyObject* type_object_base::instance_number_inplace_subtract(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_subtract"); -} - -PyObject* type_object_base::instance_number_inplace_multiply(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_multiply"); -} - -PyObject* type_object_base::instance_number_inplace_divide(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_divide"); -} - -PyObject* type_object_base::instance_number_inplace_remainder(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_remainder"); -} - -PyObject* type_object_base::instance_number_inplace_power(PyObject*, PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_power"); -} - -PyObject* type_object_base::instance_number_inplace_lshift(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_lshift"); -} - -PyObject* type_object_base::instance_number_inplace_rshift(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_rshift"); -} - -PyObject* type_object_base::instance_number_inplace_and(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_and"); -} - -PyObject* type_object_base::instance_number_inplace_or(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_or"); -} - -PyObject* type_object_base::instance_number_inplace_xor(PyObject*, PyObject*) const -{ - return unimplemented("instance_number_inplace_xor"); -} - -PyObject* type_object_base::instance_lt(PyObject*, PyObject*) const -{ - return unimplemented("instance_lt"); -} - -PyObject* type_object_base::instance_le(PyObject*, PyObject*) const -{ - return unimplemented("instance_le"); -} - -PyObject* type_object_base::instance_eq(PyObject*, PyObject*) const -{ - return unimplemented("instance_eq"); -} - -PyObject* type_object_base::instance_ne(PyObject*, PyObject*) const -{ - return unimplemented("instance_ne"); -} - -PyObject* type_object_base::instance_gt(PyObject*, PyObject*) const -{ - return unimplemented("instance_gt"); -} - -PyObject* type_object_base::instance_ge(PyObject*, PyObject*) const -{ - return unimplemented("instance_ge"); -} - -}} // namespace boost::python - -#ifdef TYPE_OBJECT_BASE_STANDALONE_TEST - -struct TestTypeObject : boost::python::type_object_base -{ - TestTypeObject() - : boost::python::type_object_base(Py_None->ob_type->ob_type) - {} - - void instance_dealloc(PyObject*) const {} -}; - -struct POD1 -{ - unsigned char data; -}; - -int main() -{ - boost::python::type_object_base *o1, *o2, *o3; - -// POD1 * pod1; -// boost::python::detail::shared_pod_manager::create(pod1); - - o1 = new TestTypeObject; - o2 = new TestTypeObject; - o3 = new TestTypeObject; - - assert(boost::python::pod_instance_counter == 0); - - o1->enable(boost::python::type_object_base::number_add); - o1->enable(boost::python::type_object_base::compare); - - o2->enable(boost::python::type_object_base::number_add); - o2->enable(boost::python::type_object_base::mapping_length); - - o3->enable(boost::python::type_object_base::number_add); - o3->enable(boost::python::type_object_base::sequence_length); - - assert(boost::python::pod_instance_counter == 3); - assert(o1->tp_as_number && !o1->tp_as_mapping && !o1->tp_as_sequence); - assert(o2->tp_as_number && o2->tp_as_mapping && !o2->tp_as_sequence); - assert(o3->tp_as_number && !o3->tp_as_mapping && o3->tp_as_sequence); - assert(o1->tp_as_number == o2->tp_as_number); - assert(o1->tp_as_number == o3->tp_as_number); - assert((void*)o2->tp_as_number != o2->tp_as_mapping); - assert((void*)o2->tp_as_mapping != o3->tp_as_sequence); - - o1->enable(boost::python::type_object_base::number_subtract); - - assert(boost::python::pod_instance_counter == 4); - assert(o1->tp_as_number != o2->tp_as_number); - assert(o2->tp_as_number == o3->tp_as_number); - - o3->enable(boost::python::type_object_base::mapping_subscript); - - assert(boost::python::pod_instance_counter == 5); - assert(o3->tp_as_number && o3->tp_as_mapping && o3->tp_as_sequence); - assert(o2->tp_as_mapping != o3->tp_as_mapping); - - o2->enable(boost::python::type_object_base::mapping_subscript); - o3->enable(boost::python::type_object_base::mapping_length); - - assert(boost::python::pod_instance_counter == 4); - assert(o2->tp_as_number && o2->tp_as_mapping && !o2->tp_as_sequence); - assert(o3->tp_as_number && o3->tp_as_mapping && o3->tp_as_sequence); - assert(o2->tp_as_mapping == o3->tp_as_mapping); - - boost::python::type_object_base *o4 = new TestTypeObject; - - assert(boost::python::pod_instance_counter == 4); - - o4->enable(boost::python::type_object_base::number_add); - - assert(boost::python::pod_instance_counter == 4); - assert(o4->tp_as_number && !o4->tp_as_mapping && !o4->tp_as_sequence); - assert(o4->tp_as_number == o3->tp_as_number); - - delete o3; - - assert(boost::python::pod_instance_counter == 3); - assert(o1->tp_as_number && !o1->tp_as_mapping && !o1->tp_as_sequence); - assert(o2->tp_as_number && o2->tp_as_mapping && !o2->tp_as_sequence); - assert(o4->tp_as_number && !o4->tp_as_mapping && !o4->tp_as_sequence); - assert(o4->tp_as_number == o2->tp_as_number); - - o3 = new TestTypeObject; - - assert(boost::python::pod_instance_counter == 3); - - o3->enable(boost::python::type_object_base::number_add); - o3->enable(boost::python::type_object_base::sequence_length); - - assert(boost::python::pod_instance_counter == 4); - assert(o3->tp_as_number && !o3->tp_as_mapping && o3->tp_as_sequence); - assert(o1->tp_as_number != o3->tp_as_number); - assert(o2->tp_as_number == o3->tp_as_number); - - delete o1; - - assert(boost::python::pod_instance_counter == 3); - - delete o4; - - assert(boost::python::pod_instance_counter == 3); - - delete o3; - - assert(boost::python::pod_instance_counter == 2); - - delete o2; - - assert(boost::python::pod_instance_counter == 0); - - assert(boost::python::detail::shared_pod_manager::obj().m_storage.size() == 0); -} - -#endif