Getting ready to support numeric operators...

This commit is contained in:
Gustavo J. A. M. Carneiro committed 2008-10-05 18:51:17 +01:00
1 parent dad9e231b8
commit b0336e7f06
5 files changed
+265 -69

No files matched your search

+38 -9
View File
@@ -16,7 +16,7 @@ from cppattribute import CppInstanceAttributeGetter, CppInstanceAttributeSetter,
CppStaticAttributeGetter, CppStaticAttributeSetter, \
PyGetSetDef, PyMetaclass
from pytypeobject import PyTypeObject
from pytypeobject import PyTypeObject, PyNumberMethods
import settings
import utils
@@ -449,7 +449,9 @@ class CppClass(object):
self.has_output_stream_operator = False
self._have_pure_virtual_methods = None
self._wrapper_registry = None
self.binary_operators = set()
self.binary_comparison_operators = set()
self.binary_numeric_operators = dict()
self.pynumbermethods = None
## list of CppClasses from which a value of this class can be
## implicitly generated; corresponds to a
@@ -575,14 +577,12 @@ class CppClass(object):
def __repr__(self):
return "<pybindgen.CppClass %r>" % self.full_name
def add_binary_operator(self, operator):
def add_binary_comparison_operator(self, operator):
"""
Add support for a C++ binary operator, such as == or <.
Add support for a C++ binary comparison operator, such as == or <.
The binary operator is assumed to operate with both operands
of the type of the class, either by reference or by value. At
the moment only a limited set of operators are supported by
PyBindGen.
of the type of the class, either by reference or by value.
@param operator: string indicating the name of the operator to
support, e.g. '=='
@@ -591,7 +591,36 @@ class CppClass(object):
raise TypeError("expected operator name as string")
if operator not in ['==', '!=', '<', '<=', '>', '>=']:
raise NotImplementedError("The operator %r is invalid or not yet supported by PyBindGen" % (operator,))
self.binary_operators.add(operator)
self.binary_comparison_operators.add(operator)
def add_binary_numeric_operator(self, operator, result_cppclass=None,
left_cppclass=None, right_cppclass=None):
"""
Add support for a C++ binary numeric operator, such as +, -, *, or /.
@param operator: string indicating the name of the operator to
support, e.g. '=='
@param result_cppclass: the CppClass object of the result type, assumed to be this class if omitted
@param left_cppclass: the CppClass object of the left operand type, assumed to be this class if omitted
@param right_cppclass: the CppClass object of the right operand type, assumed to be this class if omitted
"""
if not isinstance(operator, str):
raise TypeError("expected operator name as string")
if operator not in ['+', '-', '*', '/']:
raise NotImplementedError("The operator %r is invalid or not yet supported by PyBindGen" % (operator,))
try:
l = self.binary_numeric_operators[operator]
except KeyError:
l = []
self.binary_numeric_operators[operator] = l
if result_cppclass is None:
result_cppclass = self
if left_cppclass is None:
left_cppclass = self
if right_cppclass is None:
right_cppclass = self
l.append((result_cppclass, left_cppclass, right_cppclass))
def add_class(self, *args, **kwargs):
"""
@@ -1787,7 +1816,7 @@ if (!PyObject_IsInstance((PyObject*) other, (PyObject*) &%s)) {
def wrap_operator(name, opid_code):
code_sink.writeln("case %s:" % opid_code)
code_sink.indent()
if name in self.binary_operators:
if name in self.binary_comparison_operators:
code_sink.writeln("if (*self->obj %(OP)s *other->obj) {\n"
" Py_INCREF(Py_True);\n"
" return Py_True;\n"
+67 -43
View File
@@ -1359,61 +1359,85 @@ pybindgen.settings.error_handler = ErrorHandler()
return False
def _is_ostream(self, cpp_type):
return (isinstance (cpp_type, cpptypes.reference_t)
return (isinstance(cpp_type, cpptypes.reference_t)
and not isinstance(cpp_type.base, cpptypes.const_t)
and str(cpp_type.base) == 'std::ostream')
def _scan_class_operators(self, cls, class_wrapper, pygen_sink):
def _handle_operator(symbol, return_type, argument_types):
#print >> sys.stderr, "<<<<<OP>>>>> %s: %s : %s --> %s" % (op.symbol, cls, [str(x) for x in argument_types], return_type)
if symbol == '<<' \
and self._is_ostream(return_type) \
and len(op.arguments) == 2 \
and self._is_ostream(argument_types[0]) \
and type_traits.is_convertible(cls, argument_types[1]):
#print >> sys.stderr, "<<<<<OUTPUT STREAM OP>>>>> %s: %s " % (op.symbol, cls)
class_wrapper.add_output_stream_operator()
pygen_sink.writeln("cls.add_output_stream_operator()")
if op.symbol in ['==', '!=', '<', '<=', '>', '>='] \
and len(argument_types) == 2 \
and type_traits.is_convertible(cls, argument_types[0]) \
and type_traits.is_convertible(cls, argument_types[1]):
#print >> sys.stderr, "<<<<<BINARY COMPARISON OP>>>>> %s: %s " % (op.symbol, cls)
class_wrapper.add_binary_comparison_operator(op.symbol)
pygen_sink.writeln("cls.add_binary_comparison_operator(%r)" % (op.symbol,))
if op.symbol in ['+', '-', '/', '*'] \
and len(argument_types) == 2 \
and (type_traits.is_convertible(cls, argument_types[0])
or type_traits.is_convertible(cls, argument_types[1])):
#print >> sys.stderr, "<<<<<potential NUMERIC OP>>>>> %s: %s : %s --> %s" \
# % (op.symbol, cls, [str(x) for x in argument_types], return_type)
def get_class_wrapper(pygccxml_type):
traits = ctypeparser.TypeTraits(normalize_name(pygccxml_type.partial_decl_string))
if traits.type_is_reference:
name = str(traits.target)
else:
name = str(traits.ctype)
class_wrapper = self.type_registry.root_module.get(name, None)
#print >> sys.stderr, "(lookup %r: %r)" % (name, class_wrapper)
return class_wrapper
ret = get_class_wrapper(return_type)
if ret is None:
#print >> sys.stderr, "<<<<<BINARY NUMERIC OP>>>>> retval class %s not registered" % (return_type,)
return
arg0 = get_class_wrapper(argument_types[0])
if arg0 is None:
#print >> sys.stderr, "<<<<<BINARY NUMERIC OP>>>>> arg 1 class %s not registered" % (argument_types[0],)
return
arg1 = get_class_wrapper(argument_types[1])
if arg1 is None:
#print >> sys.stderr, "<<<<<BINARY NUMERIC OP>>>>> arg 2 class %s not registered" % (argument_types[1],)
return
#print >> sys.stderr, "<<<<<BINARY NUMERIC OP>>>>> %s: %s: %s (%s, %s) " \
# % (op.symbol, cls, ret.full_name, arg0.full_name, arg1.full_name)
class_wrapper.add_binary_numeric_operator(op.symbol, ret, arg0, arg1)
pygen_sink.writeln("cls.add_binary_numeric_operator(%r, root_module[%r], root_module[%r], root_module[%r])"
% (op.symbol, ret.full_name,
arg0.full_name, arg1.full_name))
has_output_stream_operator = False
for op in self.module_namespace.free_operators(function=self.location_filter,
allow_empty=True,
allow_empty=True,
recursive=True):
if op.symbol == '<<' \
and self._is_ostream (op.return_type) \
and len (op.arguments) >= 2 \
and self._is_ostream (op.arguments[0].type) \
and type_traits.is_convertible (cls, op.arguments[1].type):
has_output_stream_operator = True
_handle_operator(op.symbol, op.return_type, [arg.type for arg in op.arguments])
for op in cls.member_operators(function=self.location_filter,
allow_empty=True,
recursive=True):
if op.symbol == '<<' \
and self._is_ostream (op.return_type) \
and len (op.arguments) >= 2 \
and self._is_ostream (op.arguments[0].type) \
and type_traits.is_convertible (cls, op.arguments[1].type):
has_output_stream_operator = True
if has_output_stream_operator:
class_wrapper.add_output_stream_operator()
pygen_sink.writeln("cls.add_output_stream_operator()")
arg_types = [arg.type for arg in op.arguments]
arg_types.insert(0, cls)
_handle_operator(op.symbol, op.return_type, arg_types)
if type_traits.has_public_binary_operator(cls, '<'):
print >> sys.stderr, "<<<<<OP>>>>> < ", cls
class_wrapper.add_binary_operator('<')
pygen_sink.writeln("cls.add_binary_operator('<')")
if type_traits.has_public_binary_operator(cls, '<='):
print >> sys.stderr, "<<<<<OP>>>>> <= ", cls
class_wrapper.add_binary_operator('<=')
pygen_sink.writeln("cls.add_binary_operator('<=')")
if type_traits.has_public_binary_operator(cls, '>='):
print >> sys.stderr, "<<<<<OP>>>>> >= ", cls
class_wrapper.add_binary_operator('>=')
pygen_sink.writeln("cls.add_binary_operator('>=')")
if type_traits.has_public_binary_operator(cls, '>'):
print >> sys.stderr, "<<<<<OP>>>>> > ", cls
class_wrapper.add_binary_operator('>')
pygen_sink.writeln("cls.add_binary_operator('>')")
if type_traits.has_public_binary_operator(cls, '=='):
print >> sys.stderr, "<<<<<OP>>>>> == ", cls
class_wrapper.add_binary_operator('==')
pygen_sink.writeln("cls.add_binary_operator('==')")
if type_traits.has_public_binary_operator(cls, '!='):
print >> sys.stderr, "<<<<<OP>>>>> != ", cls
class_wrapper.add_binary_operator('!=')
pygen_sink.writeln("cls.add_binary_operator('!=')")
def _scan_class_methods(self, cls, class_wrapper, pygen_sink):
have_trivial_constructor = False
+106
View File
@@ -101,3 +101,109 @@ class PyTypeObject(object):
slots.setdefault('tp_is_gc', 'NULL')
code_sink.writeln(self.TEMPLATE % slots)
class PyNumberMethods(object):
TEMPLATE = (
'PyNumberMethods %(variable)s = {\n'
'(binaryfunc) %(nb_add)s;\n'
'(binaryfunc) %(nb_subtract)s;\n'
'(binaryfunc) %(nb_multiply)s;\n'
'(binaryfunc) %(nb_divide)s;\n'
'(binaryfunc) %(nb_remainder)s;\n'
'(binaryfunc) %(nb_divmod)s;\n'
'(ternaryfunc) %(nb_power)s;\n'
'(unaryfunc) %(nb_negative)s;\n'
'(unaryfunc) %(nb_positive)s;\n'
'(unaryfunc) %(nb_absolute)s;\n'
'(inquiry) %(nb_nonzero)s;\n'
'(unaryfunc) %(nb_invert)s;\n'
'(binaryfunc) %(nb_lshift)s;\n'
'(binaryfunc) %(nb_rshift)s;\n'
'(binaryfunc) %(nb_and)s;\n'
'(binaryfunc) %(nb_xor)s;\n'
'(binaryfunc) %(nb_or)s;\n'
'(coercion) %(nb_coerce)s;\n'
'(unaryfunc) %(nb_int)s;\n'
'(unaryfunc) %(nb_long)s;\n'
'(unaryfunc) %(nb_float)s;\n'
'(unaryfunc) %(nb_oct)s;\n'
'(unaryfunc) %(nb_hex)s;\n'
'/* Added in release 2.0 */\n'
'(binaryfunc) %(nb_inplace_add)s;\n'
'(binaryfunc) %(nb_inplace_subtract)s;\n'
'(binaryfunc) %(nb_inplace_multiply)s;\n'
'(binaryfunc) %(nb_inplace_divide)s;\n'
'(binaryfunc) %(nb_inplace_remainder)s;\n'
'(ternaryfunc) %(nb_inplace_power)s;\n'
'(binaryfunc) %(nb_inplace_lshift)s;\n'
'(binaryfunc) %(nb_inplace_rshift)s;\n'
'(binaryfunc) %(nb_inplace_and)s;\n'
'(binaryfunc) %(nb_inplace_xor)s;\n'
'(binaryfunc) %(nb_inplace_or)s;\n'
'\n'
'/* Added in release 2.2 */\n'
'/* The following require the Py_TPFLAGS_HAVE_CLASS flag */\n'
'(binaryfunc) %(nb_floor_divide)s;\n'
'(binaryfunc) %(nb_true_divide)s;\n'
'(binaryfunc) %(nb_inplace_floor_divide);\n'
'(binaryfunc) %(nb_inplace_true_divide);\n'
'\n'
'/* Added in release 2.5 */\n'
'(unaryfunc) %(nb_index)s;\n'
'\n'
'};\n'
)
def __init__(self):
self.slots = {}
def generate(self, code_sink):
"""
Generates the structure. All slots are optional except 'variable'.
"""
slots = dict(self.slots)
slots.setdefault('nb_add', 'NULL')
slots.setdefault('nb_subtract', 'NULL')
slots.setdefault('nb_multiply', 'NULL')
slots.setdefault('nb_divide', 'NULL')
slots.setdefault('nb_remainder', 'NULL')
slots.setdefault('nb_divmod', 'NULL')
slots.setdefault('nb_power', 'NULL')
slots.setdefault('nb_negative', 'NULL')
slots.setdefault('nb_positive', 'NULL')
slots.setdefault('nb_absolute', 'NULL')
slots.setdefault('nb_nonzero', 'NULL')
slots.setdefault('nb_invert', 'NULL')
slots.setdefault('nb_lshift', 'NULL')
slots.setdefault('nb_rshift', 'NULL')
slots.setdefault('nb_and', 'NULL')
slots.setdefault('nb_xor', 'NULL')
slots.setdefault('nb_or', 'NULL')
slots.setdefault('nb_coerce', 'NULL')
slots.setdefault('nb_int', 'NULL')
slots.setdefault('nb_long', 'NULL')
slots.setdefault('nb_float', 'NULL')
slots.setdefault('nb_oct', 'NULL')
slots.setdefault('nb_hex', 'NULL')
slots.setdefault('nb_inplace_add', 'NULL')
slots.setdefault('nb_inplace_subtract', 'NULL')
slots.setdefault('nb_inplace_multiply', 'NULL')
slots.setdefault('nb_inplace_divide', 'NULL')
slots.setdefault('nb_inplace_remainder', 'NULL')
slots.setdefault('nb_inplace_power', 'NULL')
slots.setdefault('nb_inplace_lshift', 'NULL')
slots.setdefault('nb_inplace_rshift', 'NULL')
slots.setdefault('nb_inplace_and', 'NULL')
slots.setdefault('nb_inplace_xor', 'NULL')
slots.setdefault('nb_inplace_or', 'NULL')
slots.setdefault('nb_floor_divide', 'NULL')
slots.setdefault('nb_true_divide', 'NULL')
slots.setdefault('nb_inplace_floor_divide', 'NULL')
slots.setdefault('nb_inplace_true_divide', 'NULL')
slots.setdefault('nb_index', 'NULL')
code_sink.writeln(self.TEMPLATE % slots)
+44 -11
View File
@@ -776,23 +776,40 @@ std::map<std::string, int> get_map ();
std::set<uint32_t> get_set ();
// test comparison operators
// test binary operators
struct Tupl
{
int x, y;
inline Tupl operator * (Tupl const &b)
{
Tupl retval;
retval.x = x * b.x;
retval.y = y * b.y;
return retval;
}
inline Tupl operator / (Tupl const &b)
{
Tupl retval;
retval.x = x / b.x;
retval.y = y / b.y;
return retval;
}
inline bool operator == (Tupl const &b)
{
return (x == b.x && y == b.y);
}
inline bool operator != (Tupl const &b)
{
return (x != b.x || y != b.y);
}
};
inline bool operator == (Tupl const &a, Tupl const &b)
{
return (a.x == b.x && a.y == b.y);
}
inline bool operator != (Tupl const &a, Tupl const &b)
{
return (a.x != b.x || a.y != b.y);
}
inline bool operator < (Tupl const &a, Tupl const &b)
{
return (a.x < b.x || a.x == b.x && a.y < b.y);
@@ -813,6 +830,22 @@ inline bool operator >= (Tupl const &a, Tupl const &b)
return (a.x >= b.x || a.x == b.x && a.y >= b.y);
}
inline Tupl operator + (Tupl const &a, Tupl const &b)
{
Tupl retval;
retval.x = a.x + b.x;
retval.y = a.y + b.y;
return retval;
}
inline Tupl operator - (Tupl const &a, Tupl const &b)
{
Tupl retval;
retval.x = a.x - b.x;
retval.y = a.y - b.y;
return retval;
}
#endif /* !FOO_H_ */
+10 -6
View File
@@ -416,12 +416,16 @@ int %s::custom_method_added_by_a_hook(int x)
direction=Parameter.DIRECTION_OUT)])
Tupl = mod.add_class('Tupl')
Tupl.add_binary_operator('<')
Tupl.add_binary_operator('<=')
Tupl.add_binary_operator('>=')
Tupl.add_binary_operator('>')
Tupl.add_binary_operator('==')
Tupl.add_binary_operator('!=')
Tupl.add_binary_comparison_operator('<')
Tupl.add_binary_comparison_operator('<=')
Tupl.add_binary_comparison_operator('>=')
Tupl.add_binary_comparison_operator('>')
Tupl.add_binary_comparison_operator('==')
Tupl.add_binary_comparison_operator('!=')
Tupl.add_binary_numeric_operator('+')
Tupl.add_binary_numeric_operator('-')
Tupl.add_binary_numeric_operator('*')
Tupl.add_binary_numeric_operator('/')
Tupl.add_instance_attribute('x', 'int', is_const=False)
Tupl.add_instance_attribute('y', 'int', is_const=False)
Tupl.add_constructor([Parameter.new('Tupl const &', 'arg0')])