From a143441eac2aa91654a0298642c24ef2427b0322 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 2 Sep 2008 11:06:24 +0100 Subject: [PATCH] Revamp type matching system and const handling, is_const becomes deprecated. Now types are specified with consts inside the type string, is_const is deprecated. The ctypeparser utility module, previously only used to canonicalize type strings, is used more extensively throughout pybindgen to provide type traits and type manipulation, where needed. gccxml type traits no longer used as consequence. --- pybindgen/__init__.py | 3 + pybindgen/cppclass.py | 4 +- pybindgen/cppclass_typehandlers.py | 42 ++-- pybindgen/gccxmlparser.py | 159 +++++--------- pybindgen/typehandlers/base.py | 137 +++++++----- .../typehandlers/ctypeparser/__init__.py | 195 +++++++++++++++++- pybindgen/typehandlers/inttype.py | 27 ++- pybindgen/typehandlers/pyobjecttype.py | 4 +- pybindgen/typehandlers/stringtype.py | 4 +- tests/foo.h | 2 +- tests/foomodulegen.py | 22 +- tests/foomodulegen_common.py | 2 +- tests/test-generation.py | 8 +- 13 files changed, 394 insertions(+), 215 deletions(-) diff --git a/pybindgen/__init__.py b/pybindgen/__init__.py index b277c15..2dc95b2 100644 --- a/pybindgen/__init__.py +++ b/pybindgen/__init__.py @@ -657,3 +657,6 @@ from enum import Enum from utils import write_preamble, param, retval import version +import logging +#logging.basicConfig(level=logging.DEBUG) +del logging diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 745dd85..adb025b 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -1197,8 +1197,8 @@ public: Utility method to add a 'copy constructor' method to this class. """ try: - constructor = CppConstructor([self.ThisClassRefParameter("%s &" % self.full_name, - 'ctor_arg', is_const=True)]) + constructor = CppConstructor([self.ThisClassRefParameter("const %s &" % self.full_name, + 'ctor_arg')]) except utils.SkipWrapper: return None constructor.stack_where_defined = traceback.extract_stack() diff --git a/pybindgen/cppclass_typehandlers.py b/pybindgen/cppclass_typehandlers.py index 2a701e6..2ca62a8 100644 --- a/pybindgen/cppclass_typehandlers.py +++ b/pybindgen/cppclass_typehandlers.py @@ -39,8 +39,8 @@ class CppClassReturnValueBase(ReturnValue): CTYPES = [] cpp_class = cppclass.CppClass('dummy') # CppClass instance - def __init__(self, ctype): - super(CppClassReturnValueBase, self).__init__(ctype) + def __init__(self, ctype, is_const=False): + super(CppClassReturnValueBase, self).__init__(ctype, is_const=is_const) ## name of the PyFoo * variable used in return value building self.py_name = None @@ -183,7 +183,7 @@ class CppClassRefParameter(CppClassParameterBase): '*((%s *) %s)->obj' % (self.cpp_class.pystruct, self.py_name)) else: implicit_conversion_sources = self.cpp_class.get_all_implicit_conversions() - if not (implicit_conversion_sources and self.is_const): + if not (implicit_conversion_sources and self.type_traits.target_is_const): if self.default_value is not None: self.py_name = wrapper.declarations.declare_variable( self.cpp_class.pystruct+'*', self.name, 'NULL') @@ -314,7 +314,7 @@ class CppClassRefParameter(CppClassParameterBase): ## the ->obj pointer after the python call; this is so ## that the python code directly manipulates the object ## received as parameter, instead of a copy. - if self.is_const: + if self.type_traits.target_is_const: value = "(%s*) (&(%s))" % (self.cpp_class.full_name, self.value) else: value = "&(%s)" % self.value @@ -352,8 +352,7 @@ class CppClassReturnValue(CppClassReturnValueBase): """override to fix the ctype parameter with namespace information""" if ctype == self.cpp_class.name: ctype = self.cpp_class.full_name - super(CppClassReturnValue, self).__init__(ctype) - self.is_const = is_const + super(CppClassReturnValue, self).__init__(ctype, is_const=is_const) def get_c_error_return(self): # only used in reverse wrappers """See ReturnValue.get_c_error_return""" @@ -442,7 +441,10 @@ class CppClassPtrParameter(CppClassParameterBase): if custodian is None: if transfer_ownership is None: - raise TypeConfigurationError("transfer_ownership parameter missing") + if self.type_traits.target_is_const: + transfer_ownership = False + else: + raise TypeConfigurationError("transfer_ownership parameter missing") self.transfer_ownership = transfer_ownership else: if transfer_ownership is not None: @@ -574,7 +576,7 @@ class CppClassPtrParameter(CppClassParameterBase): ## the ->obj pointer after the python call; this is so ## that the python code directly manipulates the object ## received as parameter, instead of a copy. - if self.is_const: + if self.type_traits.target_is_const: unconst_value = "(%s*) (%s)" % (self.cpp_class.full_name, value) else: unconst_value = value @@ -601,7 +603,7 @@ class CppClassPtrParameter(CppClassParameterBase): else: ## The PyObject gets a new reference to the same obj self.cpp_class.memory_policy.write_incref(wrapper.before_call, value) - if self.is_const: + if self.type_traits.target_is_const: wrapper.before_call.write_code("%s->obj = (%s*) (%s);" % (py_name, self.cpp_class.full_name, value)) else: @@ -630,7 +632,7 @@ class CppClassPtrParameter(CppClassParameterBase): % (value, self.cpp_class.helper_class.name)) wrapper.before_call.indent() - if self.is_const: + if self.type_traits.target_is_const: wrapper.before_call.write_code( "%s = (%s*) (((%s*) ((%s*) %s))->m_pyself);" % (py_name, self.cpp_class.pystruct, @@ -714,10 +716,16 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): """ if ctype == self.cpp_class.name: ctype = self.cpp_class.full_name - super(CppClassPtrReturnValue, self).__init__(ctype) - self.is_const = is_const - if custodian is None and caller_owns_return is None: - raise TypeConfigurationError("caller_owns_return not given") + super(CppClassPtrReturnValue, self).__init__(ctype, is_const=is_const) + if custodian is None: + if caller_owns_return is None: + if self.type_traits.target_is_const: + caller_owns_return = False + else: + raise TypeConfigurationError("caller_owns_return not given") + else: + if caller_owns_return is not None: + raise TypeConfigurationError("caller_owns_return should not given together with custodian") self.custodian = custodian if custodian is None: self.caller_owns_return = caller_owns_return @@ -793,7 +801,7 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): else: ## The PyObject gets a new reference to the same obj self.cpp_class.memory_policy.write_incref(wrapper.after_call, value) - if self.is_const: + if self.type_traits.target_is_const: wrapper.after_call.write_code("%s->obj = (%s*) (%s);" % (py_name, self.cpp_class.full_name, value)) else: @@ -832,7 +840,7 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): % (value, self.cpp_class.helper_class.name)) wrapper.after_call.indent() - if self.is_const: + if self.type_traits.target_is_const: const_cast_value = "const_cast<%s *>(%s) " % (self.cpp_class.full_name, value) else: const_cast_value = value @@ -921,7 +929,7 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): else: ## the caller gets a new reference to the same obj self.cpp_class.memory_policy.write_incref(wrapper.after_call, value) - if self.is_const: + if self.type_traits.target_is_const: wrapper.after_call.write_code( "%s = const_cast< %s* >(%s);" % (self.value, self.cpp_class.full_name, value)) diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index 4ae1ab2..b68e4d5 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -9,6 +9,7 @@ from pygccxml import declarations from module import Module from typehandlers.codesink import FileCodeSink, CodeSink, NullCodeSink import typehandlers.base +from typehandlers.base import ctypeparser from typehandlers.base import ReturnValue, Parameter, TypeLookupError, TypeConfigurationError, NotSupportedError from pygccxml.declarations.enumeration import enumeration_t from cppclass import CppClass, ReferenceCountingMethodsPolicy, FreeFunctionPolicy, ReferenceCountingFunctionsPolicy @@ -195,47 +196,54 @@ class GccXmlTypeRegistry(object): assert isinstance(cpp_class, CppClass) self.ordered_classes.append(cpp_class) - def get_type_traits(self, type_info): - #assert isinstance(type_info, cpptypes.type_t) +# def get_type_traits(self, type_info): +# #assert isinstance(type_info, cpptypes.type_t) - debug = False #('int64_t' in type_info.decl_string) - if debug: - print >> sys.stderr, "***** type traits for %r" % (type_info.decl_string, ) +# debug = False #('int64_t' in type_info.decl_string) +# if debug: +# print >> sys.stderr, "***** type traits for %r" % (type_info.decl_string, ) - is_const = False - is_reference = False - is_pointer = 0 +# is_const = False +# is_reference = False +# is_pointer = 0 +# pointer_or_ref_count = 0 +# inner_const = False +# while 1: +# prev_type_info = type_info +# if type_traits.is_pointer(type_info): +# is_pointer += 1 +# type_info = remove_pointer(type_info) +# pointer_or_ref_count += 1 +# elif type_traits.is_const(type_info): +# type_info = remove_const(type_info) +# if pointer_or_ref_count == 0: +# is_const = True +# elif pointer_or_ref_count == 1: +# inner_const = True +# else: +# warnings.warn("multiple consts not handled") +# elif type_traits.is_reference(type_info): +# warnings.warn("multiple &'s not handled") +# is_reference = True +# type_info = remove_reference(type_info) +# pointer_or_ref_count += 1 +# else: +# break +# if type_info is prev_type_info: +# break - while 1: - prev_type_info = type_info - if type_traits.is_pointer(type_info): - is_pointer += 1 - type_info = remove_pointer(type_info) - elif type_traits.is_const(type_info): - warnings.warn("multiple consts not handled") - is_const = True - type_info = remove_const(type_info) - elif type_traits.is_reference(type_info): - warnings.warn("multiple &'s not handled") - is_reference = True - type_info = remove_reference(type_info) - else: - break - if type_info is prev_type_info: - break +# type_name = normalize_name(type_info.partial_decl_string) +# try: +# cpp_type = self.root_module[type_name] +# except KeyError: +# cpp_type = type_name - type_name = normalize_name(type_info.partial_decl_string) - try: - cpp_type = self.root_module[type_name] - except KeyError: - cpp_type = type_name +# if not isinstance(cpp_type, CppClass): +# cpp_type = type_name - if not isinstance(cpp_type, CppClass): - cpp_type = type_name - - if debug: - print >> sys.stderr, "*** > return ", repr((cpp_type, is_const, is_pointer, is_reference)) - return (cpp_type, is_const, is_pointer, is_reference) +# if debug: +# print >> sys.stderr, "*** > return ", repr((cpp_type, is_const, is_pointer, is_reference)) +# return (cpp_type, is_const, inner_const, is_pointer, is_reference) def _fixed_std_type_name(self, type_name): type_name = utils.ascii(type_name) @@ -243,10 +251,6 @@ class GccXmlTypeRegistry(object): return decl def lookup_return(self, type_info, annotations={}): - #assert isinstance(type_info, cpptypes.type_t) - cpp_type, is_const, is_pointer, is_reference = \ - self.get_type_traits(type_info) - kwargs = {} for name, value in annotations.iteritems(): if name == 'caller_owns_return': @@ -256,39 +260,11 @@ class GccXmlTypeRegistry(object): else: warnings.warn("invalid annotation name %r" % name, AnnotationsWarning) - if is_const: - kwargs['is_const'] = True + cpp_type = normalize_name(type_info.partial_decl_string) + return (cpp_type,), kwargs - if isinstance(cpp_type, CppClass): - cpp_type = cpp_type.full_name - else: - if isinstance(type_traits.remove_declarated(type_info), enumeration_t): - cpp_type = normalize_name(cpp_type) - else: - cpp_type = self._fixed_std_type_name(cpp_type) - - cpp_type = utils.ascii(cpp_type) - - if not is_pointer and not is_reference: - return (cpp_type,), kwargs - - ## pointer to class - if is_pointer and not is_reference: - if is_const and 'caller_owns_return' not in kwargs: - ## a pointer to const object "usually" means caller_owns_return=False - ## some guessing going on here, though.. - kwargs['caller_owns_return'] = False - return (cpp_type + ' *'*is_pointer,), kwargs - - ## reference of class - if not is_pointer and is_reference: - return (cpp_type + ' *'*is_pointer + '&',), kwargs - - assert 0, "this line should not be reached" def lookup_parameter(self, type_info, param_name, annotations={}, default_value=None): - assert isinstance(type_info, cpptypes.type_t) - kwargs = {} for name, value in annotations.iteritems(): if name == 'transfer_ownership': @@ -313,39 +289,11 @@ class GccXmlTypeRegistry(object): else: warnings.warn("invalid annotation name %r" % name, AnnotationsWarning) - cpp_type, is_const, is_pointer, is_reference = \ - self.get_type_traits(type_info) - - if is_const: - kwargs['is_const'] = True if default_value: kwargs['default_value'] = utils.ascii(default_value) - if isinstance(cpp_type, CppClass): - cpp_type = cpp_type.full_name - else: - if isinstance(type_traits.remove_declarated(type_info), enumeration_t): - cpp_type = normalize_name(cpp_type) - else: - cpp_type = self._fixed_std_type_name(cpp_type) - - cpp_type = utils.ascii(cpp_type) - param_name = utils.ascii(param_name) - - if not is_pointer and not is_reference: - return (cpp_type, param_name), kwargs - - ## pointer to class - if is_pointer and not is_reference: - if is_const: - ## a pointer to const object usually means transfer_ownership=False - kwargs.setdefault('transfer_ownership', False) - return (cpp_type + ' *'*is_pointer, param_name), kwargs - - ## reference to class - if not is_pointer and is_reference: - return (cpp_type + ' *'*is_pointer + '&', param_name), kwargs - assert 0, "this line should not be reached" + cpp_type = normalize_name(type_info.partial_decl_string) + return (cpp_type, param_name), kwargs class AnnotationsScanner(object): @@ -1223,11 +1171,11 @@ pybindgen.settings.error_handler = ErrorHandler() ## handle "typedef int Something;" if isinstance(alias.type, cpptypes.int_t): - param_cls, dummy_transf = typehandlers.base.param_type_matcher.lookup('int') + param_cls, dummy_transf, dummy_traits = typehandlers.base.param_type_matcher.lookup('int') for ctype in param_cls.CTYPES: #print >> sys.stderr, "%s -> int" % ctype.replace('int', alias.name) typehandlers.base.param_type_matcher.register(ctype.replace('int', alias.name), param_cls) - return_cls, dummy_transf = typehandlers.base.return_type_matcher.lookup('int') + return_cls, dummy_transf, dummy_traits = typehandlers.base.return_type_matcher.lookup('int') for ctype in return_cls.CTYPES: #print >> sys.stderr, "%s -> int" % ctype.replace('int', alias.name) typehandlers.base.return_type_matcher.register(ctype.replace('int', alias.name), return_cls) @@ -1456,10 +1404,9 @@ pybindgen.settings.error_handler = ErrorHandler() have_trivial_constructor = True elif len(member.arguments) == 1: - (cpp_type, dummy_is_const, dummy_is_pointer, - is_reference) = \ - self.type_registry.get_type_traits(member.arguments[0].type) - if cpp_type is class_wrapper and is_reference: + traits = ctypeparser.TypeTraits(normalize_name(member.arguments[0].type.partial_decl_string)) + if traits.type_is_reference and \ + self.type_registry.root_module.get(str(traits.target), None) is class_wrapper: have_copy_constructor = True methods_to_ignore = [] diff --git a/pybindgen/typehandlers/base.py b/pybindgen/typehandlers/base.py index 4d34ac8..5f48d3c 100644 --- a/pybindgen/typehandlers/base.py +++ b/pybindgen/typehandlers/base.py @@ -8,8 +8,9 @@ and base interfaces for wrapper generators. import codesink import warnings -from ctypeparser import normalize_type_string - +import ctypeparser +import logging +logger = logging.getLogger("pybindgen.typehandlers") try: @@ -763,7 +764,7 @@ class ForwardWrapperBase(object): if (not no_c_retval and return_value is not None and return_value.ctype != 'void' and not return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR): - self.declarations.declare_variable(return_value.ctype, 'retval') + self.declarations.declare_variable(return_value.ctype_no_const, 'retval') for param in self.parameters: self.declarations.reserve_variable(param.name) @@ -784,7 +785,7 @@ class ForwardWrapperBase(object): if (not self.no_c_retval and self.return_value is not None and self.return_value.ctype != 'void' and not self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR): - self.declarations.declare_variable(self.return_value.ctype, 'retval') + self.declarations.declare_variable(self.return_value.ctype_no_const, 'retval') def set_parse_error_return(self, parse_error_return): self.before_parse.error_return = parse_error_return @@ -1022,9 +1023,56 @@ class NullTypeTransformation(object): "identity transformation" return value +class TypeHandler(object): + SUPPORTS_TRANSFORMATIONS = False + + def __init__(self, ctype, is_const=False): + if ctype is None: + self.ctype = None + self.untransformed_ctype = None + self.type_traits = None + else: + if isinstance(ctype, ctypeparser.TypeTraits): + self.type_traits = ctype + if is_const: + warnings.warn("is_const is deprecated, put a 'const' in the C type instead.", DeprecationWarning) + if self.type_traits.type_is_pointer or self.type_traits.type_is_reference: + self.type_traits.make_target_const() + else: + self.type_traits.make_const() + elif isinstance(ctype, basestring): + if is_const: + warnings.warn("is_const is deprecated, put a 'const' in the C type instead.", DeprecationWarning) + self.type_traits = ctypeparser.TypeTraits('const %s' % ctype) + else: + self.type_traits = ctypeparser.TypeTraits(ctype) + else: + raise TypeError + self.ctype = str(self.type_traits.ctype) + self.untransformed_ctype = self.ctype + self.transformation = NullTypeTransformation() + + def _get_ctype_no_const(self): + return str(self.type_traits.ctype_no_const) + ctype_no_const = property(_get_ctype_no_const) + + def set_tranformation(self, transformation, untransformed_ctype): + warnings.warn("Typo: set_tranformation -> set_transformation", DeprecationWarning, stacklevel=2) + return self.set_transformation(transformation, untransformed_ctype) + + def set_transformation(self, transformation, untransformed_ctype): + "Set the type transformation to use in this type handler" + + assert isinstance(transformation, TypeTransformation) + assert untransformed_ctype != self.ctype + assert isinstance(self.transformation, NullTypeTransformation) + assert self.SUPPORTS_TRANSFORMATIONS + + self.transformation = transformation + self.untransformed_ctype = untransformed_ctype -class ReturnValue(object): +class ReturnValue(TypeHandler): '''Abstract base class for all classes dedicated to handle specific return value types''' @@ -1058,10 +1106,13 @@ class ReturnValue(object): """ if cls is ReturnValue: ctype = args[0] - type_handler_class, transformation = \ + type_handler_class, transformation, type_traits = \ return_type_matcher.lookup(ctype) assert type_handler_class is not None if transformation is None: + args = list(args) + args[0] = type_traits + args = tuple(args) try: return type_handler_class(*args, **kwargs) except TypeError, ex: @@ -1084,26 +1135,8 @@ class ReturnValue(object): ''' if type(self) is ReturnValue: raise TypeError('ReturnValue is an abstract class; use ReturnValue.new(...)') - #assert 'const' not in ctype, "FIXME: remove this assert" - if is_const: - ctype = 'const ' + ctype - self.ctype = ctype - self.untransformed_ctype = ctype - self.transformation = NullTypeTransformation() + super(ReturnValue, self).__init__(ctype, is_const) self.value = 'retval' - self.is_const = is_const - - def set_tranformation(self, transformation, untransformed_ctype): - "Set the type transformation to use in this type handler" - - assert isinstance(transformation, TypeTransformation) - assert untransformed_ctype != self.ctype - assert isinstance(self.transformation, NullTypeTransformation) - assert self.SUPPORTS_TRANSFORMATIONS - - self.transformation = transformation - self.untransformed_ctype = untransformed_ctype - def get_c_error_return(self): '''Return a "return " code string, for use in case of error''' @@ -1135,7 +1168,7 @@ class PointerReturnValue(ReturnValue): PointerReturnValue.CTYPES = NotImplemented -class Parameter(object): +class Parameter(TypeHandler): '''Abstract base class for all classes dedicated to handle specific parameter types''' ## bit mask values @@ -1184,10 +1217,13 @@ class Parameter(object): if cls is Parameter: # support calling Parameter("typename", ...) ctype = args[0] - type_handler_class, transformation = \ + type_handler_class, transformation, type_traits = \ param_type_matcher.lookup(ctype) assert type_handler_class is not None if transformation is None: + args = list(args) + args[0] = type_traits + args = tuple(args) try: return type_handler_class(*args, **kwargs) except TypeError, ex: @@ -1214,34 +1250,16 @@ class Parameter(object): ''' if type(self) is Parameter: raise TypeError('Parameter is an abstract class; use Parameter.new(...)') - #assert 'const' not in ctype, "FIXME: remove this assert" - self.ctype_no_const = ctype - if is_const: - ctype = 'const ' + ctype - self.ctype = ctype - self.untransformed_ctype = ctype + super(Parameter, self).__init__(ctype, is_const) self.name = name assert direction in self.DIRECTIONS, \ "Error: requested direction %s for type handler %r (ctype=%r), but it only supports directions %r"\ % (self._direction_value_to_name(direction), type(self), self.ctype, [self._direction_value_to_name(d) for d in self.DIRECTIONS]) self.direction = direction - self.is_const = is_const - self.transformation = NullTypeTransformation() self.value = name self.default_value = default_value - def set_tranformation(self, transformation, untransformed_ctype): - "Set the type transformation to use in this type handler" - - assert isinstance(transformation, TypeTransformation) - assert untransformed_ctype != self.ctype - assert isinstance(self.transformation, NullTypeTransformation) - assert self.SUPPORTS_TRANSFORMATIONS - - self.transformation = transformation - self.untransformed_ctype = untransformed_ctype - def convert_c_to_python(self, wrapper): '''Write some code before calling the Python method.''' #assert isinstance(wrapper, ReverseWrapperBase) @@ -1289,7 +1307,7 @@ class TypeMatcher(object): @param name: C type name @param type_handler: class to handle this C type """ - name = normalize_type_string(name) + name = ctypeparser.normalize_type_string(name) if name in self._types: raise ValueError("return type %s already registered" % (name,)) self._types[name] = type_handler @@ -1297,30 +1315,43 @@ class TypeMatcher(object): def lookup(self, name): """ - lookup(name) -> type_handler, type_transformation + lookup(name) -> type_handler, type_transformation, type_traits Returns a handler with the given ctype name, or raises KeyError. Supports type transformations. @param name: C type name, possibly transformed (e.g. MySmartPointer looks up Foo*) """ - name = normalize_type_string(name) + logger.debug("TypeMatcher.lookup(%r)", name) + given_type_traits = ctypeparser.TypeTraits(name) + noconst_name = str(given_type_traits.ctype_no_modifiers) + tried_names = [noconst_name] try: - return self._types[name], None + rv = self._types[noconst_name], None, given_type_traits except KeyError: + logger.debug("try to lookup type handler for %r => failure", name) ## Now try all the type transformations for transf in self._transformations: untransformed_name = transf.get_untransformed_name(name) if untransformed_name is None: continue + untransformed_type_traits = ctypeparser.TypeTraits(untransformed_name) + untransformed_name = str(untransformed_type_traits.ctype_no_modifiers) try: - return self._types[untransformed_name], transf + rv = self._types[untransformed_name], transf, untransformed_type_traits except KeyError: + logger.debug("try to lookup type handler for %r => failure (%r)", untransformed_name) + tried_names.append(untransformed_name) continue + else: + logger.debug("try to lookup type handler for %r => success (%r)", untransformed_name, rv) + return rv else: - raise TypeLookupError(name) + raise TypeLookupError(tried_names) + else: + logger.debug("try to lookup type handler for %r => success (%r)", name, rv) + return rv - def items(self): "Returns an iterator over all registered items" return self._types.iteritems() diff --git a/pybindgen/typehandlers/ctypeparser/__init__.py b/pybindgen/typehandlers/ctypeparser/__init__.py index f2c5a5e..0346217 100644 --- a/pybindgen/typehandlers/ctypeparser/__init__.py +++ b/pybindgen/typehandlers/ctypeparser/__init__.py @@ -1,4 +1,5 @@ import tokenizer +import copy MODIFIERS = ['const', 'volatile'] # XXX: are there others? @@ -14,8 +15,11 @@ class CType(object): L{CType}s (arguments of templated types, function pointer name and parameters). """ __slots__ = 'tokens' - def __init__(self): - self.tokens = [] + def __init__(self, tokens=None): + if tokens is None: + self.tokens = [] + else: + self.tokens = tokens def reorder_modifiers(self): """ @@ -81,6 +85,21 @@ class CType(object): break return removed + def remove_outer_modifier(self, modifier): + """ + Remove the given modifier from the type, but only from the + outer part and only until a first * or & is found, from right + to left. + """ + for token_i in range(len(self.tokens)-1, -1, -1): + token = self.tokens[token_i] + if isinstance(token, CType): + continue + if token.name == modifier: + del self.tokens[token_i] + return True + return False + def __str__(self): l = [] first = True @@ -170,3 +189,175 @@ def normalize_type_string(type_string): ctype = parse_type(type_string) return str(ctype) + +class TypeTraits(object): + """ + Parse a C type and gather some interesting properties. + + @ivar ctype: the original unmodified type (a L{CType} object, apply str() to obtain a type string). + + @ivar ctype_no_modifiers: the type with all modifiers (const, volatile, ...) removed (except from template arguments) + + @ivar type_is_const: True if the outermost type is const + + @ivar type_is_reference: True if the outermost type is a reference + + @ivar type_is_pointer: True if the outermost type is a pointer + + @ivar target_is_const: True if the type is pointer or reference and the target is const + + @ivar target: if this is a pointer or reference type, a L{CType} + representing the target, without modifiers. If not pointer or + reference, it is None. + + >>> t = TypeTraits("int") + >>> print repr(str(t.ctype)) + 'int' + >>> print repr(str(t.ctype_no_modifiers)) + 'int' + >>> t.type_is_const + False + >>> t.type_is_pointer + False + >>> t.type_is_reference + False + >>> t.target is None + True + + >>> t = TypeTraits("const int * const") + >>> print repr(str(t.ctype)) + 'int const * const' + >>> print repr(str(t.ctype_no_modifiers)) + 'int *' + >>> print repr(str(t.ctype_no_const)) + 'int const *' + >>> t.type_is_const + True + >>> t.type_is_pointer + True + >>> t.type_is_reference + False + >>> t.target is None + False + >>> print repr(str(t.target)) + 'int' + >>> t.target_is_const + True + + >>> t = TypeTraits("int * const") + >>> print repr(str(t.ctype)) + 'int * const' + >>> print repr(str(t.ctype_no_modifiers)) + 'int *' + >>> print repr(str(t.ctype_no_const)) + 'int *' + >>> t.type_is_const + True + >>> t.type_is_pointer + True + >>> t.type_is_reference + False + >>> t.target is None + False + >>> print repr(str(t.target)) + 'int' + >>> t.target_is_const + False + + >>> t = TypeTraits("const char *") + >>> print repr(str(t.ctype)) + 'char const *' + >>> print repr(str(t.ctype_no_modifiers)) + 'char *' + >>> print repr(str(t.ctype_no_const)) + 'char const *' + >>> t.type_is_const + False + >>> t.type_is_pointer + True + >>> t.type_is_reference + False + >>> t.target is None + False + >>> print repr(str(t.target)) + 'char' + >>> t.target_is_const + True + + >>> t = TypeTraits("char *") + >>> print repr(str(t.ctype)) + 'char *' + >>> t.make_const() + >>> print repr(str(t.ctype)) + 'char * const' + >>> t.make_target_const() + >>> print repr(str(t.ctype)) + 'char const * const' + + """ + + def __init__(self, ctype): + self.ctype = parse_type(ctype) + self.ctype_no_modifiers = copy.deepcopy(self.ctype) + self.ctype_no_modifiers.remove_modifiers() + self.ctype_no_const = copy.deepcopy(self.ctype) + tokens = copy.copy(self.ctype.tokens) + tokens.reverse() + ptr_ref_level = 0 + self.type_is_const = False + self.type_is_reference = False + self.type_is_pointer = False + self.target_is_const = False + self.target = None + target_pos = None + for pos, token in enumerate(tokens): + if isinstance(token, CType): + continue + if token.name == 'const': + if ptr_ref_level == 0: + self.type_is_const = True + const_removed = self.ctype_no_const.remove_outer_modifier('const') + assert const_removed + elif ptr_ref_level == 1: + self.target_is_const = True + elif token.name == '*': + if ptr_ref_level == 0: + self.type_is_pointer = True + target_pos = pos + 1 + ptr_ref_level += 1 + elif token.name == '&': + if ptr_ref_level == 0: + self.type_is_reference = True + target_pos = pos + 1 + ptr_ref_level += 1 + if target_pos is not None: + target_tokens = tokens[target_pos:] + target_tokens.reverse() + self.target = CType(target_tokens) + self.target.remove_modifiers() + + def make_const(self): + """ + Add a const modifier to the type. Has no effect if the type is already const. + """ + if self.type_is_const: + return + self.type_is_const = True + self.ctype.tokens.append(tokenizer.Token(tokenizer.NAME, "const", None, None)) + + def make_target_const(self): + """ + Add a const modifier to the type target. Has no effect if the type target is already const. + """ + assert self.type_is_pointer or self.type_is_reference + if self.target_is_const: + return + self.target_is_const = True + for tokens in self.ctype.tokens, self.ctype_no_const.tokens: + for token_i in range(len(tokens)-1, -1, -1): + token = tokens[token_i] + if isinstance(token, CType): + continue + elif token.name in ['*', '&']: + tokens.insert(token_i, tokenizer.Token(tokenizer.NAME, "const", None, None)) + break diff --git a/pybindgen/typehandlers/inttype.py b/pybindgen/typehandlers/inttype.py index c11e445..79ede51 100644 --- a/pybindgen/typehandlers/inttype.py +++ b/pybindgen/typehandlers/inttype.py @@ -64,7 +64,7 @@ class UnsignedIntPtrParam(PointerParameter): def convert_python_to_c(self, wrapper): #assert self.ctype == 'unsigned int*' if self.array_length is None: - name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) + name = wrapper.declarations.declare_variable(str(self.type_traits.target), self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: wrapper.parse_params.add_parameter('I', ['&'+name], self.name) @@ -73,7 +73,7 @@ class UnsignedIntPtrParam(PointerParameter): else: # complicated code path to deal with arrays... - name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name, array="[%i]" % self.array_length) + name = wrapper.declarations.declare_variable(str(self.type_traits.target), self.name, array="[%i]" % self.array_length) py_list = wrapper.declarations.declare_variable("PyObject*", "py_list") idx = wrapper.declarations.declare_variable("int", "idx") wrapper.call_params.append(name) @@ -163,7 +163,6 @@ class IntPtrParam(PointerParameter): wrapper.parse_params.add_parameter("i", [self.value], self.name) def convert_python_to_c(self, wrapper): - assert self.ctype.endswith('*') name = wrapper.declarations.declare_variable('int', self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: @@ -311,13 +310,13 @@ class UnsignedLongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['unsigned long long', 'uint64_t'] + def get_ctype_without_ref(self): + return str(self.type_traits.ctype_no_const) + def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('K', [self.value]) - def get_ctype_without_ref(self): - return self.ctype_no_const - def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) @@ -329,8 +328,8 @@ class UnsignedLongLongRefParam(UnsignedLongLongParam): CTYPES = ['unsigned long long&', 'uint64_t&'] def get_ctype_without_ref(self): - assert self.ctype_no_const[-1] == '&' - return self.ctype_no_const[:-1] + assert self.type_traits.target is not None + return str(self.type_traits.target) class UnsignedLongLongReturn(ReturnValue): @@ -352,13 +351,13 @@ class LongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] CTYPES = ['long long', 'int64_t'] + def get_ctype_without_ref(self): + return str(self.type_traits.ctype_no_const) + def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) wrapper.build_params.add_parameter('L', [self.value]) - def get_ctype_without_ref(self): - return self.ctype_no_const - def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) @@ -371,8 +370,8 @@ class LongLongRefParam(LongLongParam): CTYPES = ['long long&', 'int64_t&'] def get_ctype_without_ref(self): - assert self.ctype_no_const[-1] == '&' - return self.ctype_no_const[:-1] + assert self.type_traits.target is not None + return str(self.type_traits.target) class LongLongReturn(ReturnValue): @@ -411,7 +410,6 @@ class Int8PtrParam(PointerParameter): wrapper.parse_params.add_parameter("b", [self.value], self.name) def convert_python_to_c(self, wrapper): - assert self.ctype.endswith('*') name = wrapper.declarations.declare_variable('int8_t', self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: @@ -441,7 +439,6 @@ class UInt8PtrParam(PointerParameter): wrapper.parse_params.add_parameter("B", [self.value], self.name) def convert_python_to_c(self, wrapper): - assert self.ctype.endswith('*') name = wrapper.declarations.declare_variable('uint8_t', self.name) wrapper.call_params.append('&'+name) if self.direction & self.DIRECTION_IN: diff --git a/pybindgen/typehandlers/pyobjecttype.py b/pybindgen/typehandlers/pyobjecttype.py index 6830020..dd2e81b 100644 --- a/pybindgen/typehandlers/pyobjecttype.py +++ b/pybindgen/typehandlers/pyobjecttype.py @@ -35,7 +35,7 @@ class PyObjectParam(Parameter): wrapper.parse_params.add_parameter('O', ['&'+name]) wrapper.call_params.append(name) if self.transfer_ownership: - wrapper.before_call.write_code("Py_INCREF(%s);" % name) + wrapper.before_call.write_code("Py_INCREF((PyObject*) %s);" % name) class PyObjectReturnValue(ReturnValue): @@ -57,7 +57,7 @@ class PyObjectReturnValue(ReturnValue): def convert_python_to_c(self, wrapper): wrapper.parse_params.add_parameter("O", ["&"+self.value], prepend=True) if self.caller_owns_return: - wrapper.after_call.write_code("Py_INCREF(%s);" % self.value) + wrapper.after_call.write_code("Py_INCREF((PyObject*) %s);" % self.value) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter( diff --git a/pybindgen/typehandlers/stringtype.py b/pybindgen/typehandlers/stringtype.py index 5e86ac1..08a444f 100644 --- a/pybindgen/typehandlers/stringtype.py +++ b/pybindgen/typehandlers/stringtype.py @@ -19,7 +19,7 @@ class CStringParam(PointerParameter): def convert_python_to_c(self, wrapper): assert isinstance(wrapper, ForwardWrapperBase) - name = wrapper.declarations.declare_variable(self.ctype, self.name) + name = wrapper.declarations.declare_variable(self.ctype_no_const, self.name) wrapper.parse_params.add_parameter('s', ['&'+name], self.value) wrapper.call_params.append(name) @@ -140,7 +140,7 @@ class CStringReturn(PointerReturnValue): return "return NULL;" def convert_python_to_c(self, wrapper): - name = wrapper.declarations.declare_variable(self.ctype, "retval_ptr") + name = wrapper.declarations.declare_variable(self.ctype_no_const, "retval_ptr") wrapper.parse_params.add_parameter("s", ['&'+name], self.value) def convert_c_to_python(self, wrapper): diff --git a/tests/foo.h b/tests/foo.h index 6c65bfb..74ad74c 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -58,7 +58,7 @@ public: Foo (std::string const &datum) : m_datum (datum), m_initialized (false) { Foo::instance_count++; } - std::string get_datum () const { return m_datum; } + const std::string get_datum () const { return m_datum; } std::string get_datum_deprecated () const DEPRECATED { return m_datum; } diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 55cc79c..c46ddcf 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -32,7 +32,7 @@ def my_module_gen(out_file): Foo.add_static_attribute('instance_count', ReturnValue.new('int')) Foo.add_constructor([Parameter.new('std::string', 'datum')]) Foo.add_constructor([]) - Foo.add_method('get_datum', ReturnValue.new('std::string'), []) + Foo.add_method('get_datum', ReturnValue.new('const std::string'), []) Foo.add_method('is_initialized', ReturnValue.new('bool'), [], is_const=True) Foo.add_output_stream_operator() @@ -88,14 +88,14 @@ int %s::custom_method_added_by_a_hook(int x) mod.add_function('print_something', ReturnValue.new('int'), - [Parameter.new('char*', 'message', is_const=True)], + [Parameter.new('const char*', 'message')], deprecated=True) mod.add_function('print_something_else', ReturnValue.new('int'), - [Parameter.new('char*', 'message2', is_const=True)]) + [Parameter.new('const char*', 'message2')]) ## test overloaded functions mod.add_function('get_int_from_string', ReturnValue.new('int'), - [Parameter.new('char*', 'from_string', is_const=True), + [Parameter.new('const char*', 'from_string'), Parameter.new('int', 'multiplier', default_value='1')], custom_name="get_int") mod.add_function('get_int_from_float', ReturnValue.new('int'), [Parameter.new('double', 'from_float'), @@ -136,13 +136,13 @@ int %s::custom_method_added_by_a_hook(int x) SomeObject.add_method('get_prefix_with_foo_ref', ReturnValue.new('std::string'), - [Parameter.new('Foo&', 'foo', is_const=True, + [Parameter.new('const Foo&', 'foo', direction=Parameter.DIRECTION_INOUT)], is_virtual=True, is_const=True) SomeObject.add_method('get_prefix_with_foo_ptr', ReturnValue.new('std::string'), - [Parameter.new('Foo*', 'foo', transfer_ownership=False, is_const=True)], + [Parameter.new('const Foo*', 'foo', transfer_ownership=False)], is_virtual=True, is_const=True) ## overloaded virtual methods @@ -166,7 +166,7 @@ int %s::custom_method_added_by_a_hook(int x) ## add a function that appears as a method of an object SomeObject.add_function_as_method('some_object_get_something_prefixed', ReturnValue.new('std::string'), - [Parameter.new('SomeObject*', 'obj', transfer_ownership=False, is_const=True), + [Parameter.new('const SomeObject*', 'obj', transfer_ownership=False), Parameter.new('std::string', 'something')], custom_name='get_something_prefixed') @@ -180,7 +180,7 @@ int %s::custom_method_added_by_a_hook(int x) ## add a function that appears as a method of an object SomeObject.add_function_as_method('some_object_ref_get_something_prefixed', ReturnValue.new('std::string'), - [Parameter.new('SomeObject&', 'obj', is_const=True), + [Parameter.new('const SomeObject&', 'obj'), Parameter.new('std::string', 'something')], custom_name='ref_get_something_prefixed') @@ -242,7 +242,7 @@ int %s::custom_method_added_by_a_hook(int x) ## test overloaded methods SomeObject.add_method('get_int', ReturnValue.new('int'), - [Parameter.new('char*', 'from_string', is_const=True)], + [Parameter.new('const char*', 'from_string')], custom_name="get_int") SomeObject.add_method('get_int', ReturnValue.new('int'), [Parameter.new('double', 'from_float')], @@ -269,7 +269,7 @@ int %s::custom_method_added_by_a_hook(int x) xpto_SomeClass.add_constructor([]) xpto.add_typedef(Foo, 'FooXpto') - xpto.add_function('get_foo_datum', 'std::string', [Parameter.new('xpto::FooXpto&', 'foo', is_const=True)]) + xpto.add_function('get_foo_datum', 'std::string', [Parameter.new('const xpto::FooXpto&', 'foo')]) ## ---- some implicity conversion APIs @@ -392,7 +392,7 @@ int %s::custom_method_added_by_a_hook(int x) # containers... - SimpleStructList = mod.add_container('SimpleStructList', ReturnValue.new('simple_struct_t'), 'list') + mod.add_container('SimpleStructList', ReturnValue.new('simple_struct_t'), 'list') mod.add_function('get_simple_list', ReturnValue.new('SimpleStructList'), []) mod.add_function('set_simple_list', 'int', [Parameter.new('SimpleStructList', 'list')]) diff --git a/tests/foomodulegen_common.py b/tests/foomodulegen_common.py index 124e93a..aec71d6 100644 --- a/tests/foomodulegen_common.py +++ b/tests/foomodulegen_common.py @@ -32,7 +32,7 @@ class PointerHolderTransformation(typehandlers.TypeTransformation): else: raise AssertionError handler = type_handler(*args, **kwargs) - handler.set_tranformation(self, self.get_untransformed_name(args[0])) + handler.set_transformation(self, self.get_untransformed_name(args[0])) return handler def untransform(self, type_handler, declarations, code_block, expression): diff --git a/tests/test-generation.py b/tests/test-generation.py index c55125d..dd45e5b 100755 --- a/tests/test-generation.py +++ b/tests/test-generation.py @@ -162,7 +162,9 @@ public: continue # const and output parameter makes no sense if is_const: - param_type_with_const = "const " + param_type + if '&' in param_type: # const references not allowed + continue + param_type_with_const = "const %s" % (param_type,) else: param_type_with_const = param_type @@ -171,7 +173,7 @@ public: for transfer_ownership in True, False: name = param_name + (transfer_ownership and '_transfer' or '_notransfer') try: - param = param_handler(param_type, name, transfer_ownership=transfer_ownership, is_const=is_const) + param = param_handler(param_type, name, transfer_ownership=transfer_ownership) except TypeError: print >> sys.stderr, "ERROR -----> param_handler(param_type=%r, "\ "name=%r, transfer_ownership=%r, is_const=%r)"\ @@ -183,7 +185,7 @@ public: print module.add_function(function_name, ReturnValue.new('void'), [param]) else: - param = param_handler(param_type, param_name, direction, is_const=is_const) + param = param_handler(param_type, param_name, direction) wrapper_number += 1 function_name = 'foo_function_%i' % (wrapper_number,) ## declare a fake prototype