From dad9e231b8c77b4b29153e9da22104a91118cd92 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sat, 4 Oct 2008 22:52:39 +0100 Subject: [PATCH] Add support for wrapping binary comparison operators --- pybindgen/cppclass.py | 64 ++++++++++++++++++++++++++++++++++----- pybindgen/gccxmlparser.py | 45 ++++++++++++++++++++++----- tests/foo.h | 39 ++++++++++++++++++++++++ tests/foomodulegen.py | 13 +++++++- tests/footest.py | 27 +++++++++++++++++ 5 files changed, 172 insertions(+), 16 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index f07703d..b73a0a1 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -21,6 +21,9 @@ from pytypeobject import PyTypeObject import settings import utils +if 'set' not in dir(__builtins__): + from sets import Set as set + class MemoryPolicy(object): """memory management policy for a C++ class or C/C++ struct""" @@ -446,6 +449,7 @@ class CppClass(object): self.has_output_stream_operator = False self._have_pure_virtual_methods = None self._wrapper_registry = None + self.binary_operators = set() ## list of CppClasses from which a value of this class can be ## implicitly generated; corresponds to a @@ -571,6 +575,23 @@ class CppClass(object): def __repr__(self): return "" % self.full_name + def add_binary_operator(self, operator): + """ + Add support for a C++ binary 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. + + @param operator: string indicating the name of the operator to + support, e.g. '==' + """ + 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,)) + self.binary_operators.add(operator) def add_class(self, *args, **kwargs): """ @@ -1750,17 +1771,46 @@ static void def _generate_tp_richcompare(self, code_sink): tp_richcompare_function_name = "_wrap_%s__tp_richcompare" % (self.pystruct,) - code_sink.writeln("static PyObject*\n%s (%s *self, PyObject *o2, int opid)" - % (tp_richcompare_function_name, self.pystruct)) + code_sink.writeln("static PyObject*\n%s (%s *self, %s *other, int opid)" + % (tp_richcompare_function_name, self.pystruct, self.pystruct)) code_sink.writeln("{") code_sink.indent() - ## TODO - code_sink.writeln('PyErr_SetString(PyExc_TypeError, "Comparison not defined or not yet implemented.");') - code_sink.writeln('return NULL;') + code_sink.writeln(""" +if (!PyObject_IsInstance((PyObject*) other, (PyObject*) &%s)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; +}""" % self.pytypestruct) - #code_sink.writeln("Py_INCREF(Py_NotImplemented);") - #code_sink.writeln("return Py_NotImplemented;") + code_sink.writeln("switch (opid)\n{") + + def wrap_operator(name, opid_code): + code_sink.writeln("case %s:" % opid_code) + code_sink.indent() + if name in self.binary_operators: + code_sink.writeln("if (*self->obj %(OP)s *other->obj) {\n" + " Py_INCREF(Py_True);\n" + " return Py_True;\n" + "} else {\n" + " Py_INCREF(Py_False);\n" + " return Py_False;\n" + "}" % dict(OP=name)) + else: + code_sink.writeln("Py_INCREF(Py_NotImplemented);\n" + "return Py_NotImplemented;") + code_sink.unindent() + + wrap_operator('<', 'Py_LT') + wrap_operator('<=', 'Py_LE') + wrap_operator('==', 'Py_EQ') + wrap_operator('!=', 'Py_NE') + wrap_operator('>=', 'Py_GE') + wrap_operator('>', 'Py_GT') + + code_sink.writeln("} /* closes switch (opid) */") + + code_sink.writeln("Py_INCREF(Py_NotImplemented);\n" + "return Py_NotImplemented;") code_sink.unindent() code_sink.writeln("}\n") diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index a1ed84b..2330663 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -1363,12 +1363,9 @@ pybindgen.settings.error_handler = ErrorHandler() and not isinstance(cpp_type.base, cpptypes.const_t) and str(cpp_type.base) == 'std::ostream') - def _scan_class_methods(self, cls, class_wrapper, pygen_sink): - have_trivial_constructor = False - have_copy_constructor = False + def _scan_class_operators(self, cls, class_wrapper, pygen_sink): + has_output_stream_operator = False - - for op in self.module_namespace.free_operators(function=self.location_filter, allow_empty=True, recursive=True): @@ -1388,10 +1385,45 @@ pybindgen.settings.error_handler = ErrorHandler() 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()") + + if type_traits.has_public_binary_operator(cls, '<'): + print >> sys.stderr, "<<<<>>>> < ", cls + class_wrapper.add_binary_operator('<') + pygen_sink.writeln("cls.add_binary_operator('<')") + if type_traits.has_public_binary_operator(cls, '<='): + print >> sys.stderr, "<<<<>>>> <= ", cls + class_wrapper.add_binary_operator('<=') + pygen_sink.writeln("cls.add_binary_operator('<=')") + if type_traits.has_public_binary_operator(cls, '>='): + print >> sys.stderr, "<<<<>>>> >= ", cls + class_wrapper.add_binary_operator('>=') + pygen_sink.writeln("cls.add_binary_operator('>=')") + if type_traits.has_public_binary_operator(cls, '>'): + print >> sys.stderr, "<<<<>>>> > ", cls + class_wrapper.add_binary_operator('>') + pygen_sink.writeln("cls.add_binary_operator('>')") + if type_traits.has_public_binary_operator(cls, '=='): + print >> sys.stderr, "<<<<>>>> == ", cls + class_wrapper.add_binary_operator('==') + pygen_sink.writeln("cls.add_binary_operator('==')") + if type_traits.has_public_binary_operator(cls, '!='): + print >> sys.stderr, "<<<<>>>> != ", 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 + have_copy_constructor = False if pygen_sink is None: pygen_sink = NullCodeSink() + self._scan_class_operators(cls, class_wrapper, pygen_sink) + for member in cls.get_members(): if isinstance(member, calldef.member_function_t): if member.access_type not in ['protected', 'private']: @@ -1697,9 +1729,6 @@ pybindgen.settings.error_handler = ErrorHandler() class_wrapper.add_copy_constructor() pygen_sink.writeln("cls.add_copy_constructor()") - if has_output_stream_operator: - class_wrapper.add_output_stream_operator() - pygen_sink.writeln("cls.add_output_stream_operator()") def scan_functions(self): diff --git a/tests/foo.h b/tests/foo.h index 36991ba..6abd435 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -776,4 +776,43 @@ std::map get_map (); std::set get_set (); +// test comparison operators + +struct Tupl +{ + int x, 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); +} + +inline bool operator <= (Tupl const &a, Tupl const &b) +{ + return (a.x <= b.x || 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); +} + +inline bool operator >= (Tupl const &a, Tupl const &b) +{ + return (a.x >= b.x || a.x == b.x && a.y >= b.y); +} + + + #endif /* !FOO_H_ */ diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index b090890..68e5aba 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -415,7 +415,18 @@ int %s::custom_method_added_by_a_hook(int x) TestContainer.add_method('get_vec', 'void', [Parameter.new('std::vector &', 'outVec', 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_instance_attribute('x', 'int', is_const=False) + Tupl.add_instance_attribute('y', 'int', is_const=False) + Tupl.add_constructor([Parameter.new('Tupl const &', 'arg0')]) + Tupl.add_constructor([]) + #### --- error handler --- class MyErrorHandler(pybindgen.settings.ErrorHandler): def __init__(self): diff --git a/tests/footest.py b/tests/footest.py index d8fba8f..3734621 100644 --- a/tests/footest.py +++ b/tests/footest.py @@ -994,6 +994,33 @@ class TestFoo(unittest.TestCase): t = foo.TestContainer() v = list(t.get_vec()) self.assertEqual(v, ["hello", "world"]) + + def test_richcompare(self): + t1 = foo.Tupl() + + t1.x = 1 + t1.y = 1 + + t2 = foo.Tupl() + t2.x = 1 + t2.y = 1 + + t3 = foo.Tupl() + t3.x = 1 + t3.y = 2 + + self.assert_(t1 == t2) + self.assert_(not (t1 != t2)) + self.assert_(t1 <= t2) + self.assert_(t1 >= t2) + self.assert_(t3 >= t2) + self.assert_(t3 > t2) + self.assert_(t2 <= t3) + self.assert_(t2 < t3) + self.assert_(t2 != t3) + self.assert_(not(t2 == t3)) + + if __name__ == '__main__': unittest.main()