Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
kwargs['visibility'] = member.access_type
throw = self._get_calldef_exceptions(member)
if throw:
kwargs['throw'] = throw
kwargs_repr = _pygen_kwargs(kwargs)
if kwargs_repr:
kwargs_repr[0] = '\n' + 20*' '+ kwargs_repr[0]
pygen_sink.writeln("cls.add_constructor(%s)" %
", ".join([arglist_repr] + kwargs_repr))
arguments = []
for a, kw in argument_specs:
try:
arguments.append(Parameter.new(*a, **kw))
except (TypeLookupError, TypeConfigurationError) as ex:
warnings.warn_explicit("Parameter '%s %s' error (used in %s): %r"
% (arg.decl_type.partial_decl_string, arg.name, member, ex),
WrapperWarning, member.location.file_name, member.location.line)
ok = False
break
else:
ok = True
if not ok:
continue
constructor_wrapper = class_wrapper.add_constructor(arguments, **kwargs)
constructor_wrapper.castxml_definition = member
for hook in self._post_scan_hooks:
hook(self, member, constructor_wrapper)
if (len(arguments) == 1
return 0;
}
''' % subst_vars)
self.pytype.slots.setdefault("tp_init", container_tp_init_function_name)
## ----------------------------
## Type Handlers
## ----------------------------
def _get_dummy_container():
return Container('dummy', ReturnValue.new('void'), 'list') # Container instance
class ContainerParameterBase(Parameter):
"Base class for all C++ Class parameter handlers"
CTYPES = []
container_type = _get_dummy_container()
DIRECTIONS = [Parameter.DIRECTION_IN]
def __init__(self, ctype, name, direction=Parameter.DIRECTION_IN, is_const=False, default_value=None):
"""
ctype -- C type, normally 'MyClass*'
name -- parameter name
"""
if ctype == self.container_type.name:
ctype = self.container_type.full_name
super(ContainerParameterBase, self).__init__(
ctype, name, direction, is_const, default_value)
## name of the PyFoo * variable used in parameter parsing
if isinstance(arg, ReturnValue):
super(DummyReturnValue, self).__init__(arg.ctype)
else:
args, kwargs = utils.parse_retval_spec(arg)
super(DummyReturnValue, self).__init__(args[0])
def convert_c_to_python(self, wrapper):
raise TypeError("this is a DummyReturnValue")
def convert_python_to_c(self, wrapper):
raise TypeError("this is a DummyReturnValue")
def get_c_error_return(self):
return ''
class DummyParameter(Parameter):
CTYPES = []
DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_INOUT]
"""
A 'dummy' parameter object used for modelling methods that have
incomplete or incorrect parameters or return values.
"""
def __init__(self, arg):
"""
Accepts either a Parameter object or a tuple as sole
parameter. In case it's a tuple, it is assumed to be a retval
spec (\\*args, \\*\\*kwargs).
"""
if isinstance(arg, ReturnValue):
super(DummyParameter, self).__init__(arg.ctype)
else:
args, kwargs = utils.parse_param_spec(arg)
super(DummyParameter, self).__init__(args[0], args[1])
def eval_param(param_value, wrapper=None):
if isinstance(param_value, Parameter):
return param_value
else:
args, kwargs = parse_param_spec(param_value)
return call_with_error_handling(Parameter.new, args, kwargs, wrapper,
exceptions_to_handle=(TypeConfigurationError,
NotSupportedError,
TypeLookupError))
def __init__(self, ctype, name, direction=Parameter.DIRECTION_IN, is_const=False, default_value=None):
"""
ctype -- C type, normally 'MyClass*'
name -- parameter name
"""
if ctype == self.container_type.name:
ctype = self.container_type.full_name
super(ContainerParameterBase, self).__init__(
ctype, name, direction, is_const, default_value)
## name of the PyFoo * variable used in parameter parsing
self.py_name = None
def new(cls, *args, **kwargs):
"""
>>> import inttype
>>> isinstance(Parameter.new('int', 'name'), inttype.IntParam)
True
"""
if cls is Parameter:
# support calling Parameter("typename", ...)
ctype = args[0]
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, _ = sys.exc_info()
warnings.warn("Exception %r in type handler %s constructor" % (str(ex), type_handler_class))
raise
else:
def lookup_parameter(self, type_info, param_name, annotations={}, default_value=None):
kwargs = {}
for name, value in annotations.items():
if name == 'transfer_ownership':
kwargs['transfer_ownership'] = annotations_scanner.parse_boolean(value)
elif name == 'direction':
if value.lower() == 'in':
kwargs['direction'] = Parameter.DIRECTION_IN
elif value.lower() == 'out':
kwargs['direction'] = Parameter.DIRECTION_OUT
elif value.lower() == 'inout':
kwargs['direction'] = Parameter.DIRECTION_INOUT
else:
warnings.warn("invalid direction direction %r" % value, AnnotationsWarning)
elif name == 'custodian':
kwargs['custodian'] = int(value)
elif name == 'array_length':
kwargs['array_length'] = int(value)
elif name == 'default_value':
kwargs['default_value'] = value
elif name == 'null_ok':
kwargs['null_ok'] = annotations_scanner.parse_boolean(value)
else:
warnings.warn("invalid annotation name %r" % name, AnnotationsWarning)
def get_c_error_return(self):
return "return 0;"
def convert_python_to_c(self, wrapper):
tmp_var = wrapper.declarations.declare_variable("int", "tmp")
wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True)
wrapper.after_call.write_error_check('%s > 0xff' % tmp_var,
'PyErr_SetString(PyExc_ValueError, "Out of range");')
wrapper.after_call.write_code(
"%s = %s;" % (self.value, tmp_var))
def convert_c_to_python(self, wrapper):
wrapper.build_params.add_parameter("i", ['(int)' + self.value], prepend=True)
class Int8Param(Parameter):
DIRECTIONS = [Parameter.DIRECTION_IN]
CTYPES = ['int8_t', 'signed char', 'char signed']
def convert_c_to_python(self, wrapper):
assert isinstance(wrapper, ReverseWrapperBase)
wrapper.build_params.add_parameter('i', ["(int) "+self.value])
def convert_python_to_c(self, wrapper):
assert isinstance(wrapper, ForwardWrapperBase)
name = wrapper.declarations.declare_variable("int", self.name, self.default_value)
wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value))
wrapper.before_call.write_error_check('%s > 0x7f' % name,
'PyErr_SetString(PyExc_ValueError, "Out of range");')
wrapper.call_params.append(name)
CTYPES = []
container_type = _get_dummy_container()
def __init__(self, ctype):
super(ContainerReturnValueBase, self).__init__(ctype)
## name of the PyFoo * variable used in return value building
self.py_name = None
class ContainerParameter(ContainerParameterBase):
"Container handlers"
CTYPES = []
container_type = _get_dummy_container()
DIRECTIONS = [Parameter.DIRECTION_IN]
def convert_python_to_c(self, wrapper):
"parses python args to get C++ value"
assert isinstance(wrapper, ForwardWrapperBase)
assert isinstance(self.container_type, Container)
assert self.default_value is None, "default value not implemented for containers"
#self.py_name = wrapper.declarations.declare_variable('PyObject*', self.name)
container_tmp_var = wrapper.declarations.declare_variable(
self.container_type.full_name, self.name + '_value')
wrapper.parse_params.add_parameter('O&', [self.container_type.python_to_c_converter, '&'+container_tmp_var], self.name)
wrapper.call_params.append(container_tmp_var)
def convert_c_to_python(self, wrapper):
'''Write some code before calling the Python method.'''
if self.direction & Parameter.DIRECTION_IN:
wrapper.before_call.write_code("%s->obj = new %s(%s);" % (self.py_name, self.container_type.full_name, self.name))
else:
wrapper.before_call.write_code("%s->obj = new %s;" % (self.py_name, self.container_type.full_name))
wrapper.build_params.add_parameter("N", [self.py_name])
if self.direction & Parameter.DIRECTION_OUT:
wrapper.parse_params.add_parameter('O&', [self.container_type.python_to_c_converter, '&'+self.name], self.name)
class ContainerPtrParameter(ContainerParameterBase):
"Container handlers"
CTYPES = []
container_type = _get_dummy_container()
DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, Parameter.DIRECTION_INOUT]
def __init__(self, ctype, name, direction=Parameter.DIRECTION_IN, is_const=False, default_value=None, transfer_ownership=None):
super(ContainerPtrParameter, self).__init__(ctype, name, direction, is_const, default_value)
if self.direction == Parameter.DIRECTION_OUT:
if transfer_ownership is not None and not transfer_ownership:
raise TypeConfigurationError("with direction=out, transfer_ownership must be True or omitted (got %r)"
% transfer_ownership)
self.transfer_ownership = True
else:
if transfer_ownership is None:
raise TypeConfigurationError("transfer_ownership parameter was not given")
self.transfer_ownership = transfer_ownership
def convert_python_to_c(self, wrapper):
"parses python args to get C++ value"