Merge branch 'master' into directorargout_and_java_typemaps

This commit is contained in:
Andrey Starodubtsev 2016-10-13 14:14:59 +03:00
commit b9cdc3c5e1
83 changed files with 1602 additions and 946 deletions

View file

@ -389,6 +389,7 @@ CPP_TEST_CASES += \
string_constants \
struct_initialization_cpp \
struct_value \
swig_exception \
symbol_clash \
template_arg_replace \
template_arg_scope \
@ -519,6 +520,7 @@ CPP_TEST_CASES += \
valuewrapper_opaque \
varargs \
varargs_overload \
variable_replacement \
virtual_destructor \
virtual_poly \
virtual_vs_nonvirtual_base \

View file

@ -7,6 +7,7 @@ public class li_std_except_runme {
public static void Main() {
Test test = new Test();
try { test.throw_bad_cast(); throw new Exception("throw_bad_cast failed"); } catch (InvalidCastException) {}
try { test.throw_bad_exception(); throw new Exception("throw_bad_exception failed"); } catch (ApplicationException) {}
try { test.throw_domain_error(); throw new Exception("throw_domain_error failed"); } catch (ApplicationException) {}
try { test.throw_exception(); throw new Exception("throw_exception failed"); } catch (ApplicationException) {}

View file

@ -28,6 +28,21 @@ class DirectorMethodException: public Swig::DirectorException {};
%include "std_string.i"
#ifdef SWIGPHP
%feature("director:except") {
if ($error == FAILURE) {
throw Swig::DirectorMethodException();
}
}
%exception {
try { $action }
catch (Swig::DirectorException &) { SWIG_fail; }
}
#endif
#ifdef SWIGPYTHON
%feature("director:except") {

View file

@ -0,0 +1,30 @@
var swig_exception = require("swig_exception");
var c = new swig_exception.Circle(10);
var s = new swig_exception.Square(10);
if (swig_exception.Shape.nshapes != 2) {
throw "Shape.nshapes should be 2, actually " + swig_exception.Shape.nshapes;
}
// ----- Throw exception -----
try {
c.throwException();
throw "Exception wasn't thrown";
} catch (e) {
if (e.message != "OK") {
throw "Exception message should be \"OK\", actually \"" + e.message + "\"";
}
}
// ----- Delete everything -----
c = null;
s = null;
e = null;
/* FIXME: Garbage collection needs to happen before this check will work.
if (swig_exception.Shape.nshapes != 0) {
throw "Shape.nshapes should be 0, actually " + swig_exception.Shape.nshapes;
}
*/

View file

@ -24,6 +24,7 @@
int foo3() throw(E1) { return 0; }
int foo4() throw(E2) { return 0; }
// all the STL exceptions...
void throw_bad_cast() throw(std::bad_cast) { throw std::bad_cast(); }
void throw_bad_exception() throw(std::bad_exception) { throw std::bad_exception(); }
void throw_domain_error() throw(std::domain_error) { throw std::domain_error("oops"); }
void throw_exception() throw(std::exception) { throw std::exception(); }

View file

@ -0,0 +1,20 @@
<?php
require "tests.php";
require "cpp_basic.php";
// New functions
check::functions(array(foo_func1,foo_func2,foo___str__,foosubsub___str__,bar_test,bar_testfoo,get_func1_ptr,get_func2_ptr,test_func_ptr,fl_window_show));
// New classes
check::classes(array(cpp_basic,Foo,FooSub,FooSubSub,Bar,Fl_Window));
// New vars
check::globals(array(foo_num,foo_func_ptr,bar_fptr,bar_fref,bar_fval,bar_cint,bar_global_fptr,bar_global_fref,bar_global_fval));
$f = new Foo(3);
$f->func_ptr = get_func1_ptr();
check::equal(test_func_ptr($f, 7), 2*7*3, "get_func1_ptr() didn't work");
$f->func_ptr = get_func2_ptr();
check::equal(test_func_ptr($f, 7), -7*3, "get_func2_ptr() didn't work");
check::done();
?>

View file

@ -0,0 +1,33 @@
<?php
require("swig_exception.php");
require("tests.php");
$c = new Circle(10);
$s = new Square(10);
if (Shape::nshapes() != 2) {
check::fail("Shape::nshapes() should be 2, actually ".Shape::nshapes());
}
# ----- Throw exception -----
try {
$c->throwException();
check::fail("Exception wasn't thrown");
} catch (Exception $e) {
if ($e->getMessage() != "OK") {
check::fail("Exception getMessage() should be \"OK\", actually \"".$e->getMessage()."\"");
}
}
# ----- Delete everything -----
$c = NULL;
$s = NULL;
$e = NULL;
if (Shape::nshapes() != 0) {
check::fail("Shape::nshapes() should be 0, actually ".Shape::nshapes());
}
?>

View file

@ -35,8 +35,9 @@ class check {
foreach($_original_functions[internal] as $func) unset($df[$func]);
// Now chop out any get/set accessors
foreach(array_keys($df) as $func)
if ((GETSET && ereg('_[gs]et$',$func)) || ereg('^new_', $func)
|| ereg('_(alter|get)_newobject$', $func))
if ((GETSET && preg_match('/_[gs]et$/', $func)) ||
preg_match('/^new_/', $func) ||
preg_match('/_(alter|get)_newobject$/', $func))
$extrags[]=$func;
else $extra[]=$func;
// $extra=array_keys($df);
@ -52,7 +53,8 @@ class check {
if (GETSET) {
$_extra=array();
foreach(check::get_extra_functions(false,1) as $global) {
if (ereg('^(.*)_[sg]et$',$global,$match)) $_extra[$match[1]]=1;
if (preg_match('/^(.*)_[sg]et$/', $global, $match))
$_extra[$match[1]] = 1;
}
$extra=array_keys($_extra);
} else {
@ -61,7 +63,8 @@ class check {
$df=array_flip(array_keys($GLOBALS));
foreach($_original_globals as $func) unset($df[$func]);
// MASK xxxx_LOADED__ variables
foreach(array_keys($df) as $func) if (ereg('_LOADED__$',$func)) unset($df[$func]);
foreach(array_keys($df) as $func)
if (preg_match('/_LOADED__$/', $func)) unset($df[$func]);
$extra=array_keys($df);
}
}
@ -185,7 +188,8 @@ class check {
}
function functionref($a,$type,$message) {
if (! eregi("^_[a-f0-9]+$type$",$a)) return check::fail($message);
if (! preg_match("/^_[a-f0-9]+$type$/i", $a))
return check::fail($message);
return TRUE;
}
@ -196,7 +200,8 @@ class check {
function resource($a,$b,$message) {
$resource=trim(check::var_dump($a));
if (! eregi("^resource\([0-9]+\) of type \($b\)",$resource)) return check::fail($message);
if (! preg_match("/^resource\([0-9]+\) of type \($b\)/i", $resource))
return check::fail($message);
return TRUE;
}

View file

@ -58,6 +58,7 @@ CPP_TEST_CASES += \
primitive_types \
python_abstractbase \
python_append \
python_builtin \
python_destructor_exception \
python_director \
python_docstring \

View file

@ -36,3 +36,21 @@ try:
raise RuntimeError("missed exception")
except TypeError:
pass
b111 = makeB(111)
bNones = BPtrVector([None, b111, None])
bCount = 0
noneCount = 0
for b in bNones:
if b == None:
noneCount = noneCount + 1
else:
if b.val != 111:
raise RuntimeError("b.val is wrong")
bCount = bCount + 1
if bCount != 1:
raise RuntimeError("bCount wrong")
if noneCount != 2:
raise RuntimeError("noneCount wrong")

View file

@ -2,3 +2,9 @@ from li_std_vector import *
if typedef_test(101) != 101:
raise RuntimeError
try:
sv = StructVector([None, None])
raise RuntimeError("Using None should result in a TypeError")
except TypeError:
pass

View file

@ -0,0 +1,94 @@
from python_builtin import *
if is_python_builtin():
# Test 0 for default tp_hash
vs = ValueStruct(1234)
h = hash(vs)
d = dict()
d[h] = "hi"
if h not in d:
raise RuntimeError("h should be in d")
h2 = hash(ValueStruct.inout(vs))
if h != h2:
raise RuntimeError("default tp_hash not working")
# Test 1 for tp_hash
if hash(SimpleValue(222)) != 222:
raise RuntimeError("tp_hash not working")
# Test 2 for tp_hash
try:
# Was incorrectly raising: SystemError: error return without exception set
h = hash(BadHashFunctionReturnType())
raise RuntimeError("Missing TypeError")
except TypeError:
pass
# Test 3 for tp_hash
passed = False
try:
h = hash(ExceptionHashFunction())
except RuntimeError, e:
passed = str(e).find("oops") != -1
pass
if not passed:
raise RuntimeError("did not catch exception in hash()")
# Test 4 for tp_dealloc (which is handled differently to other slots in the SWIG source)
d = Dealloc1()
if cvar.Dealloc1CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc1CalledCount != 1:
raise RuntimeError("count should be 1")
d = Dealloc2()
if cvar.Dealloc2CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc2CalledCount != 1:
raise RuntimeError("count should be 1")
d = Dealloc3()
if cvar.Dealloc3CalledCount != 0:
raise RuntimeError("count should be 0")
del d
if cvar.Dealloc3CalledCount != 1:
raise RuntimeError("count should be 1")
# Test 5 for python:compare feature
m10 = MyClass(10)
m20 = MyClass(20)
m15 = MyClass(15)
if not m10 < m15:
raise RuntimeError("m10 < m15")
if not m10 < m20:
raise RuntimeError("m10 < m20")
if not m15 < m20:
raise RuntimeError("m15 < m20")
if m10 > m15:
raise RuntimeError("m10 > m15")
if m10 > m20:
raise RuntimeError("m10 > m20")
if m15 > m20:
raise RuntimeError("m15 > m20")
if MyClass.less_than_counts != 6:
raise RuntimeError("python:compare feature not working")
sa = SimpleArray(5)
elements = [x for x in sa]
if elements != [0, 10, 20, 30, 40]:
raise RuntimeError("Iteration not working")
if len(sa) != 5:
raise RuntimeError("len not working")
for i in range(5):
if sa[i] != i*10:
raise RuntimeError("indexing not working")
subslice = sa[1:3]
elements = [x for x in subslice]
if elements != [10, 20]:
raise RuntimeError("slice not working")

View file

@ -0,0 +1,201 @@
// Test customizing slots when using the -builtin option
%module python_builtin
%inline %{
#ifdef SWIGPYTHON_BUILTIN
bool is_python_builtin() { return true; }
#else
bool is_python_builtin() { return false; }
#endif
%}
// Test 0 for default tp_hash
%inline %{
struct ValueStruct {
int value;
ValueStruct(int value) : value(value) {}
static ValueStruct *inout(ValueStruct *v) {
return v;
}
};
%}
// Test 1 for tp_hash
#if defined(SWIGPYTHON_BUILTIN)
%feature("python:tp_hash") SimpleValue "SimpleValueHashFunction"
#endif
%inline %{
struct SimpleValue {
int value;
SimpleValue(int value) : value(value) {}
};
%}
%{
#if PY_VERSION_HEX >= 0x03020000
Py_hash_t SimpleValueHashFunction(PyObject *v)
#else
long SimpleValueHashFunction(PyObject *v)
#endif
{
SwigPyObject *sobj = (SwigPyObject *) v;
SimpleValue *p = (SimpleValue *)sobj->ptr;
return p->value;
}
hashfunc test_hashfunc_cast() {
return SimpleValueHashFunction;
}
%}
// Test 2 for tp_hash
#if defined(SWIGPYTHON_BUILTIN)
%feature("python:slot", "tp_hash", functype="hashfunc") BadHashFunctionReturnType::bad_hash_function;
#endif
%inline %{
struct BadHashFunctionReturnType {
static const char * bad_hash_function() {
return "bad hash function";
}
};
%}
// Test 3 for tp_hash
#if defined(SWIGPYTHON_BUILTIN)
%feature("python:slot", "tp_hash", functype="hashfunc") ExceptionHashFunction::exception_hash_function;
#endif
%catches(const char *) exception_hash_function;
%inline %{
#if PY_VERSION_HEX < 0x03020000
#define Py_hash_t long
#endif
struct ExceptionHashFunction {
static Py_hash_t exception_hash_function() {
throw "oops";
}
};
%}
// Test 4 for tp_dealloc (which is handled differently to other slots in the SWIG source)
#if defined(SWIGPYTHON_BUILTIN)
%feature("python:tp_dealloc") Dealloc1 "Dealloc1Destroyer"
%feature("python:tp_dealloc") Dealloc2 "Dealloc2Destroyer"
%feature("python:slot", "tp_dealloc", functype="destructor") Dealloc3::Destroyer;
#endif
%inline %{
static int Dealloc1CalledCount = 0;
static int Dealloc2CalledCount = 0;
static int Dealloc3CalledCount = 0;
struct Dealloc1 {
};
struct Dealloc2 {
~Dealloc2() {}
};
struct Dealloc3 {
void Destroyer() {
Dealloc3CalledCount++;
delete this;
}
};
%}
%{
void Dealloc1Destroyer(PyObject *v) {
SwigPyObject *sobj = (SwigPyObject *) v;
Dealloc1 *p = (Dealloc1 *)sobj->ptr;
delete p;
Dealloc1CalledCount++;
}
void Dealloc2Destroyer(PyObject *v) {
SwigPyObject *sobj = (SwigPyObject *) v;
Dealloc2 *p = (Dealloc2 *)sobj->ptr;
delete p;
Dealloc2CalledCount++;
}
%}
// Test 5 for python:compare feature
%feature("python:compare", "Py_LT") MyClass::lessThan;
%inline %{
class MyClass {
public:
MyClass(int val = 0) : val(val) {}
bool lessThan(const MyClass& other) const {
less_than_counts++;
return val < other.val;
}
int val;
static int less_than_counts;
};
int MyClass::less_than_counts = 0;
%}
// Test 6 add in container __getitem__ to support basic sequence protocol
// Tests overloaded functions being used for more than one slot (mp_subscript and sq_item)
%include <exception.i>
%include <std_except.i>
%apply int {Py_ssize_t}
%typemap(in) PySliceObject * {
if (!PySlice_Check($input))
SWIG_exception(SWIG_TypeError, "in method '$symname', argument $argnum of type '$type'");
$1 = (PySliceObject *)$input;
}
%typemap(typecheck,precedence=300) PySliceObject* {
$1 = PySlice_Check($input);
}
%feature("python:slot", "mp_subscript", functype="binaryfunc") SimpleArray::__getitem__(PySliceObject *slice);
%feature("python:slot", "sq_item", functype="ssizeargfunc") SimpleArray::__getitem__(Py_ssize_t n);
%feature("python:slot", "sq_length", functype="lenfunc") SimpleArray::__len__;
%inline %{
class SimpleArray {
size_t size;
int numbers[5];
public:
SimpleArray(size_t size) : size(size) {
for (size_t x = 0; x<size; ++x)
numbers[x] = x*10;
}
Py_ssize_t __len__() {
return size;
}
int __getitem__(Py_ssize_t n) throw (std::out_of_range) {
if (n >= (int)size)
throw std::out_of_range("Index too large");
return numbers[n];
}
SimpleArray __getitem__(PySliceObject *slice) throw (std::out_of_range, std::invalid_argument) {
if (!PySlice_Check(slice))
throw std::invalid_argument("Slice object expected");
Py_ssize_t i, j, step;
#if PY_VERSION_HEX >= 0x03020000
PySlice_GetIndices((PyObject *)slice, size, &i, &j, &step);
#else
PySlice_GetIndices((PySliceObject *)slice, size, &i, &j, &step);
#endif
if (step != 1)
throw std::invalid_argument("Only a step size of 1 is implemented");
{
Py_ssize_t ii = i<0 ? 0 : i>=size ? size-1 : i;
Py_ssize_t jj = j<0 ? 0 : j>=size ? size-1 : j;
if (ii > jj)
throw std::invalid_argument("getitem i should not be larger than j");
SimpleArray n(jj-ii);
for (size_t x = 0; x<size; ++x)
n.numbers[x] = numbers[x+ii];
return n;
}
}
};
%}

View file

@ -0,0 +1,91 @@
/* File : swig_exception.i
* Test SWIG_exception().
*/
%module swig_exception
%include exception.i
%exception {
try {
$action
} catch (std::exception& e) {
SWIG_exception(SWIG_SystemError, e.what());
}
}
%inline %{
class Value {
int a_;
int b_;
public:
Value(int a, int b) : a_(a), b_(b) {}
};
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
}
double x, y;
void move(double dx, double dy);
virtual double area() = 0;
virtual double perimeter() = 0;
virtual Value throwException();
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { }
virtual double area();
virtual double perimeter();
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { }
virtual double area();
virtual double perimeter();
};
%}
%{
#define PI 3.14159265358979323846
#include <stdexcept>
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
Value Shape::throwException() {
throw std::logic_error("OK");
}
int Shape::nshapes = 0;
double Circle::area() {
return PI*radius*radius;
}
double Circle::perimeter() {
return 2*PI*radius;
}
double Square::area() {
return width*width;
}
double Square::perimeter() {
return 4*width;
}
%}

View file

@ -25,23 +25,33 @@ void foo1(Foo<int> f, const Foo<int>& ff) {}
void foo2(Foo<short> f, const Foo<short>& ff) {}
%}
#ifdef SWIGUTL
%typemap(ret) int Bar1::foo() { /* hello1 */ };
%typemap(ret) int Bar2::foo() { /* hello2 */ };
%typemap(ret) int foo() {/* hello3 */ };
#endif
// Check "ret" typemap is implemented
%{
template<typename T> struct NeededForTest {};
%}
%fragment("NeededForTest", "header") %{
template<> struct NeededForTest<short> { NeededForTest(short) {} };
%}
%typemap(ret) short "_ret_typemap_for_short_no_compile"
%typemap(ret, fragment="NeededForTest") short Bar1::foofunction() { /* ret typemap for short */ NeededForTest<short> needed($1); };
%typemap(ret, fragment="NeededForTest") short globalfoofunction() { /* ret typemap for short */ NeededForTest<short> needed($1); };
%inline %{
struct Bar1 {
int foo() { return 1;}
};
struct Bar2 {
int foo() { return 1;}
short foofunction() { return 1;}
};
short globalfoofunction() { return 1;}
%}
%{
void CheckRetTypemapUsed() {
// If the "ret" typemap is not used, the NeededForTest template specialization will not have been
// generated and so the following code will result in a compile failure
NeededForTest<short> needed(111);
(void)needed;
}
%}
%newobject FFoo::Bar(bool) const ;
%typemap(newfree) char* Bar(bool) {
@ -62,7 +72,7 @@ void foo2(Foo<short> f, const Foo<short>& ff) {}
#endif
// Test obscure bug where named typemaps where not being applied when symbol name contained a number
%typemap(out) double "_typemap_for_double_no_compile_"
%typemap(out) double "_out_typemap_for_double_no_compile_"
%typemap(out) double ABCD::meth {$1 = 0.0; TYPEMAP_OUT_INIT}
%typemap(out) double ABCD::m1 {$1 = 0.0; TYPEMAP_OUT_INIT}
%typemap(out) double ABCD::_x2 {$1 = 0.0; TYPEMAP_OUT_INIT}

View file

@ -0,0 +1,16 @@
%module variable_replacement
%inline %{
class A {
public:
int a(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12)
{
return 0;
}
};
class B : public A {
};
%}