diff --git a/.gitignore b/.gitignore index 400ce4469..4001af7c3 100644 --- a/.gitignore +++ b/.gitignore @@ -101,32 +101,11 @@ Doc/Manual/SWIGDocumentation.html Doc/Manual/SWIGDocumentation.pdf Doc/Manual/*.book -# Test Suite Generated Files -Examples/test-suite/allegrocl/*/ -Examples/test-suite/cffi/*/ -Examples/test-suite/chicken/*/ -Examples/test-suite/clisp/*/ -Examples/test-suite/csharp/*/ -Examples/test-suite/d/*/ -Examples/test-suite/go/*/ -Examples/test-suite/guile/*/ -Examples/test-suite/java/*/ -Examples/test-suite/javascript/*/ -Examples/test-suite/lua/*/ -Examples/test-suite/mzscheme/*/ -Examples/test-suite/ocaml/*/ -Examples/test-suite/octave/*/ -Examples/test-suite/perl5/*/ -Examples/test-suite/php/*/ -Examples/test-suite/pike/*/ -Examples/test-suite/python/*/ -Examples/test-suite/r/*/ -Examples/test-suite/ruby/*/ -Examples/test-suite/scilab/*/ -Examples/test-suite/tcl/*/ -Examples/test-suite/uffi/*/ +# SWIG common generated files *_wrap.c +*_wrap.cpp *_wrap.cxx +*_wrap.h *-gypcopy.cxx # Scratch directories @@ -137,27 +116,73 @@ Examples/scratch ########## Language specific files ########## -# C# generated files -*_runme.exe.mdb -*_runme.exe +# C# +Examples/test-suite/csharp/*/ +*runme.exe.mdb +*runme.exe +Examples/csharp/*/*.cs +!Examples/csharp/*/runme.cs -# Go generated files +# D +Examples/test-suite/d/*/ +Examples/d/**/example.d +Examples/d/**/example_im.d +Examples/d/**/runme + +# Go *.[5689] *_gc.c -# Javascript generated files +# Guile +Examples/guile/*/my-guile + +# Java +Examples/test-suite/java/*/ +Examples/java/*/*.java +!Examples/java/*/runme.java + +# Javascript +Examples/test-suite/javascript/*/ *.gyp -# Octave generated files +# Octave swigexample*.oct Examples/test-suite/octave/*.oct -# Python generated files, based on: -# https://github.com/github/gitignore/blob/master/Python.gitignore +# Perl5 +Examples/test-suite/perl5/*.pm +Examples/perl5/*/*.pm + +# PHP +Examples/test-suite/php/php_*.h +Examples/test-suite/php/*.php +!Examples/test-suite/php/*runme.php +!Examples/test-suite/php/skel.php +Examples/php/*/php_*.h +Examples/php/*/example.php + +# Python +# Based on https://github.com/github/gitignore/blob/master/Python.gitignore *.py[cod] */__pycache__/ /__pycache__/ +Examples/test-suite/python/*.py +!Examples/test-suite/python/*runme.py +Examples/python/*/example.py +Examples/python/**/bar.py +Examples/python/**/base.py +Examples/python/**/foo.py +Examples/python/**/spam.py -# Scilab generated files +# R +Examples/test-suite/r/*.R +Examples/test-suite/r/*.Rout +!Examples/test-suite/r/*runme.R +Examples/r/*/example.R +Examples/r/*/*.Rout +Examples/r/*/.RData + +# Scilab +Examples/test-suite/scilab/*/ loader.sce diff --git a/.travis.yml b/.travis.yml index 8d814e7f8..9b47611b7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,14 @@ language: cpp -compiler: - - clang - - gcc -env: - - SWIGLANG= matrix: include: + - compiler: clang + env: SWIGLANG= + - compiler: gcc + env: SWIGLANG= + - compiler: gcc + env: SWIGLANG= GCC5=1 CPP11=1 + - compiler: gcc + env: SWIGLANG= GCC5=1 CPP14=1 - compiler: gcc env: SWIGLANG=csharp - compiler: gcc @@ -28,6 +31,8 @@ matrix: env: SWIGLANG=octave SWIGJOBS=-j3 # 3.2 - compiler: gcc env: SWIGLANG=octave SWIGJOBS=-j3 VER=3.8 + - compiler: gcc + env: SWIGLANG=octave SWIGJOBS=-j3 VER=4.0 - compiler: gcc env: SWIGLANG=perl5 - compiler: gcc @@ -50,27 +55,51 @@ matrix: env: SWIGLANG=python SWIG_FEATURES=-builtin - compiler: gcc env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 + - compiler: gcc + env: SWIGLANG=python SWIG_FEATURES=-O - compiler: gcc env: SWIGLANG=python SWIG_FEATURES=-classic + - compiler: gcc + env: SWIGLANG=r - compiler: gcc env: SWIGLANG=ruby - compiler: gcc env: SWIGLANG=scilab - compiler: gcc env: SWIGLANG=tcl + - compiler: gcc + env: SWIGLANG=csharp GCC5=1 CPP11=1 + - compiler: gcc + env: SWIGLANG=java GCC5=1 CPP11=1 + - compiler: gcc + env: SWIGLANG=python GCC5=1 CPP11=1 allow_failures: + # Lots of failing tests currently + - compiler: gcc + env: SWIGLANG=ocaml # Occasional gcc internal compiler error - compiler: gcc env: SWIGLANG=octave SWIGJOBS=-j3 VER=3.8 + # Occasional gcc internal compiler error + - compiler: gcc + env: SWIGLANG=octave SWIGJOBS=-j3 VER=4.0 # Not quite working yet - compiler: gcc env: SWIGLANG=python SWIG_FEATURES=-classic + # Not quite working yet + - compiler: gcc + env: SWIGLANG=python SWIG_FEATURES=-O + # Runtime errors in Travis environment + - compiler: gcc + env: SWIGLANG=r before_install: - date -u - uname -a - lsb_release -a - sudo apt-get -qq update - - time sudo apt-get -qq install libboost-dev + - if test -n "$GCC5"; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test && sudo apt-get -qq update && sudo apt-get install -qq g++-5 && export CC=gcc-5 && export CXX=g++-5; fi + - if test -z "$GCC5"; then sudo apt-get -qq install libboost-dev; fi + - if test -n "$GCC5"; then sudo add-apt-repository -y ppa:boost-latest/ppa && sudo apt-get -qq update && sudo apt-get install -qq libboost1.55-dev; fi - if test -z "$SWIGLANG"; then sudo apt-get -qq install yodl; fi - if test "$SWIGLANG" = "csharp"; then sudo apt-get -qq install mono-devel; fi - if test "$SWIGLANG" = "d"; then wget http://downloads.dlang.org/releases/2014/dmd_2.066.0-0_amd64.deb; sudo dpkg -i dmd_2.066.0-0_amd64.deb; fi @@ -80,22 +109,28 @@ before_install: - if test "$SWIGLANG" = "javascript" -a "$ENGINE" = "v8"; then sudo apt-get install -qq libv8-dev; fi - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi + # configure also looks for ocamldlgen, but this isn't packaged. But it isn't used by default so this doesn't matter. + - if test "$SWIGLANG" = "ocaml"; then sudo apt-get -qq install ocaml ocaml-findlib; fi - if test "$SWIGLANG" = "octave" -a -z "$VER"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi - if test "$SWIGLANG" = "octave" -a "$VER"; then sudo add-apt-repository -y ppa:kwwette/octaves && sudo apt-get -qq update && sudo apt-get -qq install liboctave${VER}-dev; fi - if test "$SWIGLANG" = "php"; then sudo apt-get install php5-cli php5-dev; fi - if test "$SWIGLANG" = "python"; then git clone https://github.com/jcrocholl/pep8.git && pushd pep8 && git checkout tags/1.5.7 && python ./setup.py build && sudo python ./setup.py install && popd; fi - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi - - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && export CONFIGOPTS="--with-python${PY3}=python${VER}"; fi + - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && CONFIGOPTS+=("--with-python${PY3}=python${VER}"); fi + - if test "$SWIGLANG" = "r"; then sudo apt-get -qq install r-base; fi - if test "$SWIGLANG" = "scilab"; then sudo apt-get -qq install scilab; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi + - if test -n "$CPP11"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++11 -Wall -Wextra" "CFLAGS=-std=c11 -Wall -Wextra") && export CSTD=c11 && export CPPSTD=c++11; fi + - if test -n "$CPP14"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++14 -Wall -Wextra" "CFLAGS=-std=c11 -Wall -Wextra") && export CSTD=c11 && export CPPSTD=c++14; fi - $CC --version - $CXX --version # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic. - - export cflags=$(./testflags.py --language $SWIGLANG --cflags) && echo $cflags - - export cxxflags=$(./testflags.py --language $SWIGLANG --cxxflags) && echo $cxxflags + - if test -n "$SWIGLANG"; then export cflags=$(Tools/testflags.py --language $SWIGLANG --cflags --std=$CSTD) && echo $cflags; fi + - if test -n "$SWIGLANG"; then export cxxflags=$(Tools/testflags.py --language $SWIGLANG --cxxflags --std=$CPPSTD) && echo $cxxflags; fi script: - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - - ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure $CONFIGOPTS + - echo "${CONFIGOPTS[@]}" + - ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure "${CONFIGOPTS[@]}" - echo -en 'travis_fold:end:script.1\\r' - make -s $SWIGJOBS - ./swig -version && ./swig -pcreversion @@ -113,4 +148,3 @@ script: branches: only: - master - - error-declaration-after-statement diff --git a/ANNOUNCE b/ANNOUNCE index 96b1904ac..f7d7eb8a9 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 3.0.6 (in progress) *** +*** ANNOUNCE: SWIG 3.0.7 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-3.0.6, the latest SWIG release. +We're pleased to announce SWIG-3.0.7, the latest SWIG release. What is SWIG? ============= @@ -22,11 +22,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-3.0.6.tar.gz + http://prdownloads.sourceforge.net/swig/swig-3.0.7.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-3.0.6.zip + http://prdownloads.sourceforge.net/swig/swigwin-3.0.7.zip Please report problems with this release to the swig-devel mailing list, details at http://www.swig.org/mail.html. diff --git a/CCache/test.sh b/CCache/test.sh index f64c3e3de..6e5d26703 100755 --- a/CCache/test.sh +++ b/CCache/test.sh @@ -402,6 +402,29 @@ swigtests() { rm -rf $TESTDIR mkdir $TESTDIR cd $TESTDIR || exit 1 + +unset CCACHE_DIR +unset CCACHE_TEMPDIR +unset CCACHE_LOGFILE +unset CCACHE_VERBOSE +unset CCACHE_PATH +unset CCACHE_CC +unset CCACHE_PREFIX +unset CCACHE_DISABLE +unset CCACHE_READONLY +unset CCACHE_CPP2 +unset CCACHE_NOCOMPRESS +unset CCACHE_NOSTATS +unset CCACHE_NLEVELS +unset CCACHE_HARDLINK +unset CCACHE_RECACHE +unset CCACHE_UMASK +unset CCACHE_HASHDIR +unset CCACHE_UNIFY +unset CCACHE_EXTENSION +unset CCACHE_STRIPC +unset CCACHE_SWIG + CCACHE_DIR="ccache dir" # with space in directory name (like Windows default) mkdir "$CCACHE_DIR" export CCACHE_DIR diff --git a/CHANGES b/CHANGES index 8bea8c1c2..eb500e5f4 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,208 @@ SWIG (Simplified Wrapper and Interface Generator) See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. +Version 3.0.6 (5 Jul 2015) +========================== + +2015-07-02: wsfulton + Fix syntax error when the template keyword is used in types, eg: + + std::template vector v; + +2015-07-02: ngladitz + [Lua] Push characters as unformatted 1-character strings to avoid + unprintable characters such as (char)127 being converted to + "<\127>" with Lua 5.3 and later. (github PR #452) + +2015-06-29: olly + [Python] Improve handling of whitespace in %pythoncode. + + Previously SWIG looked at the indentation of the first line and + removed that many characters from each subsequent line, regardless + of what those characters were. This was made worse because SWIG's + preprocessor removes any whitespace before a '#'. Fixes github + issue #379, reported by Joe Orton. + +2015-06-12: wsfulton + [R] Fix #430 - call to SWIG_createNewRef in copyToC was incorrectly named. + +2015-06-11: sghirate + [C#] Patch #427 adds in new command line option -outfile to combine all the + generated C# code into a single file. + +2015-06-09: wsfulton + Fix seg fault processing C++11 type aliasing. Issue #424. + +2015-05-28: wsfulton + [Python] Add new feature "python:cdefaultargs" to control default argument + code generation. By default, SWIG attempts to convert C/C++ default argument values + into Python values and generates code into the Python layer with these values. + Recent versions of SWIG are able to convert more of these values, however, the + new behaviour can be circumvented if desired via this new feature, such that + the default argument values are obtained from the C layer and not the Python layer. + For example: + + struct CDA { + int fff(int a = 1, bool b = false); + }; + + The default code generation in the Python layer is: + + class CDA(_object): + ... + def fff(self, a=1, b=False): + return _default_args.CDA_fff(self, a, b) + + Adding the feature: + + %feature("python:cdefaultargs") CDA::fff; + + Results in: + + class CDA(_object): + ... + def fff(self, *args): + return _default_args.CDA_fff(self, *args) + + Some code generation modes, eg -builtin and -fastproxy, are unaffected by this as + the default values are always obtained from the C layer. + +2015-05-27: wsfulton + [Python] Deal with an integer as the default value of a typedef to bool + parameter in the C++ prototype. See #327. Regression from 3.0.0 onwards. + +2015-05-19: olly + [Python] Fix warning when compiling generated code with MSVC. + (Fixes https://sourceforge.net/p/swig/patches/351/ reported by + Mateusz Szyma¿ski). + +2015-05-14: wsfulton + Fix seg fault wrapping shared_ptr of classes with private constructors and destructors. + This also fixes the "unref" feature when used on classes with private destructors. + +2015-05-10: wsfulton + [Java] Fix multi-argument typemaps (char *STRING, size_t LENGTH) + so that they can be applied to a wider range of types. Fixes #385. + +2015-05-07: olly + [Python] Deal with an integer as the default value of a bool + parameter in the C++ prototype. Fixes github #327, reported by + Greg Allen. + +2015-05-07: LindleyF + [Java] Allow feature("director") and feature("ref") to be used + together. Github PR#403. + +2015-05-05: olly + Suppress warning 325 "Nested class not currently supported (Foo + ignored)" when Foo has already been explicitly ignored with "%ignore". + +2015-05-04: wsfulton + Add support for friend templates, including operator overloading - fixes #196. Considering + the example below, previously the operator gave a syntax error and friendfunc incorrectly + warned with: + + "Warning 503: Can't wrap 'friendfunc<(Type)>' unless renamed to a valid identifier." + + template class MyClass { + friend int friendfunc (double is, MyClass & x); + friend int operator<< (double un, const MyClass &x); + }; + + The following also previously incorrectly warned with: + + "Warning 302: Identifier 'template_friend' redefined (ignored)," + + template T template_friend(T); + struct MyTemplate { + template friend T template_friend(T); + }; + +2015-05-01: wsfulton + Fix handling of conversion operators where the operator is split over multiple + lines or has comments within the operator type. Fixes #401. + + Also fix similar problem with normal operators which gave a syntax error if split over + multiple lines or had a comment within the operator declaration. + +2015-04-30: olly + Ignore unknown preprocessor directives which are inside an inactive + conditional (github issue #394, reported by Dan Wilcox). + Regression introduced in 3.0.3. + +2015-04-27: vadz + [Python] Fix "default" typemap used after an argument with "numinputs=0" (#377). + +2015-04-24: wsfulton + [Python] Fix #256. Code generated with '-builtin -modernargs' segfaults for any + method taking zero arguments. + + Also fixes: "SystemError: error return without exception set" during error checking + when using just -builtin and the incorrect number of arguments is passed to a class + method expecting zero arguments. + +2015-04-23: wsfulton + [Java] Bug #386 - Memory leak fix in (char *STRING, size_t LENGTH) typemaps. + +2015-04-23: vadz + [Python] Make "default" typemap work again (#330, #377). + +2015-04-23: vadz + [Python] Fix the use of default values for the pointer types (#365, #376). + +2015-04-23: wsfulton + Fix 'make check-ccache' which is part of 'make check' when one of the CCACHE_ + environment variables, for example CCACHE_DISABLE, is set. + +2015-04-14: wsfulton + Clearer warning message for badly constructed typecheck typemaps. For example, was: + + example.i:3: Warning 467: Overloaded foo(int) not supported (no type checking + rule for 'int'). + + Now: + + example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking + rule - no precedence level in typecheck typemap for 'int'). + +2015-04-11: wsfulton + [Java] Fix #353 - Linker multiple definition of 'ExceptionMatches' when + using directors and multiple modules. + +2015-04-11: wsfulton + Merge #320 - Make __dict__ accessible for Python builtin classes. + +2015-04-07: wsfulton + Fix #375 - parsing of extern "C" and typedef for example: + extern "C" typedef void (*Hook2_t)(int, const char *); + extern "C" typedef int Integer; + +2015-03-12: olly + -DSWIG_DIRECTOR_STATIC is now supported for all languages with + director support, not only Python and PHP. + +2015-03-02: ianlancetaylor + [Go] Add -cgo option, required for Go versions 1.5 and + later. + +2015-02-26: olly + Fix segmentation fault when top==NULL, introduced by nested class + handling (reported in issue#346 by Pawe¿ Tomulik). + +2015-02-09: wsfulton + [Guile] Fix generated code for static const char member variables when + defined and declared inline. + +2015-02-09: mishas + [Go] Fix %import of files in sub directories. + +2015-02-05: ianlancetaylor + [Go] Ignore Go specific type maps (goin, goout, etc.) if they are empty. + +2015-02-05: ianlancetaylor + [Go] Generated Go code no longer calls _swig_goallocate or + _swig_makegostring, as they will no longer work as of Go 1.5. + Version 3.0.5 (31 Jan 2015) =========================== @@ -100,6 +302,10 @@ Version 3.0.3 (30 Dec 2014) [Python] Patch #201 The generated .py file no longer uses *args for all Python parameters. Instead, the parameters are named using the C++ parameter names. + "compactdefaultargs" feature can be enabled to restore the old behaviour. + + *** POTENTIAL INCOMPATIBILITY *** + 2014-10-24: timotheecour [D] Patch #204 Use core.atomic.atomicOp to mutate shared variables @@ -10707,7 +10913,7 @@ Version 1.3.23 (November 11, 2004) now if you have - %pythonnondynamic(1) A; + %pythonnondynamic A; struct A { int a; @@ -10725,11 +10931,11 @@ Version 1.3.23 (November 11, 2004) Since this is a feature, you can use - %pythonnondynamic(1); + %pythonnondynamic; or - %pythondynamic(0); [ Note: %pythondynamic since deprecated ] + %pythondynamic; [ Note: %pythondynamic since deprecated ] to force all the wrapped classes to be "nondynamic" ones. diff --git a/CHANGES.current b/CHANGES.current index 4679e8d63..0c56946f8 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,16 +2,27 @@ Below are the changes for the current release. See the CHANGES file for changes in older releases. See the RELEASENOTES file for a summary of changes in each release. -Version 3.0.6 (in progress) +Version 3.0.7 (in progress) =========================== -2015-02-09: wsfulton - [Guile] Fix generated code for static const char member variables when - defined and declared inline. +2015-07-18: m7thon + [Python] Docstrings provided via %feature("docstring") are now quoted and added to + the tp_doc slot when using python builtin classes (-builtin). When no docstring is + provided, the tp_doc slot is set to the fully qualified C/C++ class name. + Github issues #445 and #461. -2015-02-05: ianlancetaylor - [Go] Ignore Go specific type maps (goin, goout, etc.) if they are empty. +2015-07-17: kwwette + [octave] Support Octave version 4.0.0 (thanks to patches from Orion Poplawski). + +2015-07-07: wsfulton + SWIG no longer generates a wrapper for a class' constructor if that class has + any base class with a private destructor. This is because your compiler should + not allow a class to be instantiated if a base has a private destructor. Some + compilers do, so if you need the old behaviour, use the "notabstract" feature, eg: + + %feature("notabstract") Derived; + class Base { + ~Base() {} + }; + struct Derived : Base {}; -2015-02-05: ianlancetaylor - [Go] Generated Go code no longer calls _swig_goallocate or - _swig_makegostring, as they will no longer work as of Go 1.5. diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index ba49fa004..18fc3037e 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -12,6 +12,7 @@
  • Introduction
  • Differences to the Java module
  • Void pointers @@ -34,7 +35,7 @@
  • Directors implementation
  • Director caveats -
  • Multiples modules +
  • Multiple modules
  • C# Typemap examples -
  • Multiples modules +
  • Multiple modules
  • C# Typemap examples
  • Creating Applications with node-webkit -
  • Examples +
  • Examples
  • Typemaps
  • Structures -
  • C++ Classes +
  • C++ classes
  • C++ inheritance
  • Pointers, references, values, and arrays
  • C++ templates diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 895e6c581..20e923d19 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -111,6 +111,14 @@ swig -go -help Go specific options + +-cgo +Generate files to be used as input for the Go cgo tool. This + option is required for Go 1.5 and later, and works for Go 1.2 and + later. In the future this option will likely become the + default. + + -intgosize <s> Set the size for the Go type int. This controls the size @@ -171,8 +179,13 @@ swig -go -help

    23.3.2 Go Output Files

    -

    When generating Go code, SWIG will generate the following - files:

    +

    There are two different approaches to generating output files, + controlled by SWIG's -cgo option. The -cgo option + works with Go version 1.2 or later. It is required when using Go + version 1.5 or later.

    + +

    With or without the -cgo option, SWIG will generate the + following files when generating Go code:

    • @@ -180,21 +193,30 @@ MODULE.go will contain the Go functions that your Go code will call. These functions will be wrappers for the C++ functions defined by your module. This file should, of course, be compiled with the Go compiler. +
    • MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will be invoked by the Go wrapper code. This file should be compiled with the -usual C or C++ compiler and linked into a shared library. +usual C or C++ compiler. +
    • MODULE_wrap.h will be generated if you use the directors feature. It provides a definition of the generated C++ director classes. It is generally not necessary to use this file, but in some special cases it may be helpful to include it in your code, compiled with the usual C or C++ compiler. +
    • +
    + +

    When neither the -cgo nor the -gccgo option is + used, SWIG will also generate an additional file:

    + +
    • -If using the gc compiler, MODULE_gc.c will contain C code which should -be compiled with the C compiler distributed as part of the gc -compiler. It should then be combined with the compiled MODULE.go -using gopack. This file will not be generated when using gccgo. +MODULE_gc.c will contain C code which should be compiled with the C +compiler distributed as part of the gc compiler. It should then be +combined with the compiled MODULE.go using go tool pack. +

    @@ -203,14 +225,33 @@ support for SWIG. To use it, put your SWIG interface into a file with the extension .swig, or, if you are wrapping C++ code, .swigcxx. Put that file in a GOPATH/src directory as usual for Go sources. Put other interface code in the same directory with extensions of .c and -.cxx. The go build command and go install commands will automatically -run SWIG for you and will build the interface code. +.cxx. The go build and go install commands will +automatically run SWIG for you and will build the interface code.

    -You can also use SWIG directly yourself. When using the gc compiler -version 1.2 or later, or when using gccgo, the code generated by SWIG -can be linked directly into the Go program. A typical command +You can also use SWIG directly yourself. When using +the -cgo option, SWIG will generate files that can be used +directly by go build. Put your SWIG input file in a +directory under GOPATH/src, and give it a name that does not end in +.swig or .swigcxx. +

    + +
    +% swig -go -cgo example.i
    +% go install
    +
    + +

    +You will now have a Go package that you can import from other Go +packages as usual. +

    + +

    +To use SWIG without the -cgo option, more steps are required. +Recall that this only works with Go versions before 1.5. When using +Go version 1.2 or later, or when using gccgo, the code generated by +SWIG can be linked directly into the Go program. A typical command sequence when using the gc compiler would look like this:

    @@ -227,9 +268,8 @@ sequence when using the gc compiler would look like this:

    You can also put the wrapped code into a shared library, and when -using the gc compiler before version 1.2 this is the only supported -option. A typical command sequence for this approach would look like -this: +using the Go versions before 1.2 this is the only supported option. A +typical command sequence for this approach would look like this:

    @@ -396,34 +436,120 @@ for this by calling the Swigcptr() method.
     
     
     

    -Calling NewClassName for some C++ class ClassName -will allocate memory using the C++ memory allocator. This memory will -not be automatically freed by Go's garbage collector as the object ownership is -not tracked. When you are done with the C++ object you must free it manually -using DeleteClassName. -

    - -

    -A common technique is to store the C++ object into a Go object, and -use the Go function runtime.SetFinalizer to free the C++ object when -the Go object is freed. It is strongly recommended to read the -runtime.SetFinalizer -documentation before using this technique to understand its limitations. -For example, if the SWIG package is imported as "wrap": +Calling NewClassName for a C++ class ClassName will allocate +memory using the C++ memory allocator. This memory will not be automatically +freed by Go's garbage collector as the object ownership is not tracked. When +you are done with the C++ object you must free it using +DeleteClassName.
    +
    +The most Go idiomatic way to manage the memory for some C++ class is to call +NewClassName followed by a +defer of +the DeleteClassName call. Using defer ensures that the memory +of the C++ object is freed as soon as the function containing the defer +statement returns. Furthemore defer works great for short-lived +objects and fits nicely C++'s RAII idiom. Example:

    +func UseClassName(...) ... {
    +	o := NewClassName(...)
    +	defer DeleteClassName(o)
    +	// Use the ClassName object
    +	return ...
    +}
    +
    +
    + +

    +With increasing complexity, especially complex C++ object hierarchies, the +correct placement of defer statements becomes harder and harder as C++ +objects need to be freed in the correct order. This problem can be eased by +keeping a C++ object function local so that it is only available to the function +that creates a C++ object and functions called by this function. Example: +

    +
    +
    +func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error {
    +	o := NewClassName(constructor args)
    +	defer DeleteClassName(o)
    +	return f(o, data...)
    +}
    +
    +func UseClassName(o ClassName, data ...interface{}) (err error) {
    +	// Use the ClassName object and additional data and return error.
    +}
    +
    +func main() {
    +	WithClassName(constructor args, UseClassName, additional data)
    +}
    +
    +
    + +

    +Using defer has limitations though, especially when it comes to +long-lived C++ objects whichs lifetimes are hard to predict. For such C++ +objects a common technique is to store the C++ object into a Go object, and to +use the Go function runtime.SetFinalizer to add a finalizer which frees +the C++ object when the Go object is freed. It is strongly recommended to read +the runtime.SetFinalizer + documentation before using this technique to understand the +runtime.SetFinalizer limitations.
    +

    +

    +Common pitfalls with runtime.SetFinalizer are: +

    +
      +
    • +If a hierarchy of C++ objects will be automatically freed by Go finalizers then +the Go objects that store the C++ objects need to replicate the hierarchy of the +C++ objects to prevent that C++ objects are freed prematurely while other C++ +objects still rely on them. +
    • +
    • +The usage of Go finalizers is problematic with C++'s RAII idiom as it isn't +predictable when the finalizer will run and this might require a Close or Delete +method to be added the Go object that stores a C++ object to mitigate. +
    • +
    • +The Go finalizer function typically runs in a different OS thread which can be +problematic with C++ code that uses thread-local storage. +
    • +
    + +

    +runtime.SetFinalizer Example: +

    +
    +
    +import (
    +	"runtime"
    +	"wrap" // SWIG generated wrapper code
    +)
    +
     type GoClassName struct {
    -	w wrap.ClassName
    +	wcn wrap.ClassName
     }
     
     func NewGoClassName() *GoClassName {
    -	r := &GoClassName{wrap.NewClassName()}
    -	runtime.SetFinalizer(r,
    -		func(r *GoClassName) {
    -			wrap.DeleteClassName(r.w)
    -		})
    -	return r
    +	o := &GoClassName{wcn: wrap.NewClassName()}
    +	runtime.SetFinalizer(o, deleteGoClassName)
    +	return o
    +}
    +
    +func deleteGoClassName(o *GoClassName) {
    +	// Runs typically in a different OS thread!
    +	wrap.DeleteClassName(o.wcn)
    +	o.wcn = nil
    +}
    +
    +func (o *GoClassName) Close() {
    +	// If the C++ object has a Close method.
    +	o.wcn.Close()
    +
    +	// If the GoClassName object is no longer in an usable state.
    +	runtime.SetFinalizer(o, nil) // Remove finalizer.
    +	deleteGoClassName() // Free the C++ object.
     }
     
    diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index 9cc4277c9..02a41169a 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -457,6 +457,12 @@ be used on any platform. Again, this is an important part of staying out of the programmer's way----the last thing any developer wants to do is to spend their time debugging the output of a tool that relies on non-portable or unreliable programming features. +Dependencies are often a source of incompatibilities and problems and so +additional third party libraries are not used in the generated code. +SWIG will also generally avoid generating code that introduces a dependency +on the C++ Standard Template Library (STL). +SWIG will generate code that depends on the C libraries though. +

    diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index cae199048..7857d9770 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -30,7 +30,7 @@
  • Creating Applications with node-webkit -
  • Examples +
  • Examples
    • Simple
    • Class @@ -197,10 +197,10 @@ $ sudo npm install -g node-gyp
  •  $ swig -javascript -node -c++ example.i
    -

    Then run node-gyp

    +

    Then run node-gyp build to actually create the module:

    -$ node-gyp
    +$ node-gyp build

    This will create a build folder containing the native module. To use the extension you need to 'require' it in your Javascript source file:

    @@ -410,7 +410,7 @@ open new windows, and many more things. };
    -

    26.4 Examples

    +

    26.4 Examples

    Some basic examples are shown here in more detail.

    diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 740988e71..069707559 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -1900,7 +1900,9 @@ Adding the missing %shared_ptr macros will fix this:

    -Note: There is currently no support for %shared_ptr and the director feature. +Note: There is somewhat limited support for %shared_ptr and the director feature +and the degress of success varies among the different target languages. +Please help to improve this support by providing patches with improvements.

    diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index 61f19be68..2e1515c43 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -891,7 +891,7 @@ void spam(short);

    or

    -
    VOID FOO(bAR *B);
    +
    void foo(Bar *b);
     void foo(Bar &b);
     

    diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 551fd0750..4846aedc1 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -250,7 +250,9 @@ the functions SWIG_TypeQuery, SWIG_NewPointerObj, and others s to be called. Calling these functions from a typemap is supported, since the typemap code is embedded into the _wrap.c file, which has those declarations available. If you need to call the SWIG run-time functions from another C file, there is one header you need -to include. To generate the header that needs to be included, run the following command: +to include. To generate the header that needs to be included, SWIG can be run in a different +mode via -external-runtime to generate the run-time instead of the normal mode of +processing an input interface file. For example:

     $ swig -python -external-runtime <filename>
    diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html
    index aa6679f9a..da20b8da3 100644
    --- a/Doc/Manual/Ocaml.html
    +++ b/Doc/Manual/Ocaml.html
    @@ -1,11 +1,11 @@
     
     
     
    -  SWIG and Ocaml
    +SWIG and Ocaml
     
     
    -  
    -                   
    +
    +
     

    31 SWIG and Ocaml

    @@ -59,20 +59,23 @@

    - This chapter describes SWIG's -support of Ocaml. Ocaml is a relatively recent addition to the ML family, -and is a recent addition to SWIG. It's the second compiled, typed -language to be added. Ocaml has widely acknowledged benefits for engineers, -mostly derived from a sophisticated type system, compile-time checking -which eliminates several classes of common programming errors, and good -native performance. While all of this is wonderful, there are well-written -C and C++ libraries that Ocaml users will want to take advantage of as -part of their arsenal (such as SSL and gdbm), as well as their own mature -C and C++ code. SWIG allows this code to be used in a natural, type-safe -way with Ocaml, by providing the necessary, but repetitive glue code -which creates and uses Ocaml values to communicate with C and C++ code. - In addition, SWIG also produces the needed Ocaml source that binds -variants, functions, classes, etc. +This chapter describes SWIG's support of Ocaml. +

    + +

    +Ocaml is a relatively recent addition to the ML family, +and is a recent addition to SWIG. It's the second compiled, typed +language to be added. Ocaml has widely acknowledged benefits for engineers, +mostly derived from a sophisticated type system, compile-time checking +which eliminates several classes of common programming errors, and good +native performance. While all of this is wonderful, there are well-written +C and C++ libraries that Ocaml users will want to take advantage of as +part of their arsenal (such as SSL and gdbm), as well as their own mature +C and C++ code. SWIG allows this code to be used in a natural, type-safe +way with Ocaml, by providing the necessary, but repetitive glue code +which creates and uses Ocaml values to communicate with C and C++ code. +In addition, SWIG also produces the needed Ocaml source that binds +variants, functions, classes, etc.

    @@ -84,17 +87,16 @@ If you're not familiar with the Objective Caml language, you can visit

    - SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, - you should use the latest stable release. The SWIG Ocaml module has -been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The -best way to determine whether your system will work is to compile the -examples and test-suite which come with SWIG. You can do this by running -make check from the SWIG root directory after installing SWIG. - The Ocaml module has been tested using the system's dynamic linking (the -usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's -Dl package -. The ocaml_dynamic and ocaml_dynamic_cpp targets in the +SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, +you should use the latest stable release. The SWIG Ocaml module has +been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The +best way to determine whether your system will work is to compile the +examples and test-suite which come with SWIG. You can do this by running +make check from the SWIG root directory after installing SWIG. +The Ocaml module has been tested using the system's dynamic linking (the +usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's +Dl package. +The ocaml_dynamic and ocaml_dynamic_cpp targets in the file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.

    @@ -103,30 +105,30 @@ will be loaded dynamically. This has only been tested on Linux so far.

    - The basics of getting a SWIG Ocaml module up and running - can be seen from one of SWIG's example Makefiles, but is also described - here. To build an Ocaml module, run SWIG using the -ocaml -option. +The basics of getting a SWIG Ocaml module up and running +can be seen from one of SWIG's example Makefiles, but is also described +here. To build an Ocaml module, run SWIG using the -ocaml +option.

    -
    -
    +
    +
     %swig -ocaml example.i
    -  
    +
    - -

    This will produce 3 files. The file example_wrap.c contains + +

    This will produce 3 files. The file example_wrap.c contains all of the C code needed to build an Ocaml module. To build the module, -you will compile the file example_wrap.c with ocamlc or +you will compile the file example_wrap.c with ocamlc or ocamlopt to create the needed .o file. You will need to compile the resulting .ml and .mli files as well, and do the final link with -custom -(not needed for native link).

    - +(not needed for native link).

    +

    31.1.2 Compiling the code

    -The OCaml SWIG module now requires you to compile a module (Swig) +The OCaml SWIG module now requires you to compile a module (Swig) separately. In addition to aggregating common SWIG functionality, the Swig module contains the data structure that represents C/C++ values. This allows easier data sharing between modules if two or more are combined, because @@ -134,28 +136,29 @@ the type of each SWIG'ed module's c_obj is derived from Swig.c_obj_t. This also allows SWIG to acquire new conversions painlessly, as well as giving the user more freedom with respect to custom typing. - Use ocamlc or ocamlopt to compile your - SWIG interface like: +Use ocamlc or ocamlopt to compile your SWIG interface like:

    - -
    -
    +
    +
    +
     % swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
     % ocamlc -c swig.mli ; ocamlc -c swig.ml
     % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
     % ocamlc -c example.mli
     % ocamlc -c example.ml
    -  
    +
    - -

    ocamlc is aware of .c files and knows how to handle them. Unfortunately, - it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked - in C++ mode, you must:

    - -
    -
    -% cp example_wrap.cxx example_wrap.cxx.c
    % ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
    % ...
    -
    + +

    ocamlc is aware of .c files and knows how to handle them. Unfortunately, +it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked +in C++ mode, you must:

    + +
    +
    +% cp example_wrap.cxx example_wrap.cxx.c
    +% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
    +% ...
    +

    31.1.3 The camlp4 module

    @@ -165,8 +168,8 @@ the user more freedom with respect to custom typing. The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple rewriter which makes C++ code blend more seamlessly with objective caml code. Its use is optional, but encouraged. The source file is included in the Lib/ocaml -directory of the SWIG source distribution. You can checkout this file with -"swig -ocaml -co swigp4.ml". You should compile the file with +directory of the SWIG source distribution. You can checkout this file with +"swig -ocaml -co swigp4.ml". You should compile the file with "ocamlc -I `camlp4 -where` -pp 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"

    @@ -192,7 +195,7 @@ a '+= b (invoke object) "+=" argument as in
    (invoke a) "+=" b -Note that because camlp4 always recognizes << +Note that because camlp4 always recognizes << and >>, they are replaced by lsl and lsr in operator names. 'unop object as in
    @@ -241,11 +244,11 @@ let b = C_string (getenv "PATH") You can test-drive your module by building a toplevel ocaml interpreter. Consult the ocaml manual for details.

    - +

    When linking any ocaml bytecode with your module, use the -custom - option to build your functions into the primitive list. This - option is not needed when you build native code. +option to build your functions into the primitive list. This +option is not needed when you build native code.

    31.1.5 Compilation problems and compiling with C++

    @@ -273,9 +276,9 @@ In the code as seen by the typemap writer, there is a value, swig_result, that always contains the current return data. It is a list, and must be appended with the caml_list_append function, or with functions and macros provided by -objective caml.
    +objective caml.

    - +
     type c_obj =
         C_void
    @@ -299,66 +302,65 @@ type c_obj =
     

    - A few functions exist which generate and return these: +A few functions exist which generate and return these:

    - +
      -
    • caml_ptr_val receives a c_obj and returns a void *.  This - should be used for all pointer purposes.
    • -
    • caml_long_val receives a c_obj and returns a long.  This - should be used for most integral purposes.
      -
    • -
    • caml_val_ptr receives a void * and returns a c_obj.
    • -
    • caml_val_bool receives a C int and returns a c_obj representing - its bool value.
    • -
    • caml_val_(u)?(char|short|int|long|float|double) receives an -appropriate C value and returns a c_obj representing it.
    • -
    • caml_val_string receives a char * and returns a string value.
    • -
    • caml_val_string_len receives a char * and a length and returns - a string value.
    • -
    • caml_val_obj receives a void * and an object type and returns - a C_obj, which contains a closure giving method access.
    • - +
    • caml_ptr_val receives a c_obj and returns a void *. This + should be used for all pointer purposes.
    • +
    • caml_long_val receives a c_obj and returns a long. This + should be used for most integral purposes.
    • +
    • caml_val_ptr receives a void * and returns a c_obj.
    • +
    • caml_val_bool receives a C int and returns a c_obj representing + its bool value.
    • +
    • caml_val_(u)?(char|short|int|long|float|double) receives an + appropriate C value and returns a c_obj representing it.
    • +
    • caml_val_string receives a char * and returns a string value.
    • +
    • caml_val_string_len receives a char * and a length and returns + a string value.
    • +
    • caml_val_obj receives a void * and an object type and returns + a C_obj, which contains a closure giving method access.

    Because of this style, a typemap can return any kind of value it -wants from a function.  This enables out typemaps and inout typemaps -to work well.  The one thing to remember about outputting values -is that you must append them to the return list with swig_result = caml_list_append(swig_result,v). +wants from a function. This enables out typemaps and inout typemaps +to work well. The one thing to remember about outputting values +is that you must append them to the return list with swig_result = caml_list_append(swig_result,v).

    - This function will return a new list that has your element - appended. Upon return to caml space, the fnhelper function - beautifies the result. A list containing a single item degrades to - only that item (i.e. [ C_int 3 ] -> C_int 3), and a list - containing more than one item is wrapped in C_list (i.e. [ C_char - 'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b - ]).  This is in order to make return values easier to handle - when functions have only one return value, such as constructors, - and operators.  In addition, string, pointer, and object - values are interchangeable with respect to caml_ptr_val, so you can - allocate memory as caml strings and still use the resulting - pointers for C purposes, even using them to construct simple objects - on. Note, though, that foreign C++ code does not respect the garbage - collector, although the SWIG interface does.

    +This function will return a new list that has your element +appended. Upon return to caml space, the fnhelper function +beautifies the result. A list containing a single item degrades to +only that item (i.e. [ C_int 3 ] -> C_int 3), and a list +containing more than one item is wrapped in C_list (i.e. [ C_char +'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b +]). This is in order to make return values easier to handle +when functions have only one return value, such as constructors, +and operators. In addition, string, pointer, and object +values are interchangeable with respect to caml_ptr_val, so you can +allocate memory as caml strings and still use the resulting +pointers for C purposes, even using them to construct simple objects +on. Note, though, that foreign C++ code does not respect the garbage +collector, although the SWIG interface does.

    -

    - The wild card type that you can use in lots of different ways is - C_obj. It allows you to wrap any type of thing you like as an - object using the same mechanism that the ocaml module - does.  When evaluated in caml_ptr_val, the returned value is - the result of a call to the object's "&" operator, taken as a pointer. -

    -

    - You should only construct values using objective caml, or using the - functions caml_val_* functions provided as static functions to a SWIG - ocaml module, as well as the caml_list_* functions. These functions - provide everything a typemap needs to produce values. In addition, - value items pass through directly, but you must make your own type - signature for a function that uses value in this way. -

    +

    +The wild card type that you can use in lots of different ways is +C_obj. It allows you to wrap any type of thing you like as an +object using the same mechanism that the ocaml module +does. When evaluated in caml_ptr_val, the returned value is +the result of a call to the object's "&" operator, taken as a pointer. +

    + +

    +You should only construct values using objective caml, or using the +functions caml_val_* functions provided as static functions to a SWIG +ocaml module, as well as the caml_list_* functions. These functions +provide everything a typemap needs to produce values. In addition, +value items pass through directly, but you must make your own type +signature for a function that uses value in this way. +

    31.2.1 The generated module

    @@ -376,7 +378,7 @@ that the keywords are not the same as the C++ ones. You can introduce extra code into the output wherever you like with SWIG. These are the places you can introduce code: - @@ -385,25 +387,25 @@ file. - +
    "header"This code is inserted near the beginning of the +
    "header"This code is inserted near the beginning of the C wrapper file, before any function definitions.
    "wrapper"This code is inserted in the function definition section.
    "mli"This code is inserted into the caml interface file. Special signatures should be inserted here.
    "ml"This code is inserted in the caml code defining the +
    "ml"This code is inserted in the caml code defining the interface to your C code. Special caml code, as well as any initialization which should run when the module is loaded may be inserted here. -
    "classtemplate"The "classtemplate" place is special because it describes the output SWIG will generate for class definitions.
    - +

    31.2.2 Enums

    SWIG will wrap enumerations as polymorphic variants in the output -Ocaml code, as above in C_enum.  In order to support all +Ocaml code, as above in C_enum. In order to support all C++-style uses of enums, the function int_to_enum and enum_to_int are provided for ocaml code to produce and consume these values as -integers.  Other than that, correct uses of enums will not have -a problem.  Since enum labels may overlap between enums, the +integers. Other than that, correct uses of enums will not have +a problem. Since enum labels may overlap between enums, the enum_to_int and int_to_enum functions take an enum type label as an argument. Example:

    @@ -416,9 +418,9 @@ enum c_enum_type { a = 1, b, c = 4, d = 8 }; enum c_enum_type { a = 1, b, c = 4, d = 8 };
    -

    +

    The output mli contains: -

    +

     type c_enum_type = [
    @@ -435,16 +437,16 @@ type c_enum_tag = [
     val int_to_enum c_enum_type -> int -> c_obj
     val enum_to_int c_enum_type -> c_obj -> c_obj
     
    -
    +

    - So it's possible to do this: +So it's possible to do this:

    -
    -
    +
    +
     bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
    -bash-2.05a$ ./enum_test_top 
    +bash-2.05a$ ./enum_test_top
             Objective Caml version 3.04
     
     # open Enum_test ;;
    @@ -455,7 +457,7 @@ val x : Enum_test.c_obj = C_enum `a
     # int_to_enum `c_enum_type 4 ;;
     - : Enum_test.c_obj = C_enum `c
     
    -
    +

    31.2.2.1 Enum typing in Ocaml

    @@ -485,7 +487,7 @@ distribution.

    By including "carray.i", you will get access to some macros that help you -create typemaps for array types fairly easily. +create typemaps for array types fairly easily.

    @@ -547,7 +549,7 @@ void printfloats( float *tab, int len ) { printf( "%f ", tab[i] ); } - printf( "\n" ); + printf( "\n" ); } %} @@ -577,25 +579,25 @@ void printfloats( float *tab, int len );

    C++ classes, along with structs and unions are represented by C_obj -(string -> c_obj -> c_obj) wrapped closures.  These objects +(string -> c_obj -> c_obj) wrapped closures. These objects contain a method list, and a type, which allow them to be used like C++ objects. When passed into typemaps that use pointers, they -degrade to pointers through their "&" method.  Every method +degrade to pointers through their "&" method. Every method an object has is represented as a string in the object's method table, -and each method table exists in memory only once.  In addition +and each method table exists in memory only once. In addition to any other operators an object might have, certain builtin ones are -provided by SWIG: (all of these take no arguments (C_void)) +provided by SWIG: (all of these take no arguments (C_void))

    - - @@ -603,8 +605,8 @@ have been wrapped by SWIG. indicated parent class. This is mainly used internally by the SWIG module, but may be useful to client programs.
    "~"Delete this object
    "&"Return an ordinary C_ptr value representing this +
    "&"Return an ordinary C_ptr value representing this object's address
    "sizeof"If enabled with ("sizeof"="1") on the module node, return the object's size in char.
    ":methods"Returns a list of strings containing the names of the methods this object contains
    ":classof"Returns the name of the class this object belongs +
    ":classof"Returns the name of the class this object belongs to.
    ":parents"Returns a list of all direct parent classes which have been wrapped by SWIG.
    "[member-variable]"Each member variable is wrapped as a -method with an optional parameter. -Called with one argument, the member variable is set to the value of the +method with an optional parameter. +Called with one argument, the member variable is set to the value of the argument. With zero arguments, the value is returned.
    @@ -652,12 +654,12 @@ Since there's a makefile in that directory, the example is easy to build.

    Here's a sample transcript of an interactive session using a string vector -after making a toplevel (make toplevel). This example uses the camlp4 +after making a toplevel (make toplevel). This example uses the camlp4 module.

    -bash-2.05a$ ./example_top 
    +bash-2.05a$ ./example_top
             Objective Caml version 3.06
     
             Camlp4 Parsing version 3.06
    @@ -685,14 +687,14 @@ C_list
     - : Example.c_obj = C_void
     # x '[1] ;;
     - : Example.c_obj = C_string "spam"
    -# for i = 0 to (x -> size() as int) - 1 do 
    -    print_endline ((x '[i to int]) as string) 
    +# for i = 0 to (x -> size() as int) - 1 do
    +    print_endline ((x '[i to int]) as string)
       done ;;
     foo
     bar
     baz
     - : unit = ()
    -# 
    +#
     

    31.2.4.2 C++ Class Example

    @@ -703,7 +705,7 @@ Here's a simple example using Trolltech's Qt Library:

    - +
    qt.i
    qt.i
     %module qt
     %{
    @@ -733,9 +735,9 @@ bash-2.05a$ QTPATH=/your/qt/path
     bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
     bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
     bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml
    -bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include  qt.i
    +bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i
     bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
    -bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c 
    +bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
     bash-2.05a$ ocamlc -c qt.mli
     bash-2.05a$ ocamlc -c qt.ml
     bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
    @@ -747,7 +749,7 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
     
     
     
    -bash-2.05a$ ./qt_top 
    +bash-2.05a$ ./qt_top
             Objective Caml version 3.06
     
             Camlp4 Parsing version 3.06
    @@ -767,7 +769,7 @@ val hello : Qt.c_obj = C_obj <fun>
     
     

    Assuming you have a working installation of QT, you will see a window -containing the string "hi" in a button. +containing the string "hi" in a button.

    31.2.5 Director Classes

    @@ -852,7 +854,7 @@ let triangle_class pts ob meth args = | _ -> (invoke ob) meth args ;; let triangle = - new_derived_object + new_derived_object new_shape (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) '() ;; @@ -896,7 +898,7 @@ The definition of the actual object triangle can be described this way:
     let triangle =
    -  new_derived_object 
    +  new_derived_object
         new_shape
         (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
         '()
    @@ -904,13 +906,13 @@ let triangle =
     
     

    The first argument to new_derived_object, new_shape is the method -which returns a shape instance. This function will be invoked with the +which returns a shape instance. This function will be invoked with the third argument will be appended to the argument list [ C_void ]. In the example, the actual argument list is sent as (C_list [ C_void ; C_void ]). The augmented constructor for a director class needs the first argument to determine whether it is being constructed as a derived object, or as an object of the indicated type only (in this case shape). The -Second argument is a closure that will be added to the final C_obj. +Second argument is a closure that will be added to the final C_obj.

    diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 46a8941c2..5f8437a6a 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -59,7 +59,7 @@ Also, there are a dozen or so examples in the Examples/octave directory, and hun

    -As of SWIG 3.0.3, the Octave module has been tested with Octave versions 3.2.4, 3.4.3, 3.6.4, and 3.8.1. +As of SWIG 3.0.7, the Octave module is regularly tested with Octave versions 3.2.4, 3.8.1, and 4.0.0. Use of older Octave versions is not recommended, as these versions are no longer tested with SWIG.

    diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 8dae4bbf0..57a2cd3ef 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -74,6 +74,7 @@
  • Simple pointers
  • Unbounded C Arrays
  • String handling +
  • Default arguments
  • Typemaps
      @@ -3382,6 +3383,18 @@ problems, for example: # error handling). SWIG 3.0.3 and later report an error for invalid preprocessor directives, so you may have to update existing interface files to delimit blocks of Python code correctly.

      +

      As an alternative to providing a block containing Python code, you can +include python code from a file. The code is inserted exactly as in the +file, so this avoids any issues with the SWIG preprocessor. It's a good +approach if you have a non-trivial chunk of Python code to insert. To +use this feature you specify a filename in double quotes, for example:

      + +
      +
      +%pythoncode "somecode.py"
      +
      +
      +

      Sometimes you may want to replace or modify the wrapper function that SWIG creates in the proxy .py file. The Python module in SWIG provides some features that enable you to do this. First, to @@ -3404,7 +3417,7 @@ def bar(*args): class Foo { public: int bar(int x); -} +};

  • @@ -3441,7 +3454,7 @@ proxy, just before the return statement. class Foo { public: int bar(int x); -} +};
    @@ -3470,7 +3483,7 @@ SWIG version 1.3.28 you can use the directive forms class Foo { public: int bar(int x); -} +};
    @@ -3500,7 +3513,7 @@ class Foo { public: int bar(int x); int bar(); -} +}; @@ -4147,6 +4160,106 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

    + +

    36.7.5 Default arguments

    + + +

    +C++ default argument code generation is documented in the main +Default arguments section. +There is also an optional Python specific feature that can be used called the python:cdefaultargs +feature flag. +By default, SWIG attempts to convert C++ default argument values +into Python values and generates code into the Python layer containing these values. +For example: +

    + +
    +
    +struct CDA {
    +  int fff(int a = 1, bool b = false);
    +};
    +
    +
    + +

    +From Python this can be called as follows: +

    + +
    +
    +>>> CDA().fff()        # C++ layer receives a=1 and b=false
    +>>> CDA().fff(2)       # C++ layer receives a=2 and b=false
    +>>> CDA().fff(3, True) # C++ layer receives a=3 and b=true
    +
    +
    + +

    +The default code generation in the Python layer is: +

    + +
    +
    +class CDA(object):
    +    ...
    +    def fff(self, a=1, b=False):
    +        return _default_args.CDA_fff(self, a, b)
    +
    +
    + +

    +Adding the feature: +

    + +
    +
    +%feature("python:cdefaultargs") CDA::fff;
    +struct CDA {
    +  int fff(int a = 1, bool b = false);
    +
    +
    + +

    +results in identical behaviour when called from Python, however, it results in different code generation: +

    + +
    +
    +class CDA(object):
    +    ...
    +    def fff(self, *args):
    +        return _default_args.CDA_fff(self, *args)
    +
    +
    + +

    +The default arguments are obtained in the C++ wrapper layer instead of the Python layer. +Some code generation modes are quite different, eg -builtin and -fastproxy, +and are unaffected by python:cdefaultargs as the default values are always obtained from the C++ layer. +

    + +

    +Note that not all default arguments can be converted into a Python equivalent. +When SWIG does not convert them, it will generate code to obtain them from the C++ layer as if +python:cdefaultargs was specified. +This will happen if just one argument cannot be converted into a Python equivalent. +This occurs typically when the argument is not fully numeric, such as int(1): +

    + +
    +
    +struct CDA {
    +  int fff(int a = int(1), bool b = false);
    +};
    +
    +
    + +

    +Compatibility Note: SWIG-3.0.6 introduced the python:cdefaultargs feature. +Versions of SWIG prior to this varied in their ability to convert C++ default values into +equivalent Python default argument values. +

    +

    36.8 Typemaps

    diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index 5de390eab..50e861b22 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -119,6 +119,23 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order

    +

    + If you are compiling code yourself (not using R itself), there are a few things to watch out for: +

    + +
      +
    • The output shared library name (to the left of the file extension) MUST match the module name, or alternatively, you can also set the -package NAME command line argument. See swig -r -help for more information +
    • If you do not set the output file name appropriately, you might see errors like +
      +
      +> fact(4)
      +Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :
      +  "R_swig_fact" not available for .Call() for package "example"
      +
      +
      +
    • Make sure the architecture of the shared library(x64 for instance), matches the architecture of the R program you want to load your shared library into +
    +

    37.3 Precompiling large R files

    diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 4c33aeab8..774e00b23 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -146,7 +146,8 @@ can be obtained by typing swig -help or swig -Idir Add a directory to the file include path -lfile Include a SWIG library file. -module name Set the name of the SWIG module --o outfile Name of output file +-o outfile Set name of C/C++ output file to <outfile> +-oh headfile Set name of C++ output header file for directors to <headfile> -outcurrentdir Set default output dir to current dir instead of input file's path -outdir dir Set language specific files output directory -pcreversion Display PCRE version information @@ -212,7 +213,7 @@ additional files depending on the target language. By default, an input file with the name file.i is transformed into a file file_wrap.c or file_wrap.cxx (depending on whether or not the -c++ option has been used). The name of the -output file can be changed using the -o option. In certain +output C/C++ file can be changed using the -o option. In certain cases, file suffixes are used by the compiler to determine the source language (C, C++, etc.). Therefore, you have to use the -o option to change the suffix of the SWIG-generated wrapper diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index eeca0291c..d138073d9 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -2101,13 +2101,13 @@ Therefore, earlier methods will shadow methods that appear later.

    -When wrapping an overloaded function, there is a chance that you will get an error message like this: +When wrapping an overloaded function, there is a chance that you will get a warning message like this:

    -example.i:3: Warning 467: Overloaded foo(int) not supported (no type checking
    -rule for 'int').
    +example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking rule - 
    +no precedence level in typecheck typemap for 'int').
     
    @@ -2116,7 +2116,8 @@ This error means that the target language module supports overloading, but for some reason there is no type-checking rule that can be used to generate a working dispatch function. The resulting behavior is then undefined. You should report this as a bug to the -SWIG bug tracking database. +SWIG bug tracking database +if this is due to one of the typemaps supplied with SWIG.

    diff --git a/Doc/Manual/Scilab.html b/Doc/Manual/Scilab.html index d0a1d5381..cb4a3af90 100644 --- a/Doc/Manual/Scilab.html +++ b/Doc/Manual/Scilab.html @@ -42,7 +42,7 @@

  • Null pointers
  • Structures -
  • C++ Classes +
  • C++ classes
  • C++ inheritance
  • Pointers, references, values, and arrays
  • C++ templates @@ -931,7 +931,7 @@ ans = -

    39.3.8 C++ Classes

    +

    39.3.8 C++ classes

    @@ -1365,7 +1365,7 @@ void throw_int() throw(int) { } void throw_stl_invalid_arg(int i) throw(std::invalid_argument) { - if (i &lt 0) + if (i < 0) throw std::invalid_argument("argument is negative."); } %} diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 057d355ec..4bf40c969 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

    SWIG-3.0 Documentation

    -Last update : SWIG-3.0.6 (in progress) +Last update : SWIG-3.0.7 (in progress)

    Sections

    diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index 040244d45..5f484531b 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -4429,7 +4429,7 @@ before arrays, and so forth.

    Using the above table as a guide, each target language defines a collection of "typecheck" typemaps. -The follow excerpt from the Python module illustrates this: +The following excerpt from the Python module illustrates this:

    @@ -4542,11 +4542,31 @@ Here is an example,

    The bottom line: If you are writing new typemaps and you are using overloaded methods, you will probably -have to write typecheck code or copy existing code. Since this is a relatively new SWIG feature, there are -few examples to work with. However, you might look at some of the existing library files likes 'typemaps.i' for -a guide. +have to write new typecheck code or copy and modify existing typecheck code.

    +

    +If you write a typecheck typemap and omit the precedence level, for example commenting it out as shown below: +

    + +
    +
    +%typemap(typecheck /*,precedence=SWIG_TYPECHECK_INTEGER*/) int {
    +   $1 = PyInt_Check($input) ? 1 : 0;
    +}
    +
    +
    + +

    +then the type is given a precedence higher than any other known precedence level and a warning is issued: +

    + +
    +
    +example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'int').
    +
    +
    +

    Notes:

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index fda162615..2336120d3 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -492,7 +492,7 @@ example.i(4) : Syntax error in input(1).
  • 464. Unsupported constant value.
  • 465. Unable to handle type type.
  • 466. Unsupported variable type type. -
  • 467. Overloaded declaration not supported (no type checking rule for 'type') +
  • 467. Overloaded declaration not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'type')
  • 468. No 'throw' typemap defined for exception type type
  • 469. No or improper directorin typemap defined for type
  • 470. Thread/reentrant unsafe wrapping, consider returning by value instead. diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index 0685242ba..d85737e52 100644 --- a/Doc/Manual/Windows.html +++ b/Doc/Manual/Windows.html @@ -293,9 +293,9 @@ Execute the steps in the order shown and don't use spaces in path names. In fact Start the MSYS command prompt and execute:
     cd /
    -tar -jxf msys-automake-1.8.2.tar.bz2 
    +tar -jxf msys-automake-1.8.2.tar.bz2
     tar -jxf msys-autoconf-2.59.tar.bz2
    -tar -zxf bison-2.0-MSYS.tar.gz   
    +tar -zxf bison-2.0-MSYS.tar.gz
     
  • @@ -388,6 +388,53 @@ Include it like you would any other interface file, for example: __declspec(dllexport) ULONG __stdcall foo(DWORD, __int32); +

    Note that if you follow Microsoft's recommendation of wrapping the +__declspec calls in a preprocessor definition, you will need to +make sure that the definition is included by SWIG as well, by either defining it +manually or via a header. For example, if you have specified the +preprocessor definition in a header named export_lib.h and include +other headers which depend on it, you should use the %include directive +to include the definition explicitly. For example, if you had a header file, +bar.h, which depended on export_lib.h, your SWIG definition +file might look like:

    + +
    +// bar.i
    +%module bar
    +%include <windows.i>
    +%include "export_lib.h"
    +%include "bar.h"
    +
    + +

    +where export_lib.h may contain: +

    + +
    +// export_lib.h
    +#define BAR_API __declspec(dllexport)
    +
    + +

    +and bar.h may look like: +

    + +
    +// bar.h
    +#include "export_lib.h"
    +BAR_API void bar_function(int, double);
    +
    + +

    +Using the preprocessor to remove BAR_API is a popular simpler solution: +

    + +
    +// bar.i
    +%module bar
    +#define BAR_API
    +%include "bar.h"
    +
    diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 6fccda22e..6ba9dac12 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -321,6 +321,9 @@ else SWIGPYTHON = $(SWIG) -python -py3 endif +PEP8 = @PEP8@ +PEP8_FLAGS = --ignore=E402,E501,E30,W291,W391 + # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- @@ -373,8 +376,10 @@ endif PY2TO3 = 2to3 `2to3 -l | grep -v -E "Available|import$$" | awk '{print "-f "$$0}'` python_run: $(PYSCRIPT) - export PYTHONPATH=".:$$PYTHONPATH"; \ - $(RUNTOOL) $(PYTHON) $(PYSCRIPT) $(RUNPIPE) +ifneq (,$(PEP8)) + $(PEP8) $(PEP8_FLAGS) $(PYSCRIPT) +endif + env PYTHONPATH=$$PWD $(RUNTOOL) $(PYTHON) $(PYSCRIPT) $(RUNPIPE) ifneq (,$(SRCDIR)) $(RUNME).py: $(SRCDIR)$(RUNME).py @@ -883,7 +888,7 @@ OCAMLFIND=@OCAMLFIND@ OCAMLMKTOP=@OCAMLMKTOP@ $(SWIGWHERE) NOLINK ?= false OCAMLPP= -pp "camlp4o ./swigp4.cmo" -OCAMLP4WHERE=`$(COMPILETOOL) camlp4 -where` +OCAMLP4WHERE=`$(COMPILETOOL) @CAMLP4@ -where` OCAMLCORE=\ rm -rf swig.mli swig.ml swigp4.ml && \ $(SWIG) -ocaml -co swig.mli 2>/dev/null && \ @@ -1345,6 +1350,8 @@ CSHARPCOMPILER = @CSHARPCOMPILER@ CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ CSHARPCFLAGS = @CSHARPCFLAGS@ +CSHARPFLAGS = +CSHARPOPTIONS = CSHARPSO = @CSHARPSO@ CSHARP_RUNME = $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$(RUNME).exe @@ -1377,7 +1384,7 @@ SRCDIR_CSHARPSRCS = endif csharp_compile: $(SRCDIR_SRCS) - $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPSRCS) $(SRCDIR_CSHARPSRCS) + $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPOPTIONS) $(CSHARPSRCS) $(SRCDIR_CSHARPSRCS) # ----------------------------------------------------------------- # Run CSharp example @@ -1710,7 +1717,7 @@ SCILAB_LIBPREFIX = lib scilab: $(SWIG) -scilab $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SCILAB_INC) $(INCLUDES) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SCILAB_INC) $(INCLUDES) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(IOBJS) $(OBJS) $(LIBS) -o $(SCILAB_LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- @@ -1719,7 +1726,7 @@ scilab: scilab_cpp: $(SWIG) -c++ -scilab $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SCILAB_INC) $(INCLUDES) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SCILAB_INC) $(INCLUDES) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(IOBJS) $(OBJS) $(LIBS) $(CPP_DLLIBS) -o $(SCILAB_LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1727,7 +1734,7 @@ scilab_cpp: # ----------------------------------------------------------------- scilab_run: - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(SCILAB) $(SCILAB_OPT) -f $(SRCDIR)$(RUNME).sci $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(SCILAB) $(SCILAB_OPT) -f $(SRCDIR)$(RUNME).sci $(RUNPIPE) # ----------------------------------------------------------------- # Scilab version @@ -1750,28 +1757,37 @@ scilab_clean: ##### Go ###### ################################################################## +# TODO: The Go make targets need simplifying to use configure time +# configuration or to use Make's ifeq rather than using lots of +# runtime shell code. The output will then be a lot less verbose. + GO = @GO@ GOGCC = @GOGCC@ +GCCGO = @GCCGO@ GO1 = @GO1@ GO12 = @GO12@ GO13 = @GO13@ +GO15 = @GO15@ GOC = @GOC@ GOOPT = @GOOPT@ +GCCGOOPT = @GCCGOOPT@ GOVERSIONOPTION = @GOVERSIONOPTION@ GOSWIGARG = `if $(GOGCC) ; then echo -gccgo; fi` -GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` `if $(GO13) ; then echo -pack ; fi` +GOCOMPILEARG = `if $(GO15); then echo tool compile; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` `if $(GO13) || $(GO15); then echo -pack ; fi` GOSRCS = $(INTERFACE:.i=.go) GOCSRCS = $(INTERFACE:.i=_gc.c) -GOLD = $(GOC:c=l) +GOLD = `if $(GO15); then echo link; else echo $(GOC:c=l); fi` GOTOOL = `if $(GO1) ; then echo go tool; fi` GOPACK = `if $(GO1) ; then echo go tool pack; else echo gopack; fi` -GOPACKAGE = $(INTERFACE:.i=.a) +GOPACKAGE = $(notdir $(INTERFACE:.i=.a)) -GOOBJEXT = $(GOC:c=) +GOPATHDIR = gopath/src/$(INTERFACE:.i=) + +GOOBJEXT = `if $(GO15); then echo o; else echo $(GOC:c=); fi` GOGCOBJS = $(GOSRCS:.go=.$(GOOBJEXT)) GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) @@ -1779,19 +1795,21 @@ GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) # Build a Go module (C) # ---------------------------------------------------------------- -go: $(SRCDIR_SRCS) +go_nocgo: $(SRCDIR_SRCS) $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - if $(GO12) || $(GO13) || $(GOGCC); then \ + if $(GO12) || $(GO13) || $(GO15) || $(GOGCC); then \ $(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ else \ $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) - if ! $(GOGCC) ; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c -I . $(GOSRCS); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS); \ $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ rm -f $(GOPACKAGE); \ - if $(GO13); then \ + if $(GO13) || $(GO15); then \ cp $(GOGCOBJS) $(GOPACKAGE); \ $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ elif $(GO12); then \ @@ -1801,12 +1819,54 @@ go: $(SRCDIR_SRCS) fi; \ fi if test -f $(SRCDIR)$(RUNME).go; then \ - $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ - elif $(GO12) || $(GO13); then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ else \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +go: $(SRCDIR_SRCS) + $(SWIG) -go -cgo $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + @mkdir gopath 2>/dev/null || true + @mkdir gopath/src 2>/dev/null || true + @mkdir gopath/src/$(INTERFACE:.i=) 2>/dev/null || true + rm -f $(GOPATHDIR)/* + cp $(ISRCS) $(GOPATHDIR)/ + if test -f $(IWRAP:.i=.h); then \ + cp $(IWRAP:.i=.h) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_SRCS)"; then \ + cp $(SRCDIR_SRCS) $(GOPATHDIR)/; \ + fi + cp $(GOSRCS) $(GOPATHDIR)/ + GOPATH=`pwd`/gopath; \ + export GOPATH; \ + CGO_CPPFLAGS="$(CPPFLAGS) $(INCLUDES) -I `cd $(SRCDIR) && pwd` -I `pwd`"; \ + export CGO_CPPFLAGS; \ + CGO_CFLAGS="$(CFLAGS)"; \ + export CGO_CFLAGS; \ + CGO_LDFLAGS="$(LDFLAGS) -lm"; \ + export CGO_LDFLAGS; \ + (cd $(GOPATHDIR)/ && $(COMPILETOOL) $(GO) build `if $(GOGCC); then echo -compiler=gccgo; fi` -o $(GOPACKAGE)) + cp $(GOPATHDIR)/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE) + if $(GOGCC); then \ + cp $(dir $(INTERFACE))/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE:.a=.gox); \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -c -g $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(dir $(INTERFACE))/$(GOPACKAGE); \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -o $(RUNME).$(GOOBJEXT) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ fi; \ fi @@ -1815,19 +1875,29 @@ go: $(SRCDIR_SRCS) # Build a Go module (C++) # ---------------------------------------------------------------- -go_cpp: $(SRCDIR_SRCS) +go_cpp_nocgo: $(SRCDIR_SRCS) $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - if $(GO12) || $(GO13) || $(GOGCC); then \ - $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + if $(GO12) || $(GO13) || $(GO15) || $(GOGCC); then \ + if test -n "$(SRCDIR_CXXSRCS)$(SRCDIR_SRCS)"; then \ + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_CXXSRCS) $(SRCDIR_SRCS) $(INCLUDES); \ + fi; \ + $(foreach f,$(ICXXSRCS), \ + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) -o $(addsuffix .@OBJEXT@,$(basename $f)) $f $(INCLUDES); \ + ) \ else \ $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} $(GOCSRCS); \ + $(foreach f,$(GOSRCS), \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . -o $(addsuffix .$(GOOBJEXT),$(basename $f)) $f \ + ); \ + $(foreach f,$(GOCSRCS), \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`} \ + -o $(addsuffix .$(GOOBJEXT),$(basename $f)) $f; \ + ) \ rm -f $(GOPACKAGE); \ - if $(GO13); then \ + if $(GO13) || $(GO15); then \ cp $(GOGCOBJS) $(GOPACKAGE); \ $(COMPILETOOL) $(GOPACK) r $(GOPACKAGE) $(GOCSRCS:.c=.$(GOOBJEXT)) $(OBJS) $(IOBJS); \ elif $(GO12); then \ @@ -1835,14 +1905,65 @@ go_cpp: $(SRCDIR_SRCS) else \ $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi; \ + else \ + $(foreach f,$(GOSRCS), \ + $(COMPILETOOL) $(GCCGO) -g -c -I . -o $(addsuffix .@OBJEXT@,$(basename $f)) $f \ + ); \ fi if test -f $(SRCDIR)$(RUNME).go; then \ - $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ - elif $(GO12) || $(GO13); then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ else \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + fi; \ + fi + +go_cpp: $(SRCDIR_SRCS) + $(SWIG) -go -c++ -cgo $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + @mkdir gopath 2>/dev/null || true + @mkdir gopath/src 2>/dev/null || true + @mkdir gopath/src/$(INTERFACE:.i=) 2>/dev/null || true + rm -f $(GOPATHDIR)/* + cp $(ICXXSRCS) $(GOPATHDIR)/ + if test -f $(IWRAP:.i=.h); then \ + cp $(IWRAP:.i=.h) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_CXXSRCS)"; then \ + cp $(SRCDIR_CXXSRCS) $(GOPATHDIR)/; \ + fi + if test -n "$(SRCDIR_SRCS)"; then \ + cp $(SRCDIR_SRCS) $(GOPATHDIR)/; \ + fi + cp $(GOSRCS) $(GOPATHDIR)/ + GOPATH=`pwd`/gopath; \ + export GOPATH; \ + CGO_CPPFLAGS="$(CPPFLAGS) $(INCLUDES) -I `cd $(SRCDIR) && pwd` -I `pwd`"; \ + export CGO_CPPFLAGS; \ + CGO_CFLAGS="$(CFLAGS)"; \ + export CGO_CFLAGS; \ + CGO_CXXFLAGS="$(CXXFLAGS)"; \ + export CGO_CXXFLAGS; \ + CGO_LDFLAGS="$(LDFLAGS) -lm"; \ + export CGO_LDFLAGS; \ + (cd $(GOPATHDIR) && $(COMPILETOOL) $(GO) build `if $(GOGCC); then echo -compiler=gccgo; fi` -o $(GOPACKAGE)) + cp $(GOPATHDIR)/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE) + if $(GOGCC); then \ + cp $(dir $(INTERFACE))/$(GOPACKAGE) $(dir $(INTERFACE))/$(GOPACKAGE:.a=.gox); \ + fi + if test -f $(SRCDIR)$(RUNME).go; then \ + if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -g -c $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GCCGO) -o $(RUNME) $(RUNME).@OBJEXT@ $(dir $(INTERFACE))/$(GOPACKAGE) -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -o $(RUNME).$(GOOBJEXT) $(SRCDIR)$(RUNME).go; \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS) $(LDFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $(RUNME) $(RUNME).$(GOOBJEXT); \ fi; \ fi @@ -1852,7 +1973,7 @@ go_cpp: $(SRCDIR_SRCS) # ----------------------------------------------------------------- go_run: - env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) ./$(RUNME) $(RUNPIPE) + env $(RUNTOOL) ./$(RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1866,7 +1987,8 @@ go_version: # ----------------------------------------------------------------- go_clean: - rm -f *_wrap* *_gc* .~* $(RUNME) $(GOSRCS) + rm -f *_wrap* *_gc* *.gox .~* $(RUNME) $(GOSRCS) + rm -rf gopath rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *.[568] *.a *@SO@ diff --git a/Examples/csharp/callback/example.i b/Examples/csharp/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/csharp/callback/example.i +++ b/Examples/csharp/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/d/callback/example.i b/Examples/d/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/d/callback/example.i +++ b/Examples/d/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/go/callback/example.i b/Examples/go/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/go/callback/example.i +++ b/Examples/go/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/go/multimap/example.i b/Examples/go/multimap/example.i index 8de6b0dc3..30a37d3bf 100644 --- a/Examples/go/multimap/example.i +++ b/Examples/go/multimap/example.i @@ -74,16 +74,21 @@ extern int count(char *bytes, int len, char c); %} /* Return the mutated string as a modified element in the array. */ -%typemap(argout) (char *str, int len) +%typemap(argout,fragment="AllocateString") (char *str, int len) %{ { _gostring_ *a; a = (_gostring_*) $input.array; - a[0] = _swig_makegostring($1, $2); + a[0] = Swig_AllocateString($1, $2); } %} +%typemap(goargout,fragment="CopyString") (char *str, int len) +%{ + $input[0] = swigCopyString($input[0]) +%} + %typemap(freearg) (char *str, int len) %{ free($1); diff --git a/Examples/guile/matrix/Makefile b/Examples/guile/matrix/Makefile index 53638c867..9e541c36f 100644 --- a/Examples/guile/matrix/Makefile +++ b/Examples/guile/matrix/Makefile @@ -1,7 +1,7 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig SRCS = matrix.c vector.c -TARGET = matrix +TARGET = my-guile INTERFACE = example.i check: build diff --git a/Examples/guile/matrix/README b/Examples/guile/matrix/README index db7395b70..496e81bf1 100644 --- a/Examples/guile/matrix/README +++ b/Examples/guile/matrix/README @@ -6,7 +6,7 @@ type the following : Alternatively, use the command-line: - ./matrix -e do-test -s runme.scm + ./my-guile -e do-test -s runme.scm Or, if your operating system is spiffy enough: diff --git a/Examples/guile/port/Makefile b/Examples/guile/port/Makefile index 95a3a479f..0274dbf9b 100644 --- a/Examples/guile/port/Makefile +++ b/Examples/guile/port/Makefile @@ -1,7 +1,7 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig SRCS = example.c -TARGET = port +TARGET = my-guile INTERFACE = example.i check: build diff --git a/Examples/guile/port/README b/Examples/guile/port/README index 784e39e5d..174d8767a 100644 --- a/Examples/guile/port/README +++ b/Examples/guile/port/README @@ -1,2 +1,2 @@ This example illustrates the translation from Scheme file ports to -temporary FILE streams. Read the source and run ./port -s runme.scm +temporary FILE streams. Read the source and run ./my-guile -s runme.scm diff --git a/Examples/java/callback/example.i b/Examples/java/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/java/callback/example.i +++ b/Examples/java/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/java/pointer/example.i b/Examples/java/pointer/example.i index 5b725cee6..ed1c2fcc3 100644 --- a/Examples/java/pointer/example.i +++ b/Examples/java/pointer/example.i @@ -24,5 +24,3 @@ extern void sub(int *INPUT, int *INPUT, int *OUTPUT); %apply int *OUTPUT { int *r }; extern int divide(int n, int d, int *r); - - diff --git a/Examples/octave/callback/example.i b/Examples/octave/callback/example.i index 50ef5096d..333127a9d 100644 --- a/Examples/octave/callback/example.i +++ b/Examples/octave/callback/example.i @@ -7,8 +7,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/perl5/callback/example.i b/Examples/perl5/callback/example.i index 5f9072e61..821a9e6b5 100644 --- a/Examples/perl5/callback/example.i +++ b/Examples/perl5/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/php/callback/example.i b/Examples/php/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/php/callback/example.i +++ b/Examples/php/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/python/callback/example.i b/Examples/python/callback/example.i index 90beda01a..cf61ef9d2 100644 --- a/Examples/python/callback/example.i +++ b/Examples/python/callback/example.i @@ -4,8 +4,6 @@ #include "example.h" %} -%include "std_string.i" - /* turn on director wrapping Callback */ %feature("director") Callback; diff --git a/Examples/python/callback/runme.py b/Examples/python/callback/runme.py index ddb668407..345a3eb6e 100644 --- a/Examples/python/callback/runme.py +++ b/Examples/python/callback/runme.py @@ -2,14 +2,16 @@ # This file illustrates the cross language polymorphism using directors. -import example +import example class PyCallback(example.Callback): - def __init__(self): - example.Callback.__init__(self) - def run(self): - print "PyCallback.run()" + + def __init__(self): + example.Callback.__init__(self) + + def run(self): + print "PyCallback.run()" # Create an Caller instance @@ -25,7 +27,7 @@ callback = example.Callback() callback.thisown = 0 caller.setCallback(callback) caller.call() -caller.delCallback(); +caller.delCallback() print print "Adding and calling a Python callback" @@ -53,4 +55,3 @@ caller.delCallback() print print "python exit" - diff --git a/Examples/python/class/runme.py b/Examples/python/class/runme.py index 8f4f27eb9..34d21505c 100644 --- a/Examples/python/class/runme.py +++ b/Examples/python/class/runme.py @@ -3,7 +3,7 @@ # This file illustrates the proxy class C++ interface generated # by SWIG. -import example +import example # ----- Object creation ----- @@ -15,7 +15,7 @@ print " Created square", s # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes,"shapes were created" +print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" # ----- Member data access ----- @@ -28,16 +28,16 @@ s.x = -10 s.y = 5 print "\nHere is their current position:" -print " Circle = (%f, %f)" % (c.x,c.y) -print " Square = (%f, %f)" % (s.x,s.y) +print " Circle = (%f, %f)" % (c.x, c.y) +print " Square = (%f, %f)" % (s.x, s.y) # ----- Call some methods ----- print "\nHere are some properties of the shapes:" -for o in [c,s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() +for o in [c, s]: + print " ", o + print " area = ", o.area() + print " perimeter = ", o.perimeter() # prevent o from holding a reference to the last object looked at o = None @@ -47,5 +47,5 @@ print "\nGuess I'll clean up now" del c del s -print example.cvar.Shape_nshapes,"shapes remain" +print example.cvar.Shape_nshapes, "shapes remain" print "Goodbye" diff --git a/Examples/python/constants/runme.py b/Examples/python/constants/runme.py index 8d25b878b..415d1adc4 100644 --- a/Examples/python/constants/runme.py +++ b/Examples/python/constants/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example print "ICONST =", example.ICONST, "(should be 42)" print "FCONST =", example.FCONST, "(should be 2.1828)" @@ -8,7 +8,7 @@ print "CCONST =", example.CCONST, "(should be 'x')" print "CCONST2 =", example.CCONST2, "(this should be on a new line)" print "SCONST =", example.SCONST, "(should be 'Hello World')" print "SCONST2 =", example.SCONST2, "(should be '\"Hello World\"')" -print "EXPR =", example.EXPR, "(should be 48.5484)" +print "EXPR =", example.EXPR, "(should be 48.5484)" print "iconst =", example.iconst, "(should be 37)" print "fconst =", example.fconst, "(should be 3.14)" @@ -21,7 +21,3 @@ try: print "FOO = ", example.FOO, "(Arg! This shouldn't print anything)" except AttributeError: print "FOO isn't defined (good)" - - - - diff --git a/Examples/python/contract/runme.py b/Examples/python/contract/runme.py index d484ae916..ce01e5a1d 100644 --- a/Examples/python/contract/runme.py +++ b/Examples/python/contract/runme.py @@ -1,13 +1,13 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Manipulate the Foo global variable @@ -19,12 +19,3 @@ example.cvar.Foo = 3.1415926 # See if the change took effect print "Foo = ", example.cvar.Foo - - - - - - - - - diff --git a/Examples/python/docstrings/runme.py b/Examples/python/docstrings/runme.py index b6c95e613..c25d291b6 100644 --- a/Examples/python/docstrings/runme.py +++ b/Examples/python/docstrings/runme.py @@ -1,6 +1,5 @@ # file: runme.py -import example +import example print "example.Foo.bar.__doc__ =", repr(example.Foo.bar.__doc__), "(Should be 'No comment')" - diff --git a/Examples/python/enum/runme.py b/Examples/python/enum/runme.py index 10c4a260d..def01b147 100644 --- a/Examples/python/enum/runme.py +++ b/Examples/python/enum/runme.py @@ -18,9 +18,9 @@ print " Foo_LUDICROUS =", example.Foo.LUDICROUS print "\nTesting use of enums with functions\n" example.enum_test(example.RED, example.Foo.IMPULSE) -example.enum_test(example.BLUE, example.Foo.WARP) +example.enum_test(example.BLUE, example.Foo.WARP) example.enum_test(example.GREEN, example.Foo.LUDICROUS) -example.enum_test(1234,5678) +example.enum_test(1234, 5678) print "\nTesting use of enum with class method" f = example.Foo() @@ -28,4 +28,3 @@ f = example.Foo() f.enum_test(example.Foo.IMPULSE) f.enum_test(example.Foo.WARP) f.enum_test(example.Foo.LUDICROUS) - diff --git a/Examples/python/exception/runme.py b/Examples/python/exception/runme.py index 9e9241194..7fae49030 100644 --- a/Examples/python/exception/runme.py +++ b/Examples/python/exception/runme.py @@ -6,38 +6,37 @@ import example t = example.Test() try: - t.unknown() -except RuntimeError,e: - print "incomplete type", e.args[0] + t.unknown() +except RuntimeError, e: + print "incomplete type", e.args[0] try: - t.simple() -except RuntimeError,e: - print e.args[0] + t.simple() +except RuntimeError, e: + print e.args[0] try: - t.message() -except RuntimeError,e: - print e.args[0] + t.message() +except RuntimeError, e: + print e.args[0] if not example.is_python_builtin(): - try: + try: t.hosed() - except example.Exc,e: + except example.Exc, e: print e.code, e.msg else: - try: + try: t.hosed() - except BaseException,e: - # Throwing builtin classes as exceptions not supported (-builtin option) + except BaseException, e: + # Throwing builtin classes as exceptions not supported (-builtin + # option) print e -for i in range(1,4): - try: - t.multi(i) - except RuntimeError,e: - print e.args[0] - except example.Exc,e: - print e.code, e.msg - - +for i in range(1, 4): + try: + t.multi(i) + except RuntimeError, e: + print e.args[0] + except example.Exc, e: + print e.code, e.msg diff --git a/Examples/python/exceptproxy/runme.py b/Examples/python/exceptproxy/runme.py index 07e4b0a7f..970d6201d 100644 --- a/Examples/python/exceptproxy/runme.py +++ b/Examples/python/exceptproxy/runme.py @@ -2,8 +2,8 @@ import example if example.is_python_builtin(): - print "Skipping example: -builtin option does not support %exceptionclass" - exit(0) + print "Skipping example: -builtin option does not support %exceptionclass" + exit(0) q = example.intQueue(10) @@ -12,18 +12,18 @@ print "Inserting items into intQueue" print type(example.FullError) try: - for i in range(0,100): - q.enqueue(i) -except example.FullError,e: - print "Maxsize is", e.maxsize + for i in range(0, 100): + q.enqueue(i) +except example.FullError, e: + print "Maxsize is", e.maxsize print "Removing items" try: - while 1: - q.dequeue() -except example.EmptyError,e: - pass + while 1: + q.dequeue() +except example.EmptyError, e: + pass q = example.doubleQueue(1000) @@ -31,21 +31,15 @@ q = example.doubleQueue(1000) print "Inserting items into doubleQueue" try: - for i in range(0,10000): - q.enqueue(i*1.5) -except example.FullError,e: - print "Maxsize is", e.maxsize + for i in range(0, 10000): + q.enqueue(i * 1.5) +except example.FullError, e: + print "Maxsize is", e.maxsize print "Removing items" try: - while 1: - q.dequeue() -except example.EmptyError,e: - pass - - - - - - + while 1: + q.dequeue() +except example.EmptyError, e: + pass diff --git a/Examples/python/extend/runme.py b/Examples/python/extend/runme.py index 240b09894..2bb38fadc 100644 --- a/Examples/python/extend/runme.py +++ b/Examples/python/extend/runme.py @@ -2,16 +2,18 @@ # This file illustrates the cross language polymorphism using directors. -import example +import example # CEO class, which overrides Employee::getPosition(). class CEO(example.Manager): - def __init__(self, name): - example.Manager.__init__(self, name) - def getPosition(self): - return "CEO" + + def __init__(self, name): + example.Manager.__init__(self, name) + + def getPosition(self): + return "CEO" # Create an instance of our employee extension class, CEO. The calls to @@ -78,4 +80,3 @@ print "----------------------" # All done. print "python exit" - diff --git a/Examples/python/funcptr/runme.py b/Examples/python/funcptr/runme.py index bce065057..bf0c6e1ac 100644 --- a/Examples/python/funcptr/runme.py +++ b/Examples/python/funcptr/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example a = 37 b = 42 @@ -10,9 +10,9 @@ b = 42 print "Trying some C callback functions" print " a =", a print " b =", b -print " ADD(a,b) =", example.do_op(a,b,example.ADD) -print " SUB(a,b) =", example.do_op(a,b,example.SUB) -print " MUL(a,b) =", example.do_op(a,b,example.MUL) +print " ADD(a,b) =", example.do_op(a, b, example.ADD) +print " SUB(a,b) =", example.do_op(a, b, example.SUB) +print " MUL(a,b) =", example.do_op(a, b, example.MUL) print "Here is what the C callback function objects look like in Python" print " ADD =", example.ADD diff --git a/Examples/python/funcptr2/runme.py b/Examples/python/funcptr2/runme.py index bd58fb620..a4405d9d9 100644 --- a/Examples/python/funcptr2/runme.py +++ b/Examples/python/funcptr2/runme.py @@ -1,6 +1,6 @@ # file: runme.py -import example +import example a = 37 b = 42 @@ -10,9 +10,9 @@ b = 42 print "Trying some C callback functions" print " a =", a print " b =", b -print " ADD(a,b) =", example.do_op(a,b,example.ADD) -print " SUB(a,b) =", example.do_op(a,b,example.SUB) -print " MUL(a,b) =", example.do_op(a,b,example.MUL) +print " ADD(a,b) =", example.do_op(a, b, example.ADD) +print " SUB(a,b) =", example.do_op(a, b, example.SUB) +print " MUL(a,b) =", example.do_op(a, b, example.MUL) print "Here is what the C callback function objects look like in Python" print " ADD =", example.ADD @@ -20,5 +20,5 @@ print " SUB =", example.SUB print " MUL =", example.MUL print "Call the functions directly..." -print " add(a,b) =", example.add(a,b) -print " sub(a,b) =", example.sub(a,b) +print " add(a,b) =", example.add(a, b) +print " sub(a,b) =", example.sub(a, b) diff --git a/Examples/python/functor/runme.py b/Examples/python/functor/runme.py index 8fc0f2ff2..7f6f2b649 100644 --- a/Examples/python/functor/runme.py +++ b/Examples/python/functor/runme.py @@ -8,10 +8,9 @@ b = example.doubleSum(100.0) # Use the objects. They should be callable just like a normal # python function. -for i in range(0,100): +for i in range(0, 100): a(i) # Note: function call b(math.sqrt(i)) # Note: function call print a.result() print b.result() - diff --git a/Examples/python/import/runme.py b/Examples/python/import/runme.py index 6b800ecb8..0e83acad0 100644 --- a/Examples/python/import/runme.py +++ b/Examples/python/import/runme.py @@ -81,31 +81,27 @@ x = d.toBase() print " Spam -> Base -> Foo : ", y = foo.Foo_fromBase(x) if y: - print "bad swig" + print "bad swig" else: - print "good swig" + print "good swig" print " Spam -> Base -> Bar : ", y = bar.Bar_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" - + print "bad swig" + print " Spam -> Base -> Spam : ", y = spam.Spam_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" + print "bad swig" print " Foo -> Spam : ", y = spam.Spam_fromBase(b) if y: - print "bad swig" + print "bad swig" else: - print "good swig" - - - - + print "good swig" diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile index dfd46d05c..34362f65a 100644 --- a/Examples/python/import_packages/Makefile +++ b/Examples/python/import_packages/Makefile @@ -2,7 +2,6 @@ TOP = ../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = import_packages_subdirs = \ same_modnames1 \ diff --git a/Examples/python/import_packages/from_init1/Makefile b/Examples/python/import_packages/from_init1/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/from_init1/Makefile +++ b/Examples/python/import_packages/from_init1/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/from_init1/runme.py b/Examples/python/import_packages/from_init1/runme.py index bbe092bab..dda397487 100644 --- a/Examples/python/import_packages/from_init1/runme.py +++ b/Examples/python/import_packages/from_init1/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" -if sys.version_info < (3,0): - import py2.pkg2 - print " Finished importing py2.pkg2" +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" else: - import py3.pkg2 - print " Finished importing py3.pkg2" + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init2/Makefile b/Examples/python/import_packages/from_init2/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/from_init2/Makefile +++ b/Examples/python/import_packages/from_init2/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/from_init2/runme.py b/Examples/python/import_packages/from_init2/runme.py index bbe092bab..dda397487 100644 --- a/Examples/python/import_packages/from_init2/runme.py +++ b/Examples/python/import_packages/from_init2/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" -if sys.version_info < (3,0): - import py2.pkg2 - print " Finished importing py2.pkg2" +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" else: - import py3.pkg2 - print " Finished importing py3.pkg2" + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/from_init3/Makefile b/Examples/python/import_packages/from_init3/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/from_init3/Makefile +++ b/Examples/python/import_packages/from_init3/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/from_init3/runme.py b/Examples/python/import_packages/from_init3/runme.py index bbe092bab..dda397487 100644 --- a/Examples/python/import_packages/from_init3/runme.py +++ b/Examples/python/import_packages/from_init3/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" -if sys.version_info < (3,0): - import py2.pkg2 - print " Finished importing py2.pkg2" +if sys.version_info < (3, 0): + import py2.pkg2 + print " Finished importing py2.pkg2" else: - import py3.pkg2 - print " Finished importing py3.pkg2" + import py3.pkg2 + print " Finished importing py3.pkg2" diff --git a/Examples/python/import_packages/relativeimport1/Makefile b/Examples/python/import_packages/relativeimport1/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/relativeimport1/Makefile +++ b/Examples/python/import_packages/relativeimport1/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/relativeimport1/runme.py b/Examples/python/import_packages/relativeimport1/runme.py index 99b6e513e..997476b1d 100644 --- a/Examples/python/import_packages/relativeimport1/runme.py +++ b/Examples/python/import_packages/relativeimport1/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) with -relativeimport" -if sys.version_info < (3,0): - import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" else: - import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport2/Makefile b/Examples/python/import_packages/relativeimport2/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/relativeimport2/Makefile +++ b/Examples/python/import_packages/relativeimport2/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/relativeimport2/runme.py b/Examples/python/import_packages/relativeimport2/runme.py index f0ab6c446..9789afc18 100644 --- a/Examples/python/import_packages/relativeimport2/runme.py +++ b/Examples/python/import_packages/relativeimport2/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" -if sys.version_info < (3,0): - import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" else: - import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/relativeimport3/Makefile b/Examples/python/import_packages/relativeimport3/Makefile index b9d803a0e..dd38f90bd 100644 --- a/Examples/python/import_packages/relativeimport3/Makefile +++ b/Examples/python/import_packages/relativeimport3/Makefile @@ -2,7 +2,6 @@ TOP = ../../.. SWIG = $(realpath $(TOP)/../preinst-swig) SWIGOPT = LIBS = -PY3 = ifeq (,$(PY3)) PKG1DIR = "py2" diff --git a/Examples/python/import_packages/relativeimport3/runme.py b/Examples/python/import_packages/relativeimport3/runme.py index 99b6e513e..997476b1d 100644 --- a/Examples/python/import_packages/relativeimport3/runme.py +++ b/Examples/python/import_packages/relativeimport3/runme.py @@ -5,9 +5,9 @@ import os.path testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) with -relativeimport" -if sys.version_info < (3,0): - import py2.pkg2.bar - print " Finished importing py2.pkg2.bar" +if sys.version_info < (3, 0): + import py2.pkg2.bar + print " Finished importing py2.pkg2.bar" else: - import py3.pkg2.bar - print " Finished importing py3.pkg2.bar" + import py3.pkg2.bar + print " Finished importing py3.pkg2.bar" diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py index 7bec1ec1e..2107597b3 100644 --- a/Examples/python/import_packages/same_modnames1/runme.py +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -9,5 +9,5 @@ print " Finished importing pkg2.foo" var2 = pkg2.foo.Pkg2_Foo() if str(type(var2)).find("'pkg2.foo.Pkg2_Foo'") == -1: - raise RuntimeError("failed type checking: " + str(type(var2))) + raise RuntimeError("failed type checking: " + str(type(var2))) print " Successfully created object pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py index eec6121eb..41ff1afec 100644 --- a/Examples/python/import_packages/same_modnames2/runme.py +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -6,7 +6,7 @@ print "Testing " + testname + " - %module(package=...) + python 'import' in __in import pkg1.pkg2.foo print " Finished importing pkg1.pkg2.foo" -var2 = pkg1.pkg2.foo.Pkg2_Foo(); +var2 = pkg1.pkg2.foo.Pkg2_Foo() if str(type(var2)).find("'pkg1.pkg2.foo.Pkg2_Foo'") == -1: - raise RuntimeError("failed type checking: " + str(type(var2))) + raise RuntimeError("failed type checking: " + str(type(var2))) print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" diff --git a/Examples/python/import_template/runme.py b/Examples/python/import_template/runme.py index 0d5aded14..35f8924c1 100644 --- a/Examples/python/import_template/runme.py +++ b/Examples/python/import_template/runme.py @@ -81,31 +81,27 @@ x = d.toBase() print " Spam -> Base -> Foo : ", y = foo.intFoo_fromBase(x) if y: - print "bad swig" + print "bad swig" else: - print "good swig" + print "good swig" print " Spam -> Base -> Bar : ", y = bar.intBar_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" - + print "bad swig" + print " Spam -> Base -> Spam : ", y = spam.intSpam_fromBase(x) if y: - print "good swig" + print "good swig" else: - print "bad swig" + print "bad swig" print " Foo -> Spam : ", y = spam.intSpam_fromBase(b) if y: - print "bad swig" + print "bad swig" else: - print "good swig" - - - - + print "good swig" diff --git a/Examples/python/java/runme.py b/Examples/python/java/runme.py index 0cec8a7cb..641ba27dd 100644 --- a/Examples/python/java/runme.py +++ b/Examples/python/java/runme.py @@ -6,11 +6,11 @@ JvAttachCurrentThread(None, None) e1 = Example(1) e2 = Example(2) -print e1.Add(1,2) -print e1.Add(1.0,2.0) -e3 = e1.Add(e1,e2) +print e1.Add(1, 2) +print e1.Add(1.0, 2.0) +e3 = e1.Add(e1, e2) print e3.mPublicInt -print e1.Add("1","2") +print e1.Add("1", "2") JvDetachCurrentThread() diff --git a/Examples/python/multimap/example.i b/Examples/python/multimap/example.i index cc2482cc8..635f61c13 100644 --- a/Examples/python/multimap/example.i +++ b/Examples/python/multimap/example.i @@ -20,7 +20,7 @@ extern int gcd(int x, int y); if (!PyList_Check($input)) { SWIG_exception(SWIG_ValueError, "Expecting a list"); } - $1 = PyList_Size($input); + $1 = (int)PyList_Size($input); if ($1 == 0) { SWIG_exception(SWIG_ValueError, "List must contain at least 1 element"); } @@ -73,7 +73,7 @@ extern int gcdmain(int argc, char *argv[]); } utf8str = PyUnicode_AsUTF8String($input); PyBytes_AsStringAndSize(utf8str, &cstr, &len); - $1 = strndup(cstr, (size_t)len); + $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); $2 = (int)len; Py_DECREF(utf8str); %#else @@ -82,7 +82,7 @@ extern int gcdmain(int argc, char *argv[]); return NULL; } $1 = PyString_AsString($input); - $2 = PyString_Size($input); + $2 = (int)PyString_Size($input); %#endif } @@ -106,11 +106,11 @@ extern int count(char *bytes, int len, char c); Py_ssize_t len; PyObject *utf8str = PyUnicode_AsUTF8String($input); PyBytes_AsStringAndSize(utf8str, &cstr, &len); - $1 = strndup(cstr, (size_t)len); + $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); $2 = (int)len; Py_DECREF(utf8str); %#else - $2 = PyString_Size($input); + $2 = (int)PyString_Size($input); $1 = (char *) malloc($2+1); memmove($1,PyString_AsString($input),$2); %#endif diff --git a/Examples/python/multimap/runme.py b/Examples/python/multimap/runme.py index f996ab3ae..ad693b73a 100644 --- a/Examples/python/multimap/runme.py +++ b/Examples/python/multimap/runme.py @@ -1,16 +1,16 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Call the gcdmain() function -example.gcdmain(["gcdmain","42","105"]) +example.gcdmain(["gcdmain", "42", "105"]) # Call the count function print example.count("Hello World", "l") @@ -18,10 +18,3 @@ print example.count("Hello World", "l") # Call the capitalize function print example.capitalize("hello world") - - - - - - - diff --git a/Examples/python/operator/runme.py b/Examples/python/operator/runme.py index 3687a38de..ac48f2676 100644 --- a/Examples/python/operator/runme.py +++ b/Examples/python/operator/runme.py @@ -1,21 +1,20 @@ # Operator overloading example import example -a = example.Complex(2,3) -b = example.Complex(-5,10) +a = example.Complex(2, 3) +b = example.Complex(-5, 10) -print "a =",a -print "b =",b +print "a =", a +print "b =", b c = a + b -print "c =",c -print "a*b =",a*b -print "a-c =",a-c +print "c =", c +print "a*b =", a * b +print "a-c =", a - c -e = example.ComplexCopy(a-c) -print "e =",e +e = example.ComplexCopy(a - c) +print "e =", e # Big expression -f = ((a+b)*(c+b*e)) + (-a) -print "f =",f - +f = ((a + b) * (c + b * e)) + (-a) +print "f =", f diff --git a/Examples/python/performance/constructor/runme.py b/Examples/python/performance/constructor/runme.py index 274cbf85e..1771fba7b 100644 --- a/Examples/python/performance/constructor/runme.py +++ b/Examples/python/performance/constructor/runme.py @@ -2,8 +2,9 @@ import sys sys.path.append('..') import harness -def proc (mod) : - for i in range(1000000) : + +def proc(mod): + for i in range(1000000): x = mod.MyClass() harness.run(proc) diff --git a/Examples/python/performance/func/runme.py b/Examples/python/performance/func/runme.py index f9032b9d2..760a8ab6d 100644 --- a/Examples/python/performance/func/runme.py +++ b/Examples/python/performance/func/runme.py @@ -2,9 +2,10 @@ import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.MyClass() - for i in range(10000000) : + for i in range(10000000): x.func() harness.run(proc) diff --git a/Examples/python/performance/harness.py b/Examples/python/performance/harness.py index 00f48e66a..c3d38b4fb 100644 --- a/Examples/python/performance/harness.py +++ b/Examples/python/performance/harness.py @@ -3,9 +3,10 @@ import time import imp from subprocess import * -def run (proc) : - try : +def run(proc): + + try: mod = imp.find_module(sys.argv[1]) mod = imp.load_module(sys.argv[1], *mod) @@ -14,15 +15,18 @@ def run (proc) : t2 = time.clock() print "%s took %f seconds" % (mod.__name__, t2 - t1) - except IndexError : - proc = Popen([sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE) + except IndexError: + proc = Popen( + [sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout - proc = Popen([sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE) + proc = Popen( + [sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout - proc = Popen([sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE) + proc = Popen( + [sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout diff --git a/Examples/python/performance/hierarchy/runme.py b/Examples/python/performance/hierarchy/runme.py index 9b22586a1..8255cdc86 100644 --- a/Examples/python/performance/hierarchy/runme.py +++ b/Examples/python/performance/hierarchy/runme.py @@ -2,9 +2,10 @@ import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.H() - for i in range(10000000) : + for i in range(10000000): x.func() harness.run(proc) diff --git a/Examples/python/performance/hierarchy_operator/runme.py b/Examples/python/performance/hierarchy_operator/runme.py index 5a8c52557..eabfae864 100644 --- a/Examples/python/performance/hierarchy_operator/runme.py +++ b/Examples/python/performance/hierarchy_operator/runme.py @@ -2,9 +2,10 @@ import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.H() - for i in range(10000000) : + for i in range(10000000): x += i harness.run(proc) diff --git a/Examples/python/performance/operator/runme.py b/Examples/python/performance/operator/runme.py index 4a6031f48..d75ae404c 100644 --- a/Examples/python/performance/operator/runme.py +++ b/Examples/python/performance/operator/runme.py @@ -2,9 +2,10 @@ import sys sys.path.append('..') import harness -def proc (mod) : + +def proc(mod): x = mod.MyClass() - for i in range(10000000) : + for i in range(10000000): x = x + i harness.run(proc) diff --git a/Examples/python/pointer/runme.py b/Examples/python/pointer/runme.py index e38a306c1..5b5f16bc2 100644 --- a/Examples/python/pointer/runme.py +++ b/Examples/python/pointer/runme.py @@ -1,25 +1,25 @@ # file: runme.py -import example; +import example # First create some objects using the pointer library. -print "Testing the pointer library"; -a = example.new_intp(); -b = example.new_intp(); -c = example.new_intp(); -example.intp_assign(a,37); -example.intp_assign(b,42); +print "Testing the pointer library" +a = example.new_intp() +b = example.new_intp() +c = example.new_intp() +example.intp_assign(a, 37) +example.intp_assign(b, 42) -print " a =",a -print " b =",b -print " c =",c +print " a =", a +print " b =", b +print " c =", c # Call the add() function with some pointers -example.add(a,b,c) +example.add(a, b, c) # Now get the result r = example.intp_value(c) -print " 37 + 42 =",r +print " 37 + 42 =", r # Clean up the pointers example.delete_intp(a) @@ -30,15 +30,12 @@ example.delete_intp(c) # This should be much easier. Now how it is no longer # necessary to manufacture pointers. -print "Trying the typemap library"; -r = example.sub(37,42) -print " 37 - 42 =",r +print "Trying the typemap library" +r = example.sub(37, 42) +print " 37 - 42 =", r # Now try the version with multiple return values -print "Testing multiple return values"; -q,r = example.divide(42,37) -print " 42/37 = %d remainder %d" % (q,r) - - - +print "Testing multiple return values" +q, r = example.divide(42, 37) +print " 42/37 = %d remainder %d" % (q, r) diff --git a/Examples/python/reference/runme.py b/Examples/python/reference/runme.py index a1f53368e..0ff217b02 100644 --- a/Examples/python/reference/runme.py +++ b/Examples/python/reference/runme.py @@ -7,22 +7,22 @@ import example # ----- Object creation ----- print "Creating some objects:" -a = example.Vector(3,4,5) -b = example.Vector(10,11,12) +a = example.Vector(3, 4, 5) +b = example.Vector(10, 11, 12) -print " Created",a.cprint() -print " Created",b.cprint() +print " Created", a.cprint() +print " Created", b.cprint() # ----- Call an overloaded operator ----- # This calls the wrapper we placed around # -# operator+(const Vector &a, const Vector &) +# operator+(const Vector &a, const Vector &) # # It returns a new allocated object. print "Adding a+b" -c = example.addv(a,b) +c = example.addv(a, b) print " a+b =", c.cprint() # Note: Unless we free the result, a memory leak will occur @@ -33,25 +33,25 @@ del c # Note: Using the high-level interface here print "Creating an array of vectors" va = example.VectorArray(10) -print " va = ",va +print " va = ", va # ----- Set some values in the array ----- # These operators copy the value of $a and $b to the vector array -va.set(0,a) -va.set(1,b) +va.set(0, a) +va.set(1, b) -va.set(2,example.addv(a,b)) +va.set(2, example.addv(a, b)) # Get some values from the array print "Getting some array values" -for i in range(0,5): +for i in range(0, 5): print " va(%d) = %s" % (i, va.get(i).cprint()) # Watch under resource meter to check on this print "Making sure we don't leak memory." -for i in xrange(0,1000000): +for i in xrange(0, 1000000): c = va.get(i % 10) # ----- Clean up ----- @@ -60,4 +60,3 @@ print "Cleaning up" del va del a del b - diff --git a/Examples/python/simple/runme.py b/Examples/python/simple/runme.py index d484ae916..ce01e5a1d 100644 --- a/Examples/python/simple/runme.py +++ b/Examples/python/simple/runme.py @@ -1,13 +1,13 @@ # file: runme.py -import example +import example # Call our gcd() function x = 42 y = 105 -g = example.gcd(x,y) -print "The gcd of %d and %d is %d" % (x,y,g) +g = example.gcd(x, y) +print "The gcd of %d and %d is %d" % (x, y, g) # Manipulate the Foo global variable @@ -19,12 +19,3 @@ example.cvar.Foo = 3.1415926 # See if the change took effect print "Foo = ", example.cvar.Foo - - - - - - - - - diff --git a/Examples/python/smartptr/runme.py b/Examples/python/smartptr/runme.py index 5ea1fb947..5f8b73476 100644 --- a/Examples/python/smartptr/runme.py +++ b/Examples/python/smartptr/runme.py @@ -3,7 +3,7 @@ # This file illustrates the proxy class C++ interface generated # by SWIG. -import example +import example # ----- Object creation ----- @@ -17,7 +17,7 @@ print " Created square", s # ----- Access a static member ----- -print "\nA total of", example.cvar.Shape_nshapes,"shapes were created" +print "\nA total of", example.cvar.Shape_nshapes, "shapes were created" # ----- Member data access ----- @@ -30,16 +30,16 @@ s.x = -10 s.y = 5 print "\nHere is their current position:" -print " Circle = (%f, %f)" % (c.x,c.y) -print " Square = (%f, %f)" % (s.x,s.y) +print " Circle = (%f, %f)" % (c.x, c.y) +print " Square = (%f, %f)" % (s.x, s.y) # ----- Call some methods ----- print "\nHere are some properties of the shapes:" -for o in [c,s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() +for o in [c, s]: + print " ", o + print " area = ", o.area() + print " perimeter = ", o.perimeter() print "\nGuess I'll clean up now" @@ -50,6 +50,5 @@ del cc del ss s = 3 -print example.cvar.Shape_nshapes,"shapes remain" +print example.cvar.Shape_nshapes, "shapes remain" print "Goodbye" - diff --git a/Examples/python/std_map/runme.py b/Examples/python/std_map/runme.py index b521c9c9c..26031f3f4 100644 --- a/Examples/python/std_map/runme.py +++ b/Examples/python/std_map/runme.py @@ -7,8 +7,6 @@ pmap["hi"] = 1 pmap["hello"] = 2 - - dmap = {} dmap["hello"] = 1.0 dmap["hi"] = 2.0 @@ -28,8 +26,8 @@ for i in dmap.iterkeys(): for i in dmap.itervalues(): print "val", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v dmap = example.DoubleMap() dmap["hello"] = 1.0 @@ -41,8 +39,8 @@ for i in dmap.iterkeys(): for i in dmap.itervalues(): print "val", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v print dmap.items() @@ -54,7 +52,6 @@ print hmap.keys() print hmap.values() - dmap = {} dmap["hello"] = 2 dmap["hi"] = 4 @@ -76,7 +73,7 @@ for i in dmap.itervalues(): for i in dmap.iteritems(): print "item", i -for k,v in dmap.iteritems(): - print "item", k,v +for k, v in dmap.iteritems(): + print "item", k, v print dmap diff --git a/Examples/python/std_vector/runme.py b/Examples/python/std_vector/runme.py index d248ccbbb..d7d3c2ea4 100644 --- a/Examples/python/std_vector/runme.py +++ b/Examples/python/std_vector/runme.py @@ -4,13 +4,13 @@ import example # Call average with a Python list... -print example.average([1,2,3,4]) +print example.average([1, 2, 3, 4]) # ... or a wrapped std::vector v = example.IntVector(4) for i in range(len(v)): - v[i] = i+1 + v[i] = i + 1 print example.average(v) @@ -22,8 +22,8 @@ print example.half((1.0, 1.5, 2.0, 2.5, 3.0)) # ... or a wrapped std::vector v = example.DoubleVector() -for i in [1,2,3,4]: - v.append(i) +for i in [1, 2, 3, 4]: + v.append(i) print example.half(v) @@ -31,6 +31,5 @@ print example.half(v) example.halve_in_place(v) for i in range(len(v)): - print v[i], "; ", + print v[i], "; ", print - diff --git a/Examples/python/template/runme.py b/Examples/python/template/runme.py index 05940bc67..e408e15f9 100644 --- a/Examples/python/template/runme.py +++ b/Examples/python/template/runme.py @@ -3,32 +3,30 @@ import example # Call some templated functions -print example.maxint(3,7) -print example.maxdouble(3.14,2.18) +print example.maxint(3, 7) +print example.maxdouble(3.14, 2.18) # Create some class iv = example.vecint(100) dv = example.vecdouble(1000) -for i in range(0,100): - iv.setitem(i,2*i) +for i in range(0, 100): + iv.setitem(i, 2 * i) -for i in range(0,1000): - dv.setitem(i, 1.0/(i+1)) +for i in range(0, 1000): + dv.setitem(i, 1.0 / (i + 1)) sum = 0 -for i in range(0,100): - sum = sum + iv.getitem(i) +for i in range(0, 100): + sum = sum + iv.getitem(i) print sum sum = 0.0 -for i in range(0,1000): - sum = sum + dv.getitem(i) +for i in range(0, 1000): + sum = sum + dv.getitem(i) print sum del iv del dv - - diff --git a/Examples/python/varargs/runme.py b/Examples/python/varargs/runme.py index 8eab77041..48e3134f3 100644 --- a/Examples/python/varargs/runme.py +++ b/Examples/python/varargs/runme.py @@ -1,13 +1,13 @@ # file: runme.py import sys -import example +import example # Call printf example.printf("Hello World. I'm printf\n") # Note: We call printf, but use *python* string formatting -for i in range(0,10): +for i in range(0, 10): example.printf("i is %d\n" % i) # This will probably be garbled because %d is interpreted by C @@ -15,21 +15,13 @@ example.printf("The value is %d\n") stdout = example.stdout_stream() # Call fprintf -example.fprintf(stdout,"Hello World. I'm fprintf\n") -for i in range(0,10): - example.fprintf(stdout,"i is %d\n" % i) +example.fprintf(stdout, "Hello World. I'm fprintf\n") +for i in range(0, 10): + example.fprintf(stdout, "i is %d\n" % i) # This won't be garbled since %d is not interpreted -example.fprintf(stdout,"The value is %d\n") +example.fprintf(stdout, "The value is %d\n") # This function calls our NULL-terminated function -example.printv("Hello","World","this","is","a","test.") - - - - - - - - +example.printv("Hello", "World", "this", "is", "a", "test.") diff --git a/Examples/python/variables/runme.py b/Examples/python/variables/runme.py index b635b9859..3388a0eba 100644 --- a/Examples/python/variables/runme.py +++ b/Examples/python/variables/runme.py @@ -4,21 +4,21 @@ import example # Try to set the values of some global variables -example.cvar.ivar = 42 -example.cvar.svar = -31000 -example.cvar.lvar = 65537 -example.cvar.uivar = 123456 -example.cvar.usvar = 61000 -example.cvar.ulvar = 654321 -example.cvar.scvar = -13 -example.cvar.ucvar = 251 -example.cvar.cvar = "S" -example.cvar.fvar = 3.14159 -example.cvar.dvar = 2.1828 -example.cvar.strvar = "Hello World" -example.cvar.iptrvar= example.new_int(37) -example.cvar.ptptr = example.new_Point(37,42) -example.cvar.name = "Bill" +example.cvar.ivar = 42 +example.cvar.svar = -31000 +example.cvar.lvar = 65537 +example.cvar.uivar = 123456 +example.cvar.usvar = 61000 +example.cvar.ulvar = 654321 +example.cvar.scvar = -13 +example.cvar.ucvar = 251 +example.cvar.cvar = "S" +example.cvar.fvar = 3.14159 +example.cvar.dvar = 2.1828 +example.cvar.strvar = "Hello World" +example.cvar.iptrvar = example.new_int(37) +example.cvar.ptptr = example.new_Point(37, 42) +example.cvar.name = "Bill" # Now print out the values of the variables @@ -46,16 +46,16 @@ print "\nVariables (values printed from C)" example.print_vars() -print "\nNow I'm going to try and modify some read only variables"; +print "\nNow I'm going to try and modify some read only variables" -print " Tring to set 'path'"; +print " Tring to set 'path'" try: example.cvar.path = "Whoa!" print "Hey, what's going on?!?! This shouldn't work" except: print "Good." -print " Trying to set 'status'"; +print " Trying to set 'status'" try: example.cvar.status = 0 print "Hey, what's going on?!?! This shouldn't work" @@ -70,6 +70,3 @@ example.cvar.pt = example.cvar.ptptr print "The new value is" example.pt_print() print "You should see the value", example.Point_print(example.cvar.ptptr) - - - diff --git a/Examples/test-suite/array_typedef_memberin.i b/Examples/test-suite/array_typedef_memberin.i index d9f768ed8..3618c9305 100644 --- a/Examples/test-suite/array_typedef_memberin.i +++ b/Examples/test-suite/array_typedef_memberin.i @@ -13,13 +13,8 @@ namespace ArrayExample { public: Eight node_list; -#ifndef _MSC_VER const Eight node_list2; ConstEight node_list3; -#else - Eight node_list2; - Eight node_list3; -#endif void fn1(Eight a) {} void fn2(const Eight a) {} @@ -32,6 +27,8 @@ namespace ArrayExample void fn7(Eight*& a) {} void fn8(ConstEight*& a) {} void fn9(const ConstEight*& a) {} + + ExampleDetail() : node_list(), node_list2(), node_list3() {} }; } diff --git a/Examples/test-suite/chartest.i b/Examples/test-suite/chartest.i new file mode 100644 index 000000000..e81cf54a4 --- /dev/null +++ b/Examples/test-suite/chartest.i @@ -0,0 +1,15 @@ +%module chartest + +%inline %{ +char printable_global_char = 'a'; +char unprintable_global_char = 0x7F; + +char GetPrintableChar() { + return 'a'; +} + +char GetUnprintableChar() { + return 0x7F; +} + +%} diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 87b66f47a..ac726ef05 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -138,6 +138,7 @@ CPP_TEST_CASES += \ casts \ char_binary \ char_strings \ + chartest \ class_forward \ class_ignore \ class_scope_weird \ @@ -156,6 +157,7 @@ CPP_TEST_CASES += \ conversion \ conversion_namespace \ conversion_ns_template \ + conversion_operators \ cplusplus_throw \ cpp_basic \ cpp_enum \ @@ -198,6 +200,7 @@ CPP_TEST_CASES += \ director_protected \ director_protected_overloaded \ director_redefined \ + director_ref \ director_smartptr \ director_thread \ director_unroll \ @@ -233,6 +236,7 @@ CPP_TEST_CASES += \ features \ fragments \ friends \ + friends_template \ funcptr_cpp \ fvirtual \ global_namespace \ @@ -243,6 +247,7 @@ CPP_TEST_CASES += \ ignore_parameter \ import_nomodule \ inherit \ + inherit_member \ inherit_missing \ inherit_same_name \ inherit_target_language \ @@ -407,6 +412,7 @@ CPP_TEST_CASES += \ template_inherit \ template_inherit_abstract \ template_int_const \ + template_keyword_in_type \ template_methods \ template_namespace_forward_declaration \ template_using_directive_and_declaration_forward \ @@ -540,6 +546,7 @@ CPP11_TEST_CASES = \ cpp11_template_explicit \ cpp11_template_typedefs \ cpp11_type_traits \ + cpp11_type_aliasing \ cpp11_uniform_initialization \ cpp11_unrestricted_unions \ cpp11_userdefined_literals \ diff --git a/Examples/test-suite/conversion_operators.i b/Examples/test-suite/conversion_operators.i new file mode 100644 index 000000000..fa9e52cac --- /dev/null +++ b/Examples/test-suite/conversion_operators.i @@ -0,0 +1,55 @@ +%module conversion_operators + +// Test bug #401 where the conversion operator name incorrectly included the newline character +// Also test comments around conversion operators due to special handling in the scanner for conversion operators + +// These one line ignores should match the conversion operator names to suppress Warning 503 - SWIGWARN_LANG_IDENTIFIER +%ignore operator const EcReal; +%ignore operator EcImaginary const; +%ignore operator EcComplex const; + +%inline %{ + +struct EcReal {}; +struct EcImaginary {}; +struct EcComplex {}; + +struct EcAngle { + operator const EcReal + ( + ) const; + operator EcImaginary +const ( + ) const; + operator +EcComplex + const ( + ) const; +}; + +struct EcAngle2 { + operator const EcReal/* C comment */ + ( + ) const; + operator EcImaginary/* C comment */ +const ( + ) const; + operator/* C comment */ +EcComplex + const ( + ) const; +}; + +struct EcAngle3 { + operator const EcReal // C++ comment + ( + ) const; + operator EcImaginary // C++ comment +const ( + ) const; + operator // C++ comment +EcComplex + const ( + ) const; +}; +%} diff --git a/Examples/test-suite/cpp11_lambda_functions.i b/Examples/test-suite/cpp11_lambda_functions.i index 87c7196d8..161e08c65 100644 --- a/Examples/test-suite/cpp11_lambda_functions.i +++ b/Examples/test-suite/cpp11_lambda_functions.i @@ -100,9 +100,6 @@ int runLambdaInline() { %{ // TODO -struct LambdaStruct { - static constexpr auto lambda_struct1 = [=]() { return thing; }; -}; int(*lambda101notauto)(int, int) = [] (int a, int b) { return a + b; }; int lambda102 = [] (int a, int b) mutable { return a + b; }(1, 2); void lambda_init(int = ([=]{ return 0; })()); diff --git a/Examples/test-suite/cpp11_noexcept.i b/Examples/test-suite/cpp11_noexcept.i index 6fed5b8df..ef96fd8a7 100644 --- a/Examples/test-suite/cpp11_noexcept.i +++ b/Examples/test-suite/cpp11_noexcept.i @@ -13,7 +13,7 @@ struct NoExceptClass { NoExceptClass() noexcept {} NoExceptClass(const NoExceptClass&) noexcept {} NoExceptClass(NoExceptClass&&) noexcept {} - NoExceptClass& operator=(const NoExceptClass&) noexcept {} + NoExceptClass& operator=(const NoExceptClass&) noexcept { return *this; } ~NoExceptClass() noexcept {} void noex0() noexcept {} diff --git a/Examples/test-suite/cpp11_rvalue_reference2.i b/Examples/test-suite/cpp11_rvalue_reference2.i index 4ef871c63..6718a3941 100644 --- a/Examples/test-suite/cpp11_rvalue_reference2.i +++ b/Examples/test-suite/cpp11_rvalue_reference2.i @@ -31,14 +31,17 @@ struct Thingy { // test both primitive and user defined rvalue reference default arguments and compactdefaultargs void compactDefaultArgs(const bool &&b = (const bool &&)PublicGlobalTrue, const UserDef &&u = (const UserDef &&)PublicUserDef) {} void privateDefaultArgs(const bool &&b = (const bool &&)PrivateTrue) {} - operator int &&() {} + operator int &&() { return std::move(0); } + Thingy(const Thingy& rhs) : val(rhs.val), lvalref(rhs.lvalref), rvalref(copy_int(rhs.rvalref)) {} Thingy& operator=(const Thingy& rhs) { val = rhs.val; lvalref = rhs.lvalref; rvalref = rhs.rvalref; + return *this; } private: static const bool PrivateTrue; + int copy_int(int& i) { return i; } Thingy(); }; const bool Thingy::PrivateTrue = true; diff --git a/Examples/test-suite/cpp11_template_typedefs.i b/Examples/test-suite/cpp11_template_typedefs.i index d6a1a3c85..97a1da7ed 100644 --- a/Examples/test-suite/cpp11_template_typedefs.i +++ b/Examples/test-suite/cpp11_template_typedefs.i @@ -2,8 +2,14 @@ %module cpp11_template_typedefs %warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefName; +%warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) TypedefNamePtr; %warnfilter(SWIGWARN_CPP11_ALIAS_TEMPLATE) MyIntKeyClass; %warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) PF; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) BucketAllocator1; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) BucketAllocator2; + +// This warning should go away when type aliasing is supported +#pragma SWIG nowarn=SWIGWARN_PARSE_USING_UNDEF // Nothing known about 'p.SomeType< char *,T2,4 >'. %inline %{ template< typename T1, typename T2, int > @@ -16,6 +22,8 @@ class SomeType { // template aliasing template< typename T2 > using TypedefName = SomeType; +template< typename T2 > +using TypedefNamePtr = SomeType*; // type aliasing typedef void (*PFD)(double); // Old style @@ -28,5 +36,21 @@ class MyCPP11Class { }; template using MyIntKeyClass = MyCPP11Class; MyIntKeyClass intchar; + +TypedefName alias1(TypedefName a) { return a; } +TypedefNamePtr alias1(TypedefNamePtr a = nullptr) { return a; } %} +%inline %{ +typedef double Val; +template struct ListBucket { +}; +namespace Alloc { + template struct rebind { + typedef int other; + }; +} + +using BucketAllocator1 = typename Alloc::template rebind>::other; +using BucketAllocator2 = typename Alloc::template rebind<::template ListBucket>::other; +%} diff --git a/Examples/test-suite/cpp11_type_aliasing.i b/Examples/test-suite/cpp11_type_aliasing.i new file mode 100644 index 000000000..87443633a --- /dev/null +++ b/Examples/test-suite/cpp11_type_aliasing.i @@ -0,0 +1,66 @@ +%module cpp11_type_aliasing + +// Type aliasing seg fault : Github issue #424 + +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) Target; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) Int; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntRef; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntPtrRef; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntRValueRef; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) IntArray; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) HalideTargetPtr1; +%warnfilter(SWIGWARN_CPP11_ALIAS_DECLARATION) HalideTargetPtr2; + +%inline %{ +namespace Halide { + +struct Target { + int bits; + Target(int bits=32) : bits(bits) {} +}; + +class NamesInterface { +public: + using Target = Halide::Target; +}; + +Target get_host_target() { + return Target(); +} + +namespace Internal { + +template class GeneratorParam { + T value; +public: + GeneratorParam(const char *name, const T &v) : value(v) {} + + T getValue() { + return value; + } +}; + +class GeneratorBase : public NamesInterface { +public: + GeneratorParam target{ "target", Halide::get_host_target() }; +}; + +} +} +%} + +%template(Halide_Target) Halide::Internal::GeneratorParam; + + +%inline %{ +using Int = int; +using IntRef = int&; +using IntPtrRef = int*&; +using IntRValueRef = int&&; +using IntArray = int[]; + +using HalideTargetPtr1 = Halide::Target*; +namespace Halide { + using HalideTargetPtr2 = Target*; +} +%} diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index 292c751e4..d5eac5c03 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -6,8 +6,7 @@ LANGUAGE = csharp SCRIPTSUFFIX = _runme.cs CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ -CSHARPPATHSEPARATOR = "@CSHARPPATHSEPARATOR@" -CSHARPCYGPATH_W = @CSHARPCYGPATH_W@ +CSHARPCONVERTPATH = @top_srcdir@/@CSHARPCONVERTPATH@ srcdir = @srcdir@ top_srcdir = ../@top_srcdir@ @@ -79,13 +78,13 @@ run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ $(MAKE) -f $*/$(top_builddir)/$(EXAMPLES)/Makefile \ CSHARPFLAGS='-nologo -debug+ $(CSHARPFLAGSSPECIAL) -out:$*_runme.exe' \ - CSHARPSRCS='`$(CSHARPCYGPATH_W) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX)` `find $* -name "*.cs" -exec $(CSHARPCYGPATH_W) "{}" \+`' csharp_compile && \ + CSHARPSRCS='`$(CSHARPCONVERTPATH) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX)` `find $* -name "*.cs" -exec $(CSHARPCONVERTPATH) "{}" \+`' csharp_compile && \ env LD_LIBRARY_PATH="$*:$$LD_LIBRARY_PATH" PATH="$*:$$PATH" SHLIB_PATH="$*:$$SHLIB_PATH" DYLD_FALLBACK_LIBRARY_PATH= $(RUNTOOL) $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$*_runme.exe; \ else \ cd $* && \ $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \ CSHARPFLAGS='-nologo -debug+ $(CSHARPFLAGSSPECIAL) -t:module -out:$*.netmodule' \ - CSHARPSRCS='`find . -name "*.cs" -exec $(CSHARPCYGPATH_W) "{}" \+`' csharp_compile; \ + CSHARPSRCS='`find . -name "*.cs" -exec ../$(CSHARPCONVERTPATH) "{}" \+`' csharp_compile; \ fi # Clean: remove testcase directories diff --git a/Examples/test-suite/csharp/default_constructor_runme.cs b/Examples/test-suite/csharp/default_constructor_runme.cs index acd62dc3d..9fc8d754b 100644 --- a/Examples/test-suite/csharp/default_constructor_runme.cs +++ b/Examples/test-suite/csharp/default_constructor_runme.cs @@ -12,13 +12,5 @@ public class runme throw new Exception("Protected destructor exception should have been thrown"); } catch (MethodAccessException) { } - - // calling private destructor test - try { - using (FFF f = new FFF()) { - } - throw new Exception("Private destructor exception should have been thrown"); - } catch (MethodAccessException) { - } } } diff --git a/Examples/test-suite/csharp/li_boost_shared_ptr_bits_runme.cs b/Examples/test-suite/csharp/li_boost_shared_ptr_bits_runme.cs index b4ec47f02..38f71f978 100644 --- a/Examples/test-suite/csharp/li_boost_shared_ptr_bits_runme.cs +++ b/Examples/test-suite/csharp/li_boost_shared_ptr_bits_runme.cs @@ -16,5 +16,12 @@ public class runme HiddenDestructor hidden = HiddenDestructor.create(); hidden.Dispose(); + + HiddenPrivateDestructor hiddenPrivate = HiddenPrivateDestructor.create(); + if (HiddenPrivateDestructor.DeleteCount != 0) + throw new ApplicationException("Count should be zero"); + hiddenPrivate.Dispose(); + if (HiddenPrivateDestructor.DeleteCount != 1) + throw new ApplicationException("Count should be one"); } } diff --git a/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs b/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs index 625542751..445c4d74b 100644 --- a/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs +++ b/Examples/test-suite/csharp/li_boost_shared_ptr_runme.cs @@ -46,7 +46,7 @@ public class runme } int actualCount = Klass.getTotal_count(); if (actualCount != expectedCount) - throw new ApplicationException("Expected count: " + expectedCount + " Actual count: " + actualCount); + Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't } int wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count(); diff --git a/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs b/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs index 387d50400..1f66042a6 100644 --- a/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs +++ b/Examples/test-suite/csharp/li_std_auto_ptr_runme.cs @@ -32,7 +32,7 @@ public class li_std_auto_ptr_runme { }; int actualCount = Klass.getTotal_count(); if (actualCount != expectedCount) - throw new ApplicationException("Expected count: " + expectedCount + " Actual count: " + actualCount); + Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't } if (k2.getLabel() != "second") @@ -51,7 +51,7 @@ public class li_std_auto_ptr_runme { } int actualCount = Klass.getTotal_count(); if (actualCount != expectedCount) - throw new ApplicationException("Expected count: " + expectedCount + " Actual count: " + actualCount); + Console.Error.WriteLine("Expected count: " + expectedCount + " Actual count: " + actualCount); // Finalizers are not guaranteed to be run and sometimes they just don't } } } diff --git a/Examples/test-suite/d/default_constructor_runme.1.d b/Examples/test-suite/d/default_constructor_runme.1.d index 3640218ae..bd79cdf99 100644 --- a/Examples/test-suite/d/default_constructor_runme.1.d +++ b/Examples/test-suite/d/default_constructor_runme.1.d @@ -1,6 +1,5 @@ module default_constructor_runme; -import default_constructor.FFF; import default_constructor.G; void main() { @@ -15,16 +14,4 @@ void main() { throw e; } } - - // Private destructor test. - try { - { - scope f = new FFF(); - } - throw new Exception("Private destructor exception should have been thrown"); - } catch (Exception e) { - if (e.msg != "C++ destructor does not have public access") { - throw e; - } - } } diff --git a/Examples/test-suite/d/default_constructor_runme.2.d b/Examples/test-suite/d/default_constructor_runme.2.d index 22f5bffd2..991b4186a 100644 --- a/Examples/test-suite/d/default_constructor_runme.2.d +++ b/Examples/test-suite/d/default_constructor_runme.2.d @@ -1,6 +1,5 @@ module default_constructor_runme; -import default_constructor.FFF; import default_constructor.G; void main() { @@ -8,7 +7,6 @@ void main() { // destruction yet. // enforceThrows((){ scope g = new G(); }, "Protected destructor exception should have been thrown"); - // enforceThrows((){ scope f = new FFF(); }, "Private destructor exception should have been thrown"); } private void enforceThrows(void delegate() dg, string errorMessage) { diff --git a/Examples/test-suite/default_arg_values.i b/Examples/test-suite/default_arg_values.i index 47ca2d12f..f2fc57c9b 100644 --- a/Examples/test-suite/default_arg_values.i +++ b/Examples/test-suite/default_arg_values.i @@ -6,6 +6,12 @@ struct Display { // Bad Python wrappers were being generated when NULL used for primitive type float draw1(float v = 0) { return v; } float draw2(float *v = 0) { return v ? *v : 0; } + bool bool0(bool x = 0) { return x; } + bool bool1(bool x = 1) { return x; } + + typedef bool mybool; + bool mybool0(mybool x = 0) { return x; } + bool mybool1(mybool x = 1) { return x; } }; float* createPtr(float v) { static float val; val = v; return &val; } %} @@ -14,5 +20,11 @@ struct Display { // Bad Python wrappers were being generated when NULL used for primitive type float draw1(float v = NULL) { return v; } float draw2(float *v = NULL) { return v ? *v : 0; } + bool bool0(bool x = 0) { return x; } + bool bool1(bool x = 1) { return x; } + + typedef bool mybool; + bool mybool0(mybool x = 0) { return x; } + bool mybool1(mybool x = 1) { return x; } }; float* createPtr(float v) { static float val; val = v; return &val; } diff --git a/Examples/test-suite/default_args.i b/Examples/test-suite/default_args.i index bcb8766a8..d3014d386 100644 --- a/Examples/test-suite/default_args.i +++ b/Examples/test-suite/default_args.i @@ -114,7 +114,10 @@ %rename(renamed2arg) Foo::renameme(int x) const; %rename(renamed1arg) Foo::renameme() const; +%typemap(default) double* null_by_default "$1=0;"; + %inline %{ + typedef void* MyHandle; // Define a class class Foo { @@ -139,6 +142,12 @@ // test the method itself being renamed void oldname(int x = 1234) {} void renameme(int x = 1234, double d=123.4) const {} + + // test default values for pointer arguments + int double_if_void_ptr_is_null(int n, void* p = NULL) { return p ? n : 2*n; } + int double_if_handle_is_null(int n, MyHandle h = 0) { return h ? n : 2*n; } + int double_if_dbl_ptr_is_null(int n, double* null_by_default) + { return null_by_default ? n : 2*n; } }; int Foo::bar = 1; int Foo::spam = 2; @@ -269,3 +278,26 @@ struct ConstMethods { } Pointf; } %} + +// Default arguments after ignored ones. +%typemap(in, numinputs=0) int square_error { $1 = 2; }; +%typemap(default, noblock=1) int def17 { $1 = 17; }; + +// Enabling autodoc feature has a side effect of disabling the generation of +// aliases for functions that can hide problems with default arguments at +// Python level. +%feature("autodoc","0") slightly_off_square; + +%inline %{ + inline int slightly_off_square(int square_error, int def17) { return def17*def17 + square_error; } +%} + +// Python C default args +%feature("python:cdefaultargs") CDA::cdefaultargs_test1; +%inline %{ +struct CDA { + int cdefaultargs_test1(int a = 1) { return a; } + int cdefaultargs_test2(int a = 1) { return a; } +}; +%} + diff --git a/Examples/test-suite/default_constructor.i b/Examples/test-suite/default_constructor.i index f7fc8cfa6..74673b74a 100644 --- a/Examples/test-suite/default_constructor.i +++ b/Examples/test-suite/default_constructor.i @@ -13,6 +13,16 @@ SWIGWARN_D_MULTIPLE_INHERITANCE, SWIGWARN_PHP_MULTIPLE_INHERITANCE) AD; /* C#, D, Java, PHP multiple inheritance */ +%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE, + SWIGWARN_CSHARP_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE) GGG; /* C#, D, Java, PHP multiple inheritance */ + +%warnfilter(SWIGWARN_JAVA_MULTIPLE_INHERITANCE, + SWIGWARN_CSHARP_MULTIPLE_INHERITANCE, + SWIGWARN_D_MULTIPLE_INHERITANCE, + SWIGWARN_PHP_MULTIPLE_INHERITANCE) HHH; /* C#, D, Java, PHP multiple inheritance */ + %warnfilter(SWIGWARN_LANG_FRIEND_IGNORE) F; /* friend function */ %delobject F::destroy; @@ -103,14 +113,15 @@ public: void bar(F *) { } -#if defined(_MSC_VER) - #pragma warning(disable: 4624) // : destructor could not be generated because a base class destructor is inaccessible -#endif +// Single inheritance, base has private destructor class FFF : public F { }; -#if defined(_MSC_VER) - #pragma warning(default: 4624) // : destructor could not be generated because a base class destructor is inaccessible -#endif + +// Multiple inheritance, one base has private destructor +class GGG : public A, public F { +}; +class HHH : public F, public A { +}; /* A class with a protected destructor */ class G { diff --git a/Examples/test-suite/director_binary_string.i b/Examples/test-suite/director_binary_string.i index f842dc2c7..17bdc1b64 100644 --- a/Examples/test-suite/director_binary_string.i +++ b/Examples/test-suite/director_binary_string.i @@ -4,6 +4,7 @@ %apply (char *STRING, size_t LENGTH) { (char *dataBufferAA, int sizeAA) }; %apply (char *STRING, size_t LENGTH) { (char *dataBufferBB, int sizeBB) }; +%apply (char* STRING, size_t LENGTH) { (const void* data, size_t datalen) }; %inline %{ #include @@ -20,6 +21,7 @@ public: if (dataBufferBB) memset(dataBufferBB, -1, sizeBB); } + virtual void writeData(const void* data, size_t datalen) = 0; }; class Caller { @@ -50,6 +52,17 @@ public: void call_null() { _callback->run(NULL, 0, NULL, 0); } + int callWriteData() { + int sum = 0; + if (_callback) { + char* aa = (char*)malloc(BUFFER_SIZE_AA); + memset(aa, 9, BUFFER_SIZE_AA); + _callback->writeData(aa, BUFFER_SIZE_AA); + for (int i = 0; i < BUFFER_SIZE_AA; i++) + sum += aa[i]; + } + return sum; + } }; %} diff --git a/Examples/test-suite/director_ignore.i b/Examples/test-suite/director_ignore.i index 57cbc13d8..edb657320 100644 --- a/Examples/test-suite/director_ignore.i +++ b/Examples/test-suite/director_ignore.i @@ -10,6 +10,7 @@ %ignore OverloadedProtectedMethod(int n, int xoffset = 0, int yoffset = 0); %ignore DIgnoreConstructor(bool b); %ignore DIgnoreOnlyConstructor(bool b); +%ignore DIgnoreDestructor::~DIgnoreDestructor; %ignore Pointers; %ignore References; %ignore PublicMethod1; @@ -101,6 +102,13 @@ class DIgnoreOnlyConstructor DIgnoreOnlyConstructor(bool b) {} }; +class DIgnoreDestructor +{ + public: + DIgnoreDestructor() {} + virtual ~DIgnoreDestructor() {} +}; + %{ class DIgnoreConstructor { @@ -118,5 +126,12 @@ class DIgnoreOnlyConstructor private: // Hide constructor DIgnoreOnlyConstructor(bool b) {} }; -%} +class DIgnoreDestructor +{ + public: + DIgnoreDestructor() {} + virtual ~DIgnoreDestructor() {} +}; + +%} diff --git a/Examples/test-suite/director_ref.i b/Examples/test-suite/director_ref.i new file mode 100644 index 000000000..8bb8a9b63 --- /dev/null +++ b/Examples/test-suite/director_ref.i @@ -0,0 +1,82 @@ +%module(directors="1") director_ref + +%{ +#include + +class Foo { +public: + Foo(int i = -1) : count(0) {} + virtual void OnDelete() {} + virtual ~Foo() {} + virtual std::string Msg(std::string msg = "default") { return "Foo-" + msg; } + + std::string GetMsg() { return Msg(); } + std::string GetMsg(std::string msg) { return Msg(msg); } + + void Ref() { ++count; } + void Unref() { --count; if (count == 0) { OnDelete(); delete this; } } + int GetRefCount() { return count; } +private: + int count; +}; + +class FooPtr { +public: + FooPtr(Foo* f = NULL) : my_f(f) { if (my_f) { my_f->Ref(); } } + ~FooPtr() { if (my_f) { my_f->Unref(); } } + void Reset(Foo* f = NULL) { + if (f) { f->Ref(); } + if (my_f) { my_f->Unref(); } + my_f = f; + } + int GetOwnedRefCount() { + if (my_f) { return my_f->GetRefCount(); } + return 0; + } + +private: + Foo* my_f; +}; + +%} + +%include + +%feature("director") Foo; +%feature("ref") Foo "$this->Ref();" +%feature("unref") Foo "$this->Unref();" + +class Foo { +public: + Foo(int i = -1) : count(0) {} + virtual void OnDelete() {} + virtual ~Foo() {} + virtual std::string Msg(std::string msg = "default") { return "Foo-" + msg; } + + std::string GetMsg() { return Msg(); } + std::string GetMsg(std::string msg) { return Msg(msg); } + + void Ref() { ++count; } + void Unref() { --count; if (count == 0) { OnDelete(); delete this; } } + int GetRefCount() { return count; } +private: + int count; +}; + +class FooPtr { +public: + FooPtr(Foo* f = NULL) : my_f(f) { if (my_f) { my_f->Ref(); } } + ~FooPtr() { if (my_f) { my_f->Unref(); } } + void Reset(Foo* f = NULL) { + if (f) { f->Ref(); } + if (my_f) { my_f->Unref(); } + my_f = f; + } + int GetOwnedRefCount() { + if (my_f) { return my_f->GetRefCount(); } + return 0; + } + +private: + Foo* my_f; +}; diff --git a/Examples/test-suite/errors/cpp_macro_locator.i b/Examples/test-suite/errors/cpp_macro_locator.i index bd441a121..e00caf00d 100644 --- a/Examples/test-suite/errors/cpp_macro_locator.i +++ b/Examples/test-suite/errors/cpp_macro_locator.i @@ -100,4 +100,9 @@ void overloadinline2(const int *) {} void overload5(int *) {} void overload5(const int *) {} - +%ignore Outer2::QuietInner; +struct Outer2 { + struct QuietInner { + VARIABLEMACRO(MyInnerVar) + }; +}; diff --git a/Examples/test-suite/errors/cpp_template_friend.i b/Examples/test-suite/errors/cpp_template_friend.i new file mode 100644 index 000000000..c9d1c9d5d --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_friend.i @@ -0,0 +1,26 @@ +%module cpp_template_friend + +template T template_friend1(T); +template T template_friend1(T); +struct MyTemplate1 { + template friend T template_friend1(T); +}; + +template T template_friend2(T); +struct MyTemplate2 { + template friend T template_friend2(T); +}; +template T template_friend2(T); + + +int normal_friend1(int); +int normal_friend1(int); +struct MyClass1 { + friend int normal_friend1(int); +}; + +int normal_friend2(int); +struct MyClass2 { + friend int normal_friend2(int); +}; +int normal_friend2(int); diff --git a/Examples/test-suite/errors/cpp_template_friend.stderr b/Examples/test-suite/errors/cpp_template_friend.stderr new file mode 100644 index 000000000..8dea195dc --- /dev/null +++ b/Examples/test-suite/errors/cpp_template_friend.stderr @@ -0,0 +1,8 @@ +cpp_template_friend.i:4: Warning 302: Identifier 'template_friend1' redefined (ignored), +cpp_template_friend.i:3: Warning 302: previous definition of 'template_friend1'. +cpp_template_friend.i:13: Warning 302: Identifier 'template_friend2' redefined (ignored), +cpp_template_friend.i:9: Warning 302: previous definition of 'template_friend2'. +cpp_template_friend.i:17: Warning 322: Redundant redeclaration of 'normal_friend1', +cpp_template_friend.i:16: Warning 322: previous declaration of 'normal_friend1'. +cpp_template_friend.i:26: Warning 322: Redundant redeclaration of 'normal_friend2', +cpp_template_friend.i:22: Warning 322: previous declaration of 'normal_friend2'. diff --git a/Examples/test-suite/errors/cpp_using_type_aliasing.i b/Examples/test-suite/errors/cpp_using_type_aliasing.i new file mode 100644 index 000000000..df65dbd3d --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_type_aliasing.i @@ -0,0 +1,13 @@ +%module cpp_using_type_aliasing + +namespace Space { + template struct Okay { + }; + struct User { + protected: + using OkayInt = Okay; + }; + struct Derived : User { + Okay ff(); + }; +}; diff --git a/Examples/test-suite/errors/cpp_using_type_aliasing.stderr b/Examples/test-suite/errors/cpp_using_type_aliasing.stderr new file mode 100644 index 000000000..3f256652f --- /dev/null +++ b/Examples/test-suite/errors/cpp_using_type_aliasing.stderr @@ -0,0 +1,3 @@ +cpp_using_type_aliasing.i:8: Warning 341: The 'using' keyword in type aliasing is not fully supported yet. +cpp_using_type_aliasing.i:8: Warning 315: Nothing known about 'Okay< int >'. +cpp_using_type_aliasing.i:8: Warning 315: Nothing known about 'Okay< int >'. diff --git a/Examples/test-suite/errors/doxygen_unknown_command.stderr b/Examples/test-suite/errors/doxygen_unknown_command.stderr index 40055ee8b..1ac00d6b0 100644 --- a/Examples/test-suite/errors/doxygen_unknown_command.stderr +++ b/Examples/test-suite/errors/doxygen_unknown_command.stderr @@ -1 +1 @@ -doxygen_unknown_command.i:4: Warning 740: Doxygen parser warning: unknown command "unknown". +doxygen_unknown_command.i:4: Warning 760: Doxygen parser warning: unknown command "unknown". diff --git a/Examples/test-suite/errors/pp_unknowndirective.i b/Examples/test-suite/errors/pp_unknowndirective.i index 659a997d3..b4e608b34 100644 --- a/Examples/test-suite/errors/pp_unknowndirective.i +++ b/Examples/test-suite/errors/pp_unknowndirective.i @@ -1,5 +1,10 @@ %module xxx +/* Regression test for bug introduced in 3.0.4 and fixed in 3.0.6 - the '%std' + * here led to SWIG calling abort(). + */ +%typemap(jstype) std::vector, const %std::vector&, std::vector& "List" + /* This used to give the rather cryptic "Syntax error in input(1)." prior to * SWIG 3.0.4. This testcase checks that the improved message is actually * issued. diff --git a/Examples/test-suite/errors/pp_unknowndirective.stderr b/Examples/test-suite/errors/pp_unknowndirective.stderr index d0d5e249f..2cc2377c7 100644 --- a/Examples/test-suite/errors/pp_unknowndirective.stderr +++ b/Examples/test-suite/errors/pp_unknowndirective.stderr @@ -1 +1 @@ -pp_unknowndirective.i:7: Error: Unknown directive '%remane'. +pp_unknowndirective.i:12: Error: Unknown directive '%remane'. diff --git a/Examples/test-suite/errors/pp_unknowndirective2.i b/Examples/test-suite/errors/pp_unknowndirective2.i index 889e6c5b2..5c914e507 100644 --- a/Examples/test-suite/errors/pp_unknowndirective2.i +++ b/Examples/test-suite/errors/pp_unknowndirective2.i @@ -1,6 +1,6 @@ %module xxx -#ifdef FOO +#ifndef FOO long long i; /* Check we get an error for an unknown directive (this should be #elif). * Unknown directives were silently ignored by SWIG < 3.0.3. */ diff --git a/Examples/test-suite/errors/swig_pythoncode_bad.i b/Examples/test-suite/errors/swig_pythoncode_bad.i new file mode 100644 index 000000000..f1d497618 --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad.i @@ -0,0 +1,7 @@ +%module xxx + +%pythoncode %{ + def foo(): + a = 1 # This line starts with a tab instead of 8 spaces. + return 2 +%} diff --git a/Examples/test-suite/errors/swig_pythoncode_bad.stderr b/Examples/test-suite/errors/swig_pythoncode_bad.stderr new file mode 100644 index 000000000..71e5db8da --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad.stderr @@ -0,0 +1 @@ +swig_pythoncode_bad.i:7: Error: Line indented less than expected (line 2 of pythoncode) diff --git a/Examples/test-suite/errors/swig_pythoncode_bad2.i b/Examples/test-suite/errors/swig_pythoncode_bad2.i new file mode 100644 index 000000000..f80f1be86 --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad2.i @@ -0,0 +1,13 @@ +%module xxx + +%pythoncode %{ + def one(): + print "in one" +%} + +%pythoncode %{ + print "still in one" + + def two(): + print "in two" +%} diff --git a/Examples/test-suite/errors/swig_pythoncode_bad2.stderr b/Examples/test-suite/errors/swig_pythoncode_bad2.stderr new file mode 100644 index 000000000..48ad77e51 --- /dev/null +++ b/Examples/test-suite/errors/swig_pythoncode_bad2.stderr @@ -0,0 +1 @@ +swig_pythoncode_bad2.i:13: Error: Line indented less than expected (line 3 of pythoncode) diff --git a/Examples/test-suite/extern_c.i b/Examples/test-suite/extern_c.i index 9c17d18fb..e56d9f128 100644 --- a/Examples/test-suite/extern_c.i +++ b/Examples/test-suite/extern_c.i @@ -14,3 +14,18 @@ typedef int Integer2; void RealFunction(int value) {} %} + +%inline %{ +extern "C" { + typedef void (*Hook1_t)(int, const char *); +} +extern "C" typedef void (*Hook2_t)(int, const char *); +void funcy1(Hook1_t) {} +void funcy2(Hook2_t) {} +Hook1_t hook1; +Hook2_t hook2; + +extern "C" typedef int Integer; +Integer int1; +%} + diff --git a/Examples/test-suite/friends_template.i b/Examples/test-suite/friends_template.i new file mode 100644 index 000000000..48623f2ca --- /dev/null +++ b/Examples/test-suite/friends_template.i @@ -0,0 +1,46 @@ +%module friends_template + +%{ +template class MyClass; + +template int operator<<(double un, const MyClass & x) { return 0; } +template int funk_hidden(double is, MyClass & x) { return 2; } + +template T template_friend_hidden(T t) { return t + 1; } +%} + +%inline %{ +template int operator>>(double is, MyClass & x) { return 1; } +template int funk_seen(double is, MyClass & x) { return 2; } +template T template_friend_seen(T t1, T t2) { return t1 + t2; } +int friend_plain_seen(int i) { return i; } + +template class MyClass +{ + friend int operator<< (double un, const MyClass & x); + friend int operator>> (double is, MyClass & x); + friend int funk_hidden (double is, MyClass & x); + friend int funk_seen (double is, MyClass & x); +}; + +struct MyTemplate { + template friend T template_friend_hidden(T); + template friend T template_friend_seen(T, T); + friend int friend_plain_seen(int i); +}; + +MyClass makeMyClassInt() { return MyClass(); } +%} + +// Although the friends in MyClass are automatically instantiated via %template(MyClassDouble) MyClass, +// the operator friends are not valid and hence %rename is needed. +%rename(OperatorInputDouble) operator>> ; +%rename(OperatorOutputDouble) operator<< ; +%template(MyClassDouble) MyClass; + +%template(TemplateFriendHiddenInt) template_friend_hidden; +%template(TemplateFriendSeenInt) template_friend_seen; + +// These have no %template(XX) MyClass to instantiate, but they can be instantiated separately... +%template(OperatorInputInt) operator>> ; +%template(OperatorFunkSeenInt) funk_seen ; diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 4480ecf1f..63c18f2f4 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -5,31 +5,39 @@ LANGUAGE = go GO = @GO@ GOGCC = @GOGCC@ +GCCGO = @GCCGO@ GO1 = @GO1@ GO12 = @GO12@ GO13 = @GO13@ +GO15 = @GO15@ GOC = @GOC@ SCRIPTSUFFIX = _runme.go -GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` -GOLD = $(GOC:c=l) +GOCOMPILEARG = `if $(GO15); then echo tool compile; elif $(GO1); then echo tool $(GOC:c=g); fi` +GOLD = `if $(GO15); then echo link; else echo $(GOC:c=l); fi` GOTOOL = `if $(GO1) ; then echo go tool; fi` GOPACK = `if $(GO1) ; then echo go tool pack; else echo gopack; fi` -GOOBJEXT = $(GOC:c=) +GOOBJEXT = `if $(GO15); then echo o; else echo $(GOC:c=); fi` SO = @SO@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -top_builddir = @top_builddir@ +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ CPP_TEST_CASES = \ go_inout \ go_director_inout +MULTI_CPP_TEST_CASES = \ + go_subdir_import + include $(srcdir)/../common.mk +INCLUDES = -I$(abs_top_srcdir)/$(EXAMPLES)/$(TEST_SUITE) + .SUFFIXES: .cpptest .ctest .multicpptest # Rules for the different types of tests @@ -37,17 +45,37 @@ include $(srcdir)/../common.mk $(setup) +$(swig_and_compile_cpp) $(run_testcase_cpp) + if ! $(GO15); then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ + SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ + INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ + TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ + $(LANGUAGE)$(VARIANT)_cpp_nocgo; \ + $(run_testcase_cpp); \ + fi %.ctest: $(setup) +$(swig_and_compile_c) $(run_testcase) + if ! $(GO15); then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CSRCS="$(CSRCS)" \ + SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ + INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ + TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ + $(LANGUAGE)$(VARIANT)_nocgo; \ + $(run_testcase); \ + fi %.multicpptest: $(setup) +$(swig_and_compile_multi_cpp) $(run_multi_testcase) +li_windows.cpptest: + # Does not work because go build won't build li_windows.go, + # because file names with "windows" are only built on Windows. + multi_import.multicpptest: $(setup) for f in multi_import_b multi_import_a; do \ @@ -59,15 +87,43 @@ multi_import.multicpptest: done $(run_multi_testcase) +go_subdir_import.multicpptest: + $(setup) + mkdir -p testdir/go_subdir_import/ + mkdir -p gopath/src/testdir/go_subdir_import/ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ + SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ + INTERFACEPATH="$(SRCDIR)$(INTERFACEDIR)go_subdir_import_b.i" \ + INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT) -outdir ." NOLINK=true \ + TARGET="$(TARGETPREFIX)go_subdir_import_b$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" \ + INTERFACE="testdir/go_subdir_import/go_subdir_import_b.i" \ + $(LANGUAGE)$(VARIANT)_cpp; + for f in testdir/go_subdir_import/go_subdir_import_c go_subdir_import_a ; do \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ + SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ + INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ + TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ + $(LANGUAGE)$(VARIANT)_cpp; \ + done + if $(GOGCC); then \ + cp gopath/src/testdir/go_subdir_import/go_subdir_import_b/go_subdir_import_b.a gopath/src/testdir/go_subdir_import/go_subdir_import_b.gox; \ + cp gopath/src/testdir/go_subdir_import/go_subdir_import_b/go_subdir_import_b.a .; \ + cp gopath/src/testdir/go_subdir_import/go_subdir_import_c/go_subdir_import_c.a gopath/src/testdir/go_subdir_import/go_subdir_import_c.gox; \ + cp gopath/src/testdir/go_subdir_import/go_subdir_import_c/go_subdir_import_c.a testdir/go_subdir_import/; \ + fi + $(run_multi_testcase) + # Runs the testcase. run_testcase = \ if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@; \ - elif $(GO12) || $(GO13); then \ + $(COMPILETOOL) $(GCCGO) -c -g -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.a; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ @@ -75,12 +131,14 @@ run_testcase = \ run_testcase_cpp = \ if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ - $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@ -lstdc++; \ - elif $(GO12) || $(GO13); then \ + $(COMPILETOOL) $(GCCGO) -c -g -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.a -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ @@ -88,28 +146,38 @@ run_testcase_cpp = \ run_multi_testcase = \ if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ + $(COMPILETOOL) $(GCCGO) -c -g -I . -I gopath/src $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ files=`cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list`; \ - $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.@OBJEXT@ $${f}_wrap.@OBJEXT@; done` -lstdc++; \ - elif $(GO12) || $(GO13); then \ + $(COMPILETOOL) $(GCCGO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ `for f in $$files; do echo $$f.a; done` -lstdc++; \ + elif $(GO12) || $(GO13) || $(GO15); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ else \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ $(COMPILETOOL) $(GOTOOL) $(GOLD) -L . -r $${GOROOT:-`go env GOROOT`}/pkg/$${GOOS:-`go env GOOS`}_$${GOARCH:-`go env GOARCH`}:. -o $*_runme $(SCRIPTPREFIX)$*_runme.$(GOOBJEXT); \ fi && \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$*_runme; \ fi %.clean: - @rm -f $*.go $*_gc.c $*_wrap.* $*_runme + @rm -rf $*.go $*_gc.c $*_wrap.* $*_runme $*.gox $*.a clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" go_clean - rm -f mod_a.go mod_b.go imports_a.go imports_b.go - rm -f clientdata_prop_a.go clientdata_prop_b.go - rm -f multi_import_a.go multi_import_b.go - rm -f packageoption_a.go packageoption_b.go packageoption_c.go - rm -f import_stl_a.go import_stl_b.go + rm -f mod_a.go mod_a.gox mod_b.go mod_b.gox + rm -f imports_a.go imports_a.gox imports_b.go imports_b.gox + rm -f clientdata_prop_a.go clientdata_prop_a.gox + rm -f clientdata_prop_b.go clientdata_prop_b.gox + rm -f multi_import_a.go multi_import_a.gox + rm -f multi_import_b.go multi_import_b.gox + rm -rf go_subdir_import_a.go go_subdir_import_a.gox testdir + rm -f packageoption_a.go packageoption_a.gox + rm -f packageoption_b.go packageoption_b.gox + rm -f packageoption_c.go packageoption_c.gox + rm -f import_stl_a.go import_stl_a.gox + rm -f import_stl_b.go import_stl_b.gox + rm -rf gopath cvsignore: @echo '*_gc.c *_wrap.* *.so *.dll *.exp *.lib' diff --git a/Examples/test-suite/go/default_constructor_runme.go b/Examples/test-suite/go/default_constructor_runme.go index e5e325475..40a5a6e49 100644 --- a/Examples/test-suite/go/default_constructor_runme.go +++ b/Examples/test-suite/go/default_constructor_runme.go @@ -21,9 +21,6 @@ func main() { f := dc.NewF() f.Destroy() - ff := dc.NewFFF() - ff.Destroy() - g := dc.NewG() dc.GDestroy(g) diff --git a/Examples/test-suite/go/go_subdir_import_runme.go b/Examples/test-suite/go/go_subdir_import_runme.go new file mode 100644 index 000000000..f90a6eb54 --- /dev/null +++ b/Examples/test-suite/go/go_subdir_import_runme.go @@ -0,0 +1,16 @@ +package main + +import ( + "go_subdir_import_a" + "testdir/go_subdir_import/go_subdir_import_b" + "testdir/go_subdir_import/go_subdir_import_c" +) + +func main() { + b := go_subdir_import_b.NewObjB(); + c := go_subdir_import_c.NewObjC(); + v := go_subdir_import_a.AddFive(b, c) + if v != 50 { + panic(0) + } +} diff --git a/Examples/test-suite/go/inherit_member_runme.go b/Examples/test-suite/go/inherit_member_runme.go new file mode 100644 index 000000000..599a0eb56 --- /dev/null +++ b/Examples/test-suite/go/inherit_member_runme.go @@ -0,0 +1,15 @@ +package main + +import wrap "./inherit_member" + +func main() { + s := wrap.NewChild() + s.SetPvar("p") + s.SetCvar("c") + if s.GetPvar() != "p" { + panic(s.GetPvar()) + } + if s.GetCvar() != "c" { + panic(s.GetCvar()) + } +} diff --git a/Examples/test-suite/go/overload_polymorphic_runme.go b/Examples/test-suite/go/overload_polymorphic_runme.go index 1720e1a4d..46f837f49 100644 --- a/Examples/test-suite/go/overload_polymorphic_runme.go +++ b/Examples/test-suite/go/overload_polymorphic_runme.go @@ -6,6 +6,10 @@ func main(){ t := overload_polymorphic.NewDerived() if overload_polymorphic.Test(t) != 0 { - panic("failed") + panic("failed 1") + } + + if overload_polymorphic.Test2(t) != 1 { + panic("failed 2") } } diff --git a/Examples/test-suite/go_director_inout.i b/Examples/test-suite/go_director_inout.i index af59e313c..5a7fbdf89 100644 --- a/Examples/test-suite/go_director_inout.i +++ b/Examples/test-suite/go_director_inout.i @@ -44,14 +44,14 @@ type GoRetStruct struct { $result.str.assign($input.p, $input.n); %} -%typemap(out) RetStruct +%typemap(out,fragment="AllocateString") RetStruct %{ - $result = _swig_makegostring($1.str.data(), $1.str.length()); + $result = Swig_AllocateString($1.str.data(), $1.str.length()); %} -%typemap(goout) RetStruct +%typemap(goout,fragment="CopyString") RetStruct %{ - $result = GoRetStruct{Str: $input} + $result = GoRetStruct{Str: swigCopyString($input)} %} %typemap(godirectorout) RetStruct @@ -81,23 +81,28 @@ type GoRetStruct struct { } %} -%typemap(directorin) MyStruct +%typemap(directorin,fragment="AllocateString") MyStruct %{ - $input = _swig_makegostring($1.str.data(), $1.str.length()); + $input = Swig_AllocateString($1.str.data(), $1.str.length()); %} -%typemap(out) MyStruct +%typemap(godirectorin,fragment="CopyString") MyStruct %{ - $result = _swig_makegostring($1.str.data(), $1.str.length()); -%} - -%typemap(godirectorin) MyStruct -%{ - if err := json.Unmarshal([]byte($input), &$result); err != nil { + if err := json.Unmarshal([]byte(swigCopyString($input)), &$result); err != nil { panic(err) } %} +%typemap(out,fragment="AllocateString") MyStruct +%{ + $result = Swig_AllocateString($1.str.data(), $1.str.length()); +%} + +%typemap(goout,fragment="CopyString") MyStruct +%{ + $result = swigCopyString($input) +%} + %typemap(in) MyStruct %{ $1.str.assign($input.p, $input.n); diff --git a/Examples/test-suite/go_inout.i b/Examples/test-suite/go_inout.i index 510ed68e0..57e7bf2fb 100644 --- a/Examples/test-suite/go_inout.i +++ b/Examples/test-suite/go_inout.i @@ -56,14 +56,14 @@ type In json.Marshaler %typemap(imtype) RetStruct "string" -%typemap(out) RetStruct +%typemap(out,fragment="AllocateString") RetStruct %{ - $result = _swig_makegostring($1.str.data(), $1.str.length()); + $result = Swig_AllocateString($1.str.data(), $1.str.length()); %} -%typemap(goout) RetStruct +%typemap(goout,fragment="CopyString") RetStruct %{ - if err := json.Unmarshal([]byte($1), &$result); err != nil { + if err := json.Unmarshal([]byte(swigCopyString($1)), &$result); err != nil { panic(err) } %} @@ -146,7 +146,7 @@ static void putuint64(std::string *s, size_t off, uint64_t v) { %} // Pack the vector into a string. -%typemap(argout) MyArray* +%typemap(argout,fragment="AllocateString") MyArray* %{ { size_t tot = 8; @@ -164,15 +164,15 @@ static void putuint64(std::string *s, size_t off, uint64_t v) { str.replace(off, p->size(), *p); off += p->size(); } - *$input = _swig_makegostring(str.data(), str.size()); + *$input = Swig_AllocateString(str.data(), str.size()); } %} // Unpack the string into a []string. -%typemap(goargout) MyArray* +%typemap(goargout,fragment="CopyString") MyArray* %{ { - str := *$input + str := swigCopyString(*$input) bin := binary.LittleEndian size := bin.Uint64([]byte(str[:8])) str = str[8:] diff --git a/Examples/test-suite/go_subdir_import.list b/Examples/test-suite/go_subdir_import.list new file mode 100644 index 000000000..e117d32fa --- /dev/null +++ b/Examples/test-suite/go_subdir_import.list @@ -0,0 +1,3 @@ +testdir/go_subdir_import/go_subdir_import_c +go_subdir_import_b +go_subdir_import_a diff --git a/Examples/test-suite/go_subdir_import_a.i b/Examples/test-suite/go_subdir_import_a.i new file mode 100644 index 000000000..3fc36e6f9 --- /dev/null +++ b/Examples/test-suite/go_subdir_import_a.i @@ -0,0 +1,37 @@ +/* File : go_subdir_import_a.i */ + +/* + * This files helps check the case where the SWIG-generated .go file needs to + * import another, SWIG-generated, module that is in a relative subdirectory. + * This case might happen for two different reasons: + * 1) Importing a module for which the .i file is in a subdirectory relatively + * to this file (this is tested here with go_subdir_import_c). + * 2) Importing a module whos module name is a path (this is tested here with + * go_subdir_import_b). + * + * This file is the "root" file that imports the two modules which will be + * generated (by swig) in a relative subdirectory. + */ +%module go_subdir_import_a + +%import(module="testdir/go_subdir_import/go_subdir_import_c") "testdir/go_subdir_import/go_subdir_import_c.i" +%import "go_subdir_import_b.i" + +%{ +class ObjC { + public: + virtual int getInt() const; +}; + +class ObjB { + public: + virtual int getInt() const; +}; +%} + +%inline %{ +int AddFive(const ObjB& b, const ObjC& c) { + return b.getInt() + c.getInt() + 5; +} +%} + diff --git a/Examples/test-suite/go_subdir_import_b.i b/Examples/test-suite/go_subdir_import_b.i new file mode 100644 index 000000000..42544822e --- /dev/null +++ b/Examples/test-suite/go_subdir_import_b.i @@ -0,0 +1,12 @@ +/* File : go_subdir_import_b.i */ +%module "testdir/go_subdir_import/go_subdir_import_b" + +%inline %{ +class ObjB { + public: + virtual int getInt() const { + return 27; + } +}; +%} + diff --git a/Examples/test-suite/inherit_member.i b/Examples/test-suite/inherit_member.i new file mode 100644 index 000000000..c26da6151 --- /dev/null +++ b/Examples/test-suite/inherit_member.i @@ -0,0 +1,17 @@ +// Based on https://github.com/swig/swig/issues/339 . + +%module inherit_member + +%include + +%inline %{ + +struct parent_class { + std::string pvar; +}; + + struct child : public parent_class { + std::string cvar; +}; + +%} diff --git a/Examples/test-suite/java/cpp11_constexpr_runme.java b/Examples/test-suite/java/cpp11_constexpr_runme.java index c774e82f8..de1ae8cc3 100644 --- a/Examples/test-suite/java/cpp11_constexpr_runme.java +++ b/Examples/test-suite/java/cpp11_constexpr_runme.java @@ -23,7 +23,7 @@ public class cpp11_constexpr_runme { check(cpp11_constexpr.CCC(), 30); check(cpp11_constexpr.DDD(), 40); - ConstExpressions ce = new ConstExpressions(); + ConstExpressions ce = new ConstExpressions(0); check(ce.JJJ, 100); check(ce.KKK, 200); check(ce.LLL, 300); diff --git a/Examples/test-suite/java/cpp11_type_aliasing_runme.java b/Examples/test-suite/java/cpp11_type_aliasing_runme.java new file mode 100644 index 000000000..0db1df372 --- /dev/null +++ b/Examples/test-suite/java/cpp11_type_aliasing_runme.java @@ -0,0 +1,20 @@ +import cpp11_type_aliasing.*; + +public class cpp11_type_aliasing_runme { + + static { + try { + System.loadLibrary("cpp11_type_aliasing"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); + System.exit(1); + } + } + + public static void main(String argv[]) { + Halide_Target ht = new GeneratorBase().getTarget(); + Target x = ht.getValue(); + if (x.getBits() != 32) + throw new RuntimeException("Incorrect bits"); + } +} diff --git a/Examples/test-suite/java/default_constructor_runme.java b/Examples/test-suite/java/default_constructor_runme.java index 6473c4099..eb6a2df53 100644 --- a/Examples/test-suite/java/default_constructor_runme.java +++ b/Examples/test-suite/java/default_constructor_runme.java @@ -20,13 +20,5 @@ public class default_constructor_runme { throw new RuntimeException("Protected destructor exception should have been thrown"); } catch (UnsupportedOperationException e) { } - - // calling private destructor test - try { - FFF f = new FFF(); - f.delete(); - throw new RuntimeException("Private destructor exception should have been thrown"); - } catch (UnsupportedOperationException e) { - } } } diff --git a/Examples/test-suite/java/director_binary_string_runme.java b/Examples/test-suite/java/director_binary_string_runme.java index 962073367..14982efc2 100644 --- a/Examples/test-suite/java/director_binary_string_runme.java +++ b/Examples/test-suite/java/director_binary_string_runme.java @@ -17,11 +17,15 @@ public class director_binary_string_runme { Callback callback = new DirectorBinaryStringCallback(); caller.setCallback(callback); int sum = caller.call(); + int sumData = caller.callWriteData(); caller.delCallback(); if (sum != 9*2*8 + 13*3*5) throw new RuntimeException("Unexpected sum: " + sum); + if (sumData != 9*2*8) + throw new RuntimeException("Unexpected sum: " + sum); + new Callback().run(null, null); callback = new DirectorBinaryStringCallback(); caller.setCallback(callback); @@ -45,5 +49,13 @@ class DirectorBinaryStringCallback extends Callback { for (int i = 0; i < dataBufferBB.length; i++) dataBufferBB[i] = (byte)(dataBufferBB[i] * 3); } + + @Override + public void writeData(byte[] dataBufferAA) + { + if (dataBufferAA != null) + for (int i = 0; i < dataBufferAA.length; i++) + dataBufferAA[i] = (byte)(dataBufferAA[i] * 2); + } } diff --git a/Examples/test-suite/java/director_ref_runme.java b/Examples/test-suite/java/director_ref_runme.java new file mode 100644 index 000000000..1f85a6698 --- /dev/null +++ b/Examples/test-suite/java/director_ref_runme.java @@ -0,0 +1,71 @@ + +import director_ref.*; + +public class director_ref_runme { + + static { + try { + System.loadLibrary("director_ref"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); + System.exit(1); + } + } + + public static void main(String argv[]) { + director_ref_MyFoo a = new director_ref_MyFoo(); + if (a.GetRefCount() != 1) { + throw new RuntimeException ( "Refcount test 1 failed." ); + } + + // Make sure director logic still works. + if (!a.GetMsg().equals("director_ref_MyFoo-default")) { + throw new RuntimeException ( "Test 1 failed" ); + } + if (!a.GetMsg("boo").equals("director_ref_MyFoo-boo")) { + throw new RuntimeException ( "Test 2 failed" ); + } + + a.delete(); // should delete the object. + if (a.cppDeleted != true) { + throw new RuntimeException ( "Unref test 1 failed." ); + } + + a = new director_ref_MyFoo(); + FooPtr p = new FooPtr(a); + if (a.GetRefCount() != 2) { + throw new RuntimeException ( "Refcount test 2 failed." ); + } + a.delete(); // Shouldn't actually delete the underlying object + if (a.cppDeleted) { + throw new RuntimeException ( "Unref test 2 failed." ); + } + if (p.GetOwnedRefCount() != 1) { + throw new RuntimeException ( "Unref test 3 failed." ); + } + p.Reset(); // Now it should be deleted on the cpp side. + // We can't check cppDeleted because the director will stop + // working after a delete() call. + if (p.GetOwnedRefCount() != 0) { + throw new RuntimeException ( "Unref test 4 failed." ); + } + } +} + +class director_ref_MyFoo extends Foo { + public director_ref_MyFoo() { + super(); + } + public director_ref_MyFoo(int i) { + super(i); + } + public String Msg(String msg) { + return "director_ref_MyFoo-" + msg; + } + public void OnDelete() { + cppDeleted = true; + } + + public boolean cppDeleted = false; +} + diff --git a/Examples/test-suite/java/friends_template_runme.java b/Examples/test-suite/java/friends_template_runme.java new file mode 100644 index 000000000..eb66cd5cb --- /dev/null +++ b/Examples/test-suite/java/friends_template_runme.java @@ -0,0 +1,28 @@ + +import friends_template.*; + +public class friends_template_runme { + + static { + try { + System.loadLibrary("friends_template"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); + System.exit(1); + } + } + + public static void main(String argv[]) { + friends_template.OperatorOutputDouble(1.1, new MyClassDouble()); + friends_template.OperatorInputDouble(1.1, new MyClassDouble()); + friends_template.funk_hidden(1.1, new MyClassDouble()); + friends_template.funk_seen(1.1, new MyClassDouble()); + + friends_template.TemplateFriendHiddenInt(0); + friends_template.TemplateFriendSeenInt(0, 0); + + SWIGTYPE_p_MyClassT_int_t myClassInt = friends_template.makeMyClassInt(); + friends_template.OperatorInputInt(1, myClassInt); + friends_template.OperatorFunkSeenInt(1.1, myClassInt); + } +} diff --git a/Examples/test-suite/java/li_boost_shared_ptr_bits_runme.java b/Examples/test-suite/java/li_boost_shared_ptr_bits_runme.java index d1489edf4..aefa81182 100644 --- a/Examples/test-suite/java/li_boost_shared_ptr_bits_runme.java +++ b/Examples/test-suite/java/li_boost_shared_ptr_bits_runme.java @@ -23,5 +23,12 @@ public class li_boost_shared_ptr_bits_runme { HiddenDestructor hidden = HiddenDestructor.create(); hidden.delete(); + + HiddenPrivateDestructor hiddenPrivate = HiddenPrivateDestructor.create(); + if (HiddenPrivateDestructor.getDeleteCount() != 0) + throw new RuntimeException("Count should be zero"); + hiddenPrivate.delete(); + if (HiddenPrivateDestructor.getDeleteCount() != 1) + throw new RuntimeException("Count should be one"); } } diff --git a/Examples/test-suite/java/li_carrays_runme.java b/Examples/test-suite/java/li_carrays_runme.java index f576eab84..d32bb6ff9 100644 --- a/Examples/test-suite/java/li_carrays_runme.java +++ b/Examples/test-suite/java/li_carrays_runme.java @@ -31,7 +31,7 @@ public class li_carrays_runme { { // global array variable - int length = 5; + int length = 3; XY xyArrayPointer = li_carrays.getGlobalXYArray(); XYArray xyArray = XYArray.frompointer(xyArrayPointer); for (int i=0; i create() { + boost::shared_ptr hidden( new HiddenPrivateDestructor(), HiddenPrivateDestructor::Deleter() ); + return hidden; + } + static int DeleteCount; +}; + +int HiddenPrivateDestructor::DeleteCount = 0; +%} + diff --git a/Examples/test-suite/lua/chartest_runme.lua b/Examples/test-suite/lua/chartest_runme.lua new file mode 100644 index 000000000..e15f3dc6b --- /dev/null +++ b/Examples/test-suite/lua/chartest_runme.lua @@ -0,0 +1,14 @@ +require("import") -- the import fn +import("chartest") -- import code + +function char_assert(char, code) + assert(type(char) == 'string') + assert(char:len() == 1) + assert(char:byte() == code) +end + +char_assert(chartest.GetPrintableChar(), 0x61) +char_assert(chartest.GetUnprintableChar(), 0x7F) + +char_assert(chartest.printable_global_char, 0x61) +char_assert(chartest.unprintable_global_char, 0x7F) diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index 9a4e008b9..0956fcbc4 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -3,7 +3,7 @@ ####################################################################### LANGUAGE = ocaml -OCAMLC = ocamlc +OCAMLC = @OCAMLC@ VARIANT = _static SCRIPTSUFFIX = _runme.ml @@ -25,18 +25,11 @@ run_testcase = \ fi ; check_quant: - cat /dev/null > testing - cat /dev/null > success - cat /dev/null > results + : > testing + : > success $(MAKE) check - echo "Failed:" >> results - for element in `cat testing` ; do \ - if grep $$element success >/dev/null 2>/dev/null ; then \ - : ; \ - else \ - echo $$element >> results ; \ - fi ; \ - done + echo "Failed:" > results + diff testing success | sed 's/^< //p;d' >> results echo "Success:" >> results cat success >> results diff --git a/Examples/test-suite/octave/default_constructor_runme.m b/Examples/test-suite/octave/default_constructor_runme.m index 41d0f3f1e..ebe553b20 100644 --- a/Examples/test-suite/octave/default_constructor_runme.m +++ b/Examples/test-suite/octave/default_constructor_runme.m @@ -14,24 +14,18 @@ try catch end_try_catch -del_b = dc.delete_B; - try bb = dc.new_BB(); error("Whoa. new_BB created.") catch end_try_catch -del_bb = dc.delete_BB; - try c = dc.new_C(); error("Whoa. new_C created.") catch end_try_catch -del_c = dc.delete_C; - cc = dc.new_CC(); dc.delete_CC(cc); @@ -41,24 +35,18 @@ try catch end_try_catch -del_d = dc.delete_D; - try dd = dc.new_DD(); error("Whoa. new_DD created") catch end_try_catch -dd = dc.delete_DD; - try ad = dc.new_AD(); error("Whoa. new_AD created") catch end_try_catch -del_ad = dc.delete_AD; - e = dc.new_E(); dc.delete_E(e); @@ -71,31 +59,20 @@ try catch end_try_catch -del_eb = dc.delete_EB; - f = dc.new_F(); try - del_f = dc.delete_F; + del_f = dc.delete_F(f); error("Whoa. delete_F created") catch end_try_catch dc.F_destroy(f); -ff = dc.new_FFF(); -try - del_ff = dc.delete_FFF; - error("Whoa. delete_FFF created") -catch -end_try_catch - -dc.F_destroy(ff); - g = dc.new_G(); try - del_g = dc.delete_G; + del_g = dc.delete_G(g); error("Whoa. delete_G created") catch end_try_catch diff --git a/Examples/test-suite/operator_overload_break.i b/Examples/test-suite/operator_overload_break.i index f5f3c1a46..a948f2d49 100644 --- a/Examples/test-suite/operator_overload_break.i +++ b/Examples/test-suite/operator_overload_break.i @@ -12,6 +12,10 @@ %rename(PlusPlusPostfix) operator++(int); #endif +%ignore operator new (size_t); +%ignore operator delete (void *); +%ignore operator delete[] (void *); + %{ #include using namespace std; @@ -60,4 +64,16 @@ public: int k; }; +struct Op2 { + void *operator new + (size_t); // definition split over two lines was giving syntax error + void operator delete /* comment here did not work */ (void *); + void operator + delete[] (void *); +}; + +void *Op2::operator new(size_t) { return malloc(sizeof(Op)); } +void Op2::operator delete(void *p) { free(p); } +void Op2::operator delete[] (void *) {} + %} diff --git a/Examples/test-suite/overload_polymorphic.i b/Examples/test-suite/overload_polymorphic.i index a1f123b9d..ac004f948 100644 --- a/Examples/test-suite/overload_polymorphic.i +++ b/Examples/test-suite/overload_polymorphic.i @@ -19,4 +19,8 @@ public: int test(Base* base){ return 0;} int test(int hello){ return 1; } +class Unknown; +int test2(Unknown* unknown) { return 0; } +int test2(Base* base) { return 1; } + %} diff --git a/Examples/test-suite/perl5/li_carrays_runme.pl b/Examples/test-suite/perl5/li_carrays_runme.pl index 00d12cd1b..51c813403 100644 --- a/Examples/test-suite/perl5/li_carrays_runme.pl +++ b/Examples/test-suite/perl5/li_carrays_runme.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl use strict; use warnings; -use Test::More tests => 38; +use Test::More tests => 34; BEGIN { use_ok('li_carrays') } require_ok('li_carrays'); @@ -23,7 +23,7 @@ require_ok('li_carrays'); { # global array variable - my $length = 5; + my $length = 3; my $xyArrayPointer = $li_carrays::globalXYArray; my $xyArray = li_carrays::XYArray::frompointer($xyArrayPointer); for (my $i=0; $i<$length; $i++) { diff --git a/Examples/test-suite/preproc_defined.i b/Examples/test-suite/preproc_defined.i index 617e84f61..0a91bd98a 100644 --- a/Examples/test-suite/preproc_defined.i +++ b/Examples/test-suite/preproc_defined.i @@ -107,3 +107,18 @@ void another_macro_checking(void) { bumpf(10); } %} + +/* Check that unknown preprocessor directives are ignored inside an inactive + * conditional (github issue #394). + */ +#ifdef APPLE_OPENGL +# import +#endif +#ifdef AAA +# define B +#else +# wibble wibble +#endif +#if 0 +# wobble wobble +#endif diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 82a0e9db1..a99c30439 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -61,6 +61,7 @@ CPP_TEST_CASES += \ python_director \ python_nondynamic \ python_overload_simple_cast \ + python_pythoncode \ python_richcompare \ simutry \ std_containers \ @@ -125,17 +126,14 @@ py_runme = $(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) py2_runme = $(SCRIPTPREFIX)$*$(PY2SCRIPTSUFFIX) py3_runme = $(SCRIPTPREFIX)$*$(PY3SCRIPTSUFFIX) -check_pep8 = \ - if [ -n "$(PEP8)" ]; then \ - $(PEP8) $(PEP8_FLAGS) $(SCRIPTPREFIX)$*.py;\ - fi +ifneq (,$(PEP8)) +check_pep8 = $(PEP8) $(PEP8_FLAGS) $(SCRIPTPREFIX)$*.py check_pep8_multi_cpp = \ - if [ -n "$(PEP8)" ]; then \ - for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ + for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ $(PEP8) $(PEP8_FLAGS) $$f.py; \ - done \ - fi + done +endif run_python = env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=.:$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(py_runme) diff --git a/Examples/test-suite/python/abstract_access_runme.py b/Examples/test-suite/python/abstract_access_runme.py index 55638e40e..8abce98ae 100644 --- a/Examples/test-suite/python/abstract_access_runme.py +++ b/Examples/test-suite/python/abstract_access_runme.py @@ -2,5 +2,4 @@ import abstract_access d = abstract_access.D() if d.do_x() != 1: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/abstract_typedef2_runme.py b/Examples/test-suite/python/abstract_typedef2_runme.py index 2a11d1944..ef6f415dd 100644 --- a/Examples/test-suite/python/abstract_typedef2_runme.py +++ b/Examples/test-suite/python/abstract_typedef2_runme.py @@ -1,8 +1,3 @@ -from abstract_typedef2 import * +from abstract_typedef2 import * a = A_UF() - - - - - diff --git a/Examples/test-suite/python/abstract_typedef_runme.py b/Examples/test-suite/python/abstract_typedef_runme.py index 15d70aa42..d69134f2e 100644 --- a/Examples/test-suite/python/abstract_typedef_runme.py +++ b/Examples/test-suite/python/abstract_typedef_runme.py @@ -1,11 +1,8 @@ -from abstract_typedef import * +from abstract_typedef import * e = Engine() a = A() - + if a.write(e) != 1: - raise RuntimeError - - - + raise RuntimeError diff --git a/Examples/test-suite/python/argcargvtest_runme.py b/Examples/test-suite/python/argcargvtest_runme.py index 047ea9551..38843b932 100644 --- a/Examples/test-suite/python/argcargvtest_runme.py +++ b/Examples/test-suite/python/argcargvtest_runme.py @@ -1,27 +1,26 @@ from argcargvtest import * -largs=['hi','hola','hello'] +largs = ['hi', 'hola', 'hello'] if mainc(largs) != 3: - raise RuntimeError("bad main typemap") + raise RuntimeError("bad main typemap") -targs=('hi','hola') -if mainv(targs,1) != 'hola': - print(mainv(targs,1)) - raise RuntimeError("bad main typemap") +targs = ('hi', 'hola') +if mainv(targs, 1) != 'hola': + print(mainv(targs, 1)) + raise RuntimeError("bad main typemap") -targs=('hi', 'hola') -if mainv(targs,1) != 'hola': - raise RuntimeError("bad main typemap") +targs = ('hi', 'hola') +if mainv(targs, 1) != 'hola': + raise RuntimeError("bad main typemap") try: - error = 0 - mainv('hello',1) - error = 1 + error = 0 + mainv('hello', 1) + error = 1 except TypeError: - pass + pass if error: - raise RuntimeError("bad main typemap") - + raise RuntimeError("bad main typemap") initializeApp(largs) diff --git a/Examples/test-suite/python/array_member_runme.py b/Examples/test-suite/python/array_member_runme.py index 95cf03b44..de6e0f3e7 100644 --- a/Examples/test-suite/python/array_member_runme.py +++ b/Examples/test-suite/python/array_member_runme.py @@ -3,19 +3,16 @@ from array_member import * f = Foo() f.data = cvar.global_data -for i in range(0,8): - if get_value(f.data,i) != get_value(cvar.global_data,i): +for i in range(0, 8): + if get_value(f.data, i) != get_value(cvar.global_data, i): raise RuntimeError, "Bad array assignment" -for i in range(0,8): - set_value(f.data,i,-i) +for i in range(0, 8): + set_value(f.data, i, -i) cvar.global_data = f.data -for i in range(0,8): - if get_value(f.data,i) != get_value(cvar.global_data,i): +for i in range(0, 8): + if get_value(f.data, i) != get_value(cvar.global_data, i): raise RuntimeError, "Bad array assignment" - - - diff --git a/Examples/test-suite/python/arrays_global_runme.py b/Examples/test-suite/python/arrays_global_runme.py index ab7fd6a41..fa3b9f2ec 100644 --- a/Examples/test-suite/python/arrays_global_runme.py +++ b/Examples/test-suite/python/arrays_global_runme.py @@ -2,19 +2,19 @@ import arrays_global arrays_global.cvar.array_i = arrays_global.cvar.array_const_i -from arrays_global import * +from arrays_global import * BeginString_FIX44a cvar.BeginString_FIX44b BeginString_FIX44c cvar.BeginString_FIX44d cvar.BeginString_FIX44d -cvar.BeginString_FIX44b ="12"'\0'"45" +cvar.BeginString_FIX44b = "12"'\0'"45" cvar.BeginString_FIX44b cvar.BeginString_FIX44d cvar.BeginString_FIX44e BeginString_FIX44f -test_a("hello","hi","chello","chi") +test_a("hello", "hi", "chello", "chi") -test_b("1234567","hi") +test_b("1234567", "hi") diff --git a/Examples/test-suite/python/autodoc_runme.py b/Examples/test-suite/python/autodoc_runme.py index 6ad4bae0c..6a490d1b4 100644 --- a/Examples/test-suite/python/autodoc_runme.py +++ b/Examples/test-suite/python/autodoc_runme.py @@ -3,166 +3,161 @@ from commentVerifier import check import sys def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") if not is_new_style_class(A): - # Missing static methods make this hard to test... skip if -classic is used! - sys.exit(0) + # Missing static methods make this hard to test... skip if -classic is + # used! + sys.exit(0) check(A.__doc__, "Proxy of C++ A class") check(A.funk.__doc__, "just a string") check(A.func0.__doc__, "func0(self, arg2, hello) -> int") check(A.func1.__doc__, "func1(A self, short arg2, Tuple hello) -> int") check(A.func2.__doc__, -"func2(self, arg2, hello) -> int\n" -"\n" -"Parameters:\n" -" arg2: short\n" -" hello: int tuple[2]\n" -) + "func2(self, arg2, hello) -> int\n" + "\n" + "Parameters:\n" + " arg2: short\n" + " hello: int tuple[2]\n" + ) check(A.func3.__doc__, -"func3(A self, short arg2, Tuple hello) -> int\n" -"\n" -"Parameters:\n" -" arg2: short\n" -" hello: int tuple[2]\n" -) + "func3(A self, short arg2, Tuple hello) -> int\n" + "\n" + "Parameters:\n" + " arg2: short\n" + " hello: int tuple[2]\n" + ) check(A.func0default.__doc__, -"func0default(self, e, arg3, hello, f=2) -> int\n" -"func0default(self, e, arg3, hello) -> int" -) + "func0default(self, e, arg3, hello, f=2) -> int\n" + "func0default(self, e, arg3, hello) -> int" + ) check(A.func1default.__doc__, -"func1default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" -"func1default(A self, A e, short arg3, Tuple hello) -> int" -) + "func1default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" + "func1default(A self, A e, short arg3, Tuple hello) -> int" + ) check(A.func2default.__doc__, -"func2default(self, e, arg3, hello, f=2) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg3: short\n" -" hello: int tuple[2]\n" -" f: double\n" -"\n" -"func2default(self, e, arg3, hello) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg3: short\n" -" hello: int tuple[2]\n" -) + "func2default(self, e, arg3, hello, f=2) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg3: short\n" + " hello: int tuple[2]\n" + " f: double\n" + "\n" + "func2default(self, e, arg3, hello) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg3: short\n" + " hello: int tuple[2]\n" + ) check(A.func3default.__doc__, -"func3default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg3: short\n" -" hello: int tuple[2]\n" -" f: double\n" -"\n" -"func3default(A self, A e, short arg3, Tuple hello) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg3: short\n" -" hello: int tuple[2]\n" -) + "func3default(A self, A e, short arg3, Tuple hello, double f=2) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg3: short\n" + " hello: int tuple[2]\n" + " f: double\n" + "\n" + "func3default(A self, A e, short arg3, Tuple hello) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg3: short\n" + " hello: int tuple[2]\n" + ) check(A.func0static.__doc__, -"func0static(e, arg2, hello, f=2) -> int\n" -"func0static(e, arg2, hello) -> int" -) + "func0static(e, arg2, hello, f=2) -> int\n" + "func0static(e, arg2, hello) -> int" + ) check(A.func1static.__doc__, -"func1static(A e, short arg2, Tuple hello, double f=2) -> int\n" -"func1static(A e, short arg2, Tuple hello) -> int" -) + "func1static(A e, short arg2, Tuple hello, double f=2) -> int\n" + "func1static(A e, short arg2, Tuple hello) -> int" + ) check(A.func2static.__doc__, -"func2static(e, arg2, hello, f=2) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg2: short\n" -" hello: int tuple[2]\n" -" f: double\n" -"\n" -"func2static(e, arg2, hello) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg2: short\n" -" hello: int tuple[2]\n" -) + "func2static(e, arg2, hello, f=2) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg2: short\n" + " hello: int tuple[2]\n" + " f: double\n" + "\n" + "func2static(e, arg2, hello) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg2: short\n" + " hello: int tuple[2]\n" + ) check(A.func3static.__doc__, -"func3static(A e, short arg2, Tuple hello, double f=2) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg2: short\n" -" hello: int tuple[2]\n" -" f: double\n" -"\n" -"func3static(A e, short arg2, Tuple hello) -> int\n" -"\n" -"Parameters:\n" -" e: A *\n" -" arg2: short\n" -" hello: int tuple[2]\n" -) + "func3static(A e, short arg2, Tuple hello, double f=2) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg2: short\n" + " hello: int tuple[2]\n" + " f: double\n" + "\n" + "func3static(A e, short arg2, Tuple hello) -> int\n" + "\n" + "Parameters:\n" + " e: A *\n" + " arg2: short\n" + " hello: int tuple[2]\n" + ) if sys.version_info[0:2] > (2, 4): - # Python 2.4 does not seem to work - if is_python_builtin(): - check(A.variable_a.__doc__, "A.variable_a") - check(A.variable_b.__doc__, "A.variable_b") - check(A.variable_c.__doc__, "A.variable_c") - check(A.variable_d.__doc__, "A.variable_d") - else: - check(A.variable_a.__doc__, "A_variable_a_get(self) -> int" - ) - check(A.variable_b.__doc__, "A_variable_b_get(A self) -> int") + # Python 2.4 does not seem to work + check(A.variable_a.__doc__, + "A_variable_a_get(self) -> int" + ) + check(A.variable_b.__doc__, + "A_variable_b_get(A self) -> int" + ) check(A.variable_c.__doc__, - "A_variable_c_get(self) -> int\n" - "\n" - "Parameters:\n" - " self: A *\n" - ) + "A_variable_c_get(self) -> int\n" + "\n" + "Parameters:\n" + " self: A *\n" + ) check(A.variable_d.__doc__, - "A_variable_d_get(A self) -> int\n" - "\n" - "Parameters:\n" - " self: A *\n" - ) + "A_variable_d_get(A self) -> int\n" + "\n" + "Parameters:\n" + " self: A *\n" + ) check(B.__doc__, "Proxy of C++ B class") - -# skip builtin check - the autodoc is missing, but it probably should not be -if not is_python_builtin(): - check(C.__init__.__doc__, "__init__(self, a, b, h) -> C") - check(D.__init__.__doc__, "__init__(D self, int a, int b, Hola h) -> D") - check(E.__init__.__doc__, - "__init__(self, a, b, h) -> E\n" - "\n" - "Parameters:\n" - " a: special comment for parameter a\n" - " b: another special comment for parameter b\n" - " h: enum Hola\n" - ) - check(F.__init__.__doc__, - "__init__(F self, int a, int b, Hola h) -> F\n" - "\n" - "Parameters:\n" - " a: special comment for parameter a\n" - " b: another special comment for parameter b\n" - " h: enum Hola\n" - ) +check(C.__init__.__doc__, "__init__(self, a, b, h) -> C") +check(D.__init__.__doc__, "__init__(D self, int a, int b, Hola h) -> D") +check(E.__init__.__doc__, + "__init__(self, a, b, h) -> E\n" + "\n" + "Parameters:\n" + " a: special comment for parameter a\n" + " b: another special comment for parameter b\n" + " h: enum Hola\n" + ) +check(F.__init__.__doc__, + "__init__(F self, int a, int b, Hola h) -> F\n" + "\n" + "Parameters:\n" + " a: special comment for parameter a\n" + " b: another special comment for parameter b\n" + " h: enum Hola\n" + ) check(B.funk.__doc__, "funk(B self, int c, int d) -> int") check(funk.__doc__, "funk(A e, short arg2, int c, int d) -> int") check(funkdefaults.__doc__, -"funkdefaults(A e, short arg2, int c, int d, double f=2) -> int\n" -"funkdefaults(A e, short arg2, int c, int d) -> int" -) + "funkdefaults(A e, short arg2, int c, int d, double f=2) -> int\n" + "funkdefaults(A e, short arg2, int c, int d) -> int" + ) check(func_input.__doc__, "func_input(int * INPUT) -> int") check(func_output.__doc__, "func_output() -> int") diff --git a/Examples/test-suite/python/callback_runme.py b/Examples/test-suite/python/callback_runme.py index b2bbb2d0f..ef7baad4e 100644 --- a/Examples/test-suite/python/callback_runme.py +++ b/Examples/test-suite/python/callback_runme.py @@ -2,30 +2,30 @@ import _callback from callback import * if foo(2) != 2: - raise RuntimeError + raise RuntimeError if A_bar(2) != 4: - raise RuntimeError + raise RuntimeError if foobar(3, _callback.foo) != foo(3): - raise RuntimeError + raise RuntimeError if foobar(3, foo) != foo(3): - raise RuntimeError + raise RuntimeError if foobar(3, A_bar) != A_bar(3): - raise RuntimeError + raise RuntimeError if foobar(3, foof) != foof(3): - raise RuntimeError + raise RuntimeError if foobar_i(3, foo_i) != foo_i(3): - raise RuntimeError + raise RuntimeError if foobar_d(3.5, foo_d) != foo_d(3.5): - raise RuntimeError + raise RuntimeError a = A() if foobarm(3, a, A.foom_cb_ptr) != a.foom(3): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/char_binary_runme.py b/Examples/test-suite/python/char_binary_runme.py index b6d9c81c8..13457253f 100644 --- a/Examples/test-suite/python/char_binary_runme.py +++ b/Examples/test-suite/python/char_binary_runme.py @@ -2,11 +2,11 @@ from char_binary import * t = Test() if t.strlen('hile') != 4: - print t.strlen('hile') - raise RuntimeError, "bad multi-arg typemap" + print t.strlen('hile') + raise RuntimeError, "bad multi-arg typemap" if t.strlen('hil\0') != 4: - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError, "bad multi-arg typemap" # # creating a raw char* @@ -20,17 +20,16 @@ pchar_setitem(pc, 4, 0) if t.strlen(pc) != 4: - raise RuntimeError, "bad multi-arg typemap" + raise RuntimeError, "bad multi-arg typemap" cvar.var_pchar = pc if cvar.var_pchar != "hola": - print cvar.var_pchar - raise RuntimeError, "bad pointer case" + print cvar.var_pchar + raise RuntimeError, "bad pointer case" cvar.var_namet = pc -#if cvar.var_namet != "hola\0": +# if cvar.var_namet != "hola\0": if cvar.var_namet != "hola": - raise RuntimeError, "bad pointer case" + raise RuntimeError, "bad pointer case" delete_pchar(pc) - diff --git a/Examples/test-suite/python/compactdefaultargs_runme.py b/Examples/test-suite/python/compactdefaultargs_runme.py index ff865714c..e81c8d173 100644 --- a/Examples/test-suite/python/compactdefaultargs_runme.py +++ b/Examples/test-suite/python/compactdefaultargs_runme.py @@ -4,17 +4,16 @@ defaults1 = Defaults1(1000) defaults1 = Defaults1() if defaults1.ret(10.0) != 10.0: - raise RuntimeError + raise RuntimeError if defaults1.ret() != -1.0: - raise RuntimeError + raise RuntimeError defaults2 = Defaults2(1000) defaults2 = Defaults2() if defaults2.ret(10.0) != 10.0: - raise RuntimeError + raise RuntimeError if defaults2.ret() != -1.0: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/complextest_runme.py b/Examples/test-suite/python/complextest_runme.py index cc2463a39..7dd7f5a3b 100644 --- a/Examples/test-suite/python/complextest_runme.py +++ b/Examples/test-suite/python/complextest_runme.py @@ -1,17 +1,17 @@ import complextest -a = complex(-1,2) +a = complex(-1, 2) if complextest.Conj(a) != a.conjugate(): - raise RuntimeError, "bad complex mapping" + raise RuntimeError, "bad complex mapping" if complextest.Conjf(a) != a.conjugate(): - raise RuntimeError, "bad complex mapping" + raise RuntimeError, "bad complex mapping" -v = (complex(1,2), complex(2,3), complex(4,3), 1) +v = (complex(1, 2), complex(2, 3), complex(4, 3), 1) try: - complextest.Copy_h(v) + complextest.Copy_h(v) except: - pass + pass diff --git a/Examples/test-suite/python/constant_directive_runme.py b/Examples/test-suite/python/constant_directive_runme.py index 48f85ce8a..a7ed82b8b 100644 --- a/Examples/test-suite/python/constant_directive_runme.py +++ b/Examples/test-suite/python/constant_directive_runme.py @@ -1,15 +1,20 @@ import constant_directive -if not isinstance(constant_directive.TYPE1_CONSTANT1,constant_directive.Type1): - raise RuntimeError("Failure: TYPE1_CONSTANT1 type: {}".format(type(constant_directive.TYPE1_CONSTANT1))) -if not isinstance(constant_directive.getType1Instance(),constant_directive.Type1): - raise RuntimeError("Failure: getType1Instance() type: {}".format(type(constant_directive.getType1Instance()))) +if not isinstance(constant_directive.TYPE1_CONSTANT1, constant_directive.Type1): + raise RuntimeError("Failure: TYPE1_CONSTANT1 type: {}".format( + type(constant_directive.TYPE1_CONSTANT1))) +if not isinstance(constant_directive.getType1Instance(), constant_directive.Type1): + raise RuntimeError("Failure: getType1Instance() type: {}".format( + type(constant_directive.getType1Instance()))) if constant_directive.TYPE1_CONSTANT1.val != 1: - raise RuntimeError("constant_directive.TYPE1_CONSTANT1.val is %r (should be 1)" % constant_directive.TYPE1_CONSTANT1.val) + raise RuntimeError("constant_directive.TYPE1_CONSTANT1.val is %r (should be 1)" % + constant_directive.TYPE1_CONSTANT1.val) if constant_directive.TYPE1_CONSTANT2.val != 2: - raise RuntimeError("constant_directive.TYPE1_CONSTANT2.val is %r (should be 2)" % constant_directive.TYPE1_CONSTANT2.val) + raise RuntimeError("constant_directive.TYPE1_CONSTANT2.val is %r (should be 2)" % + constant_directive.TYPE1_CONSTANT2.val) if constant_directive.TYPE1_CONSTANT3.val != 3: - raise RuntimeError("constant_directive.TYPE1_CONSTANT3.val is %r (should be 3)" % constant_directive.TYPE1_CONSTANT3.val) + raise RuntimeError("constant_directive.TYPE1_CONSTANT3.val is %r (should be 3)" % + constant_directive.TYPE1_CONSTANT3.val) diff --git a/Examples/test-suite/python/constover_runme.py b/Examples/test-suite/python/constover_runme.py index 5c5419706..2d28a55cc 100644 --- a/Examples/test-suite/python/constover_runme.py +++ b/Examples/test-suite/python/constover_runme.py @@ -11,7 +11,7 @@ p = constover.test_pconst("test") if p != "test_pconst": print "test_pconst failed!" error = 1 - + f = constover.Foo() p = f.test("test") if p != "test": @@ -32,7 +32,5 @@ p = f.test_pconstm("test") if p != "test_pconstmethod": print "member-test_pconstm failed!" error = 1 - + sys.exit(error) - - diff --git a/Examples/test-suite/python/constructor_copy_runme.py b/Examples/test-suite/python/constructor_copy_runme.py index 431d3232f..a54bc106f 100644 --- a/Examples/test-suite/python/constructor_copy_runme.py +++ b/Examples/test-suite/python/constructor_copy_runme.py @@ -1,7 +1,7 @@ from constructor_copy import * -f1 = Foo1(3); -f11 = Foo1(f1); +f1 = Foo1(3) +f11 = Foo1(f1) if f1.x != f11.x: @@ -24,7 +24,7 @@ bc = Bari(bi) if (bi.x != bc.x): raise RuntimeError - + bd = Bard(5) try: @@ -35,4 +35,3 @@ except: if not good: raise RuntimeError - diff --git a/Examples/test-suite/python/contract_runme.py b/Examples/test-suite/python/contract_runme.py index 905bf1196..cd75a51d2 100644 --- a/Examples/test-suite/python/contract_runme.py +++ b/Examples/test-suite/python/contract_runme.py @@ -1,143 +1,142 @@ import contract -contract.test_preassert(1,2) +contract.test_preassert(1, 2) try: - contract.test_preassert(-1) - print "Failed! Preassertions are broken" + contract.test_preassert(-1) + print "Failed! Preassertions are broken" except: - pass + pass contract.test_postassert(3) try: - contract.test_postassert(-3) - print "Failed! Postassertions are broken" + contract.test_postassert(-3) + print "Failed! Postassertions are broken" except: - pass + pass -contract.test_prepost(2,3) -contract.test_prepost(5,-4) +contract.test_prepost(2, 3) +contract.test_prepost(5, -4) try: - contract.test_prepost(-3,4) - print "Failed! Preassertions are broken" + contract.test_prepost(-3, 4) + print "Failed! Preassertions are broken" except: - pass + pass try: - contract.test_prepost(4,-10) - print "Failed! Postassertions are broken" + contract.test_prepost(4, -10) + print "Failed! Postassertions are broken" except: - pass + pass f = contract.Foo() -f.test_preassert(4,5) +f.test_preassert(4, 5) try: - f.test_preassert(-2,3) - print "Failed! Method preassertion." + f.test_preassert(-2, 3) + print "Failed! Method preassertion." except: - pass + pass f.test_postassert(4) try: - f.test_postassert(-4) - print "Failed! Method postassertion" + f.test_postassert(-4) + print "Failed! Method postassertion" except: - pass + pass -f.test_prepost(3,4) -f.test_prepost(4,-3) +f.test_prepost(3, 4) +f.test_prepost(4, -3) try: - f.test_prepost(-4,2) - print "Failed! Method preassertion." + f.test_prepost(-4, 2) + print "Failed! Method preassertion." except: - pass + pass try: - f.test_prepost(4,-10) - print "Failed! Method postassertion." + f.test_prepost(4, -10) + print "Failed! Method postassertion." except: - pass + pass -contract.Foo_stest_prepost(4,0) +contract.Foo_stest_prepost(4, 0) try: - contract.Foo_stest_prepost(-4,2) - print "Failed! Static method preassertion" + contract.Foo_stest_prepost(-4, 2) + print "Failed! Static method preassertion" except: - pass + pass try: - contract.Foo_stest_prepost(4,-10) - print "Failed! Static method posteassertion" + contract.Foo_stest_prepost(4, -10) + print "Failed! Static method posteassertion" except: - pass - + pass + b = contract.Bar() try: - b.test_prepost(2,-4) - print "Failed! Inherited preassertion." + b.test_prepost(2, -4) + print "Failed! Inherited preassertion." except: - pass + pass d = contract.D() try: - d.foo(-1,1,1,1,1) - print "Failed! Inherited preassertion (D)." + d.foo(-1, 1, 1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.foo(1,-1,1,1,1) - print "Failed! Inherited preassertion (D)." + d.foo(1, -1, 1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.foo(1,1,-1,1,1) - print "Failed! Inherited preassertion (D)." + d.foo(1, 1, -1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.foo(1,1,1,-1,1) - print "Failed! Inherited preassertion (D)." + d.foo(1, 1, 1, -1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.foo(1,1,1,1,-1) - print "Failed! Inherited preassertion (D)." + d.foo(1, 1, 1, 1, -1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.bar(-1,1,1,1,1) - print "Failed! Inherited preassertion (D)." + d.bar(-1, 1, 1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.bar(1,-1,1,1,1) - print "Failed! Inherited preassertion (D)." + d.bar(1, -1, 1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.bar(1,1,-1,1,1) - print "Failed! Inherited preassertion (D)." + d.bar(1, 1, -1, 1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.bar(1,1,1,-1,1) - print "Failed! Inherited preassertion (D)." + d.bar(1, 1, 1, -1, 1) + print "Failed! Inherited preassertion (D)." except: - pass + pass try: - d.bar(1,1,1,1,-1) - print "Failed! Inherited preassertion (D)." + d.bar(1, 1, 1, 1, -1) + print "Failed! Inherited preassertion (D)." except: - pass + pass -#Namespace +# Namespace my = contract.myClass(1) try: - my = contract.myClass(0) - print "Failed! constructor preassertion" + my = contract.myClass(0) + print "Failed! constructor preassertion" except: - pass - + pass diff --git a/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py b/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py index 0a1c45716..363736a84 100644 --- a/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py +++ b/Examples/test-suite/python/cpp11_alternate_function_syntax_runme.py @@ -2,12 +2,13 @@ import cpp11_alternate_function_syntax a = cpp11_alternate_function_syntax.SomeStruct() -res = a.addNormal(4,5) +res = a.addNormal(4, 5) if res != 9: - raise RuntimeError, ("SomeStruct::addNormal(4,5) returns ", res, " should be 9.") + raise RuntimeError, ("SomeStruct::addNormal(4,5) returns ", + res, " should be 9.") -res = a.addAlternate(4,5) +res = a.addAlternate(4, 5) if res != 9: - raise RuntimeError, ("SomeStruct::addAlternate(4,5) returns ", res, " should be 9.") - + raise RuntimeError, ("SomeStruct::addAlternate(4,5) returns ", + res, " should be 9.") diff --git a/Examples/test-suite/python/cpp11_decltype_runme.py b/Examples/test-suite/python/cpp11_decltype_runme.py index bfcbbec79..1650d9004 100644 --- a/Examples/test-suite/python/cpp11_decltype_runme.py +++ b/Examples/test-suite/python/cpp11_decltype_runme.py @@ -3,17 +3,16 @@ import cpp11_decltype a = cpp11_decltype.A() a.i = 5 if a.i != 5: - raise RuntimeError, "Assignment to a.i failed." + raise RuntimeError, "Assignment to a.i failed." a.j = 10 if a.j != 10: - raise RuntimeError, "Assignment to a.j failed." + raise RuntimeError, "Assignment to a.j failed." b = a.foo(5) if b != 10: - raise RuntimeError, "foo(5) should return 10." + raise RuntimeError, "foo(5) should return 10." b = a.foo(6) if b != 0: - raise RuntimeError, "foo(6) should return 0." - + raise RuntimeError, "foo(6) should return 0." diff --git a/Examples/test-suite/python/cpp11_function_objects_runme.py b/Examples/test-suite/python/cpp11_function_objects_runme.py index 5a63b632b..d1515c16c 100644 --- a/Examples/test-suite/python/cpp11_function_objects_runme.py +++ b/Examples/test-suite/python/cpp11_function_objects_runme.py @@ -1,7 +1,9 @@ import cpp11_function_objects import sys + class Test1(cpp11_function_objects.Test): + def __init__(self): cpp11_function_objects.Test.__init__(self) @@ -10,14 +12,17 @@ class Test1(cpp11_function_objects.Test): t = cpp11_function_objects.Test() if t.value != 0: - raise RuntimeError("Runtime cpp11_function_objects failed. t.value should be 0, but is " + str(t.value)) + raise RuntimeError( + "Runtime cpp11_function_objects failed. t.value should be 0, but is " + str(t.value)) -t(1,2) # adds numbers and sets value +t(1, 2) # adds numbers and sets value if t.value != 3: - raise RuntimeError("Runtime cpp11_function_objects failed. t.value not changed - should be 3, but is " + str(t.value)) - + raise RuntimeError( + "Runtime cpp11_function_objects failed. t.value not changed - should be 3, but is " + str(t.value)) + t2 = Test1() -a = cpp11_function_objects.testit1(t2, 4,3) +a = cpp11_function_objects.testit1(t2, 4, 3) if a != 12: - raise RuntimeError("Runtime cpp11_function_objects failed. t.value not changed - should be 12, but is " + str(a)) + raise RuntimeError( + "Runtime cpp11_function_objects failed. t.value not changed - should be 12, but is " + str(a)) diff --git a/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py b/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py index eedf8f148..285273efa 100644 --- a/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py +++ b/Examples/test-suite/python/cpp11_initializer_list_extend_runme.py @@ -1,4 +1,3 @@ import cpp11_initializer_list_extend -c = cpp11_initializer_list_extend.Container( [10, 20, 30, 40] ) - +c = cpp11_initializer_list_extend.Container([10, 20, 30, 40]) diff --git a/Examples/test-suite/python/cpp11_initializer_list_runme.py b/Examples/test-suite/python/cpp11_initializer_list_runme.py index 395cd610d..84f955f63 100644 --- a/Examples/test-suite/python/cpp11_initializer_list_runme.py +++ b/Examples/test-suite/python/cpp11_initializer_list_runme.py @@ -2,4 +2,3 @@ import cpp11_initializer_list a = cpp11_initializer_list.A() a = cpp11_initializer_list.A(11.1) - diff --git a/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py b/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py index d304c139d..54a8fe0eb 100644 --- a/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py +++ b/Examples/test-suite/python/cpp11_null_pointer_constant_runme.py @@ -3,13 +3,15 @@ import cpp11_null_pointer_constant a = cpp11_null_pointer_constant.A() if a._myA != None: - raise RuntimeError, ("cpp11_null_pointer_constant: _myA should be None, but is ", a._myA) + raise RuntimeError, ( + "cpp11_null_pointer_constant: _myA should be None, but is ", a._myA) b = cpp11_null_pointer_constant.A() if a._myA != b._myA: - raise RuntimeError, ("cpp11_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA) + raise RuntimeError, ( + "cpp11_null_pointer_constant: a._myA should be the same as b._myA, but ", a._myA, "!=", b._myA) a._myA = cpp11_null_pointer_constant.A() if a._myA == None: - raise RuntimeError, ("cpp11_null_pointer_constant: _myA should be object, but is None") - + raise RuntimeError, ( + "cpp11_null_pointer_constant: _myA should be object, but is None") diff --git a/Examples/test-suite/python/cpp11_raw_string_literals_runme.py b/Examples/test-suite/python/cpp11_raw_string_literals_runme.py index 32282d8d8..29e53c6a7 100644 --- a/Examples/test-suite/python/cpp11_raw_string_literals_runme.py +++ b/Examples/test-suite/python/cpp11_raw_string_literals_runme.py @@ -1,50 +1,48 @@ from cpp11_raw_string_literals import * if cvar.L != 100: - raise RuntimeError + raise RuntimeError if cvar.u8 != 100: - raise RuntimeError + raise RuntimeError if cvar.u != 100: - raise RuntimeError + raise RuntimeError if UStruct.U != 100: - raise RuntimeError + raise RuntimeError if cvar.R != 100: - raise RuntimeError + raise RuntimeError if cvar.LR != 100: - raise RuntimeError + raise RuntimeError if cvar.u8R != 100: - raise RuntimeError + raise RuntimeError if cvar.uR != 100: - raise RuntimeError + raise RuntimeError if URStruct.UR != 100: - raise RuntimeError + raise RuntimeError if cvar.aa != "Wide string": - raise RuntimeError + raise RuntimeError if cvar.bb != "UTF-8 string": - raise RuntimeError, cvar.wide + raise RuntimeError, cvar.wide if cvar.xx != ")I'm an \"ascii\" \\ string.": - raise RuntimeError, cvar.xx + raise RuntimeError, cvar.xx if cvar.ee != ")I'm an \"ascii\" \\ string.": - raise RuntimeError, cvar.ee + raise RuntimeError, cvar.ee if cvar.ff != "I'm a \"raw wide\" \\ string.": - raise RuntimeError, cvar.ff + raise RuntimeError, cvar.ff if cvar.gg != "I'm a \"raw UTF-8\" \\ string.": - raise RuntimeError, cvar.gg - - + raise RuntimeError, cvar.gg diff --git a/Examples/test-suite/python/cpp11_result_of_runme.py b/Examples/test-suite/python/cpp11_result_of_runme.py index 4dc39fcdf..4469efd81 100644 --- a/Examples/test-suite/python/cpp11_result_of_runme.py +++ b/Examples/test-suite/python/cpp11_result_of_runme.py @@ -2,8 +2,10 @@ import cpp11_result_of result = cpp11_result_of.test_result(cpp11_result_of.SQUARE, 3.0) if result != 9.0: - raise RuntimeError, "test_result(square, 3.0) is not 9.0. Got: " + str(result) + raise RuntimeError, "test_result(square, 3.0) is not 9.0. Got: " + str( + result) result = cpp11_result_of.test_result_alternative1(cpp11_result_of.SQUARE, 3.0) if result != 9.0: - raise RuntimeError, "test_result_alternative1(square, 3.0) is not 9.0. Got: " + str(result) + raise RuntimeError, "test_result_alternative1(square, 3.0) is not 9.0. Got: " + str( + result) diff --git a/Examples/test-suite/python/cpp11_rvalue_reference_runme.py b/Examples/test-suite/python/cpp11_rvalue_reference_runme.py index a72a3e63b..c1cd3bf26 100644 --- a/Examples/test-suite/python/cpp11_rvalue_reference_runme.py +++ b/Examples/test-suite/python/cpp11_rvalue_reference_runme.py @@ -4,21 +4,24 @@ a = cpp11_rvalue_reference.A() a.setAcopy(5) if a.getAcopy() != 5: - raise RunTimeError, ("int A::getAcopy() value is ", a.getAcopy(), " should be 5") + raise RunTimeError, ("int A::getAcopy() value is ", + a.getAcopy(), " should be 5") ptr = a.getAptr() a.setAptr(ptr) if a.getAcopy() != 5: - raise RunTimeError, ("after A::setAptr(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") + raise RunTimeError, ("after A::setAptr(): int A::getAcopy() value is ", a.getAcopy( + ), " should be 5") a.setAref(ptr) if a.getAcopy() != 5: - raise RunTimeError, ("after A::setAref(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") + raise RunTimeError, ("after A::setAref(): int A::getAcopy() value is ", a.getAcopy( + ), " should be 5") rvalueref = a.getAmove() a.setAmove(rvalueref) if a.getAcopy() != 5: - raise RunTimeError, ("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy(), " should be 5") - + raise RunTimeError, ("after A::setAmove(): int A::getAcopy() value is ", a.getAcopy( + ), " should be 5") diff --git a/Examples/test-suite/python/cpp11_strongly_typed_enumerations_runme.py b/Examples/test-suite/python/cpp11_strongly_typed_enumerations_runme.py index 6509ba873..21b4f63f5 100644 --- a/Examples/test-suite/python/cpp11_strongly_typed_enumerations_runme.py +++ b/Examples/test-suite/python/cpp11_strongly_typed_enumerations_runme.py @@ -1,9 +1,11 @@ from cpp11_strongly_typed_enumerations import * + def enumCheck(actual, expected): - if actual != expected: - raise RuntimeError("Enum value mismatch. Expected " + str(expected) + " Actual: " + str(actual)) - return expected + 1 + if actual != expected: + raise RuntimeError( + "Enum value mismatch. Expected " + str(expected) + " Actual: " + str(actual)) + return expected + 1 val = 0 val = enumCheck(Enum1_Val1, val) @@ -161,4 +163,3 @@ enumCheck(class1.class1Test2(Class1.Enum12_Val5c), 1121) enumCheck(globalTest1(Enum1_Val5a), 13) enumCheck(globalTest2(Class1.Enum12_Val5c), 1121) #enumCheck(globalTest3(Class1.Struct1.Enum12_Val5f), 3121) - diff --git a/Examples/test-suite/python/cpp11_thread_local_runme.py b/Examples/test-suite/python/cpp11_thread_local_runme.py index 59a657488..83f2390ec 100644 --- a/Examples/test-suite/python/cpp11_thread_local_runme.py +++ b/Examples/test-suite/python/cpp11_thread_local_runme.py @@ -2,37 +2,36 @@ from cpp11_thread_local import * t = ThreadLocals() if t.stval != 11: - raise RuntimeError + raise RuntimeError if t.tsval != 22: - raise RuntimeError + raise RuntimeError if t.tscval99 != 99: - raise RuntimeError + raise RuntimeError cvar.etval = -11 if cvar.etval != -11: - raise RuntimeError + raise RuntimeError cvar.stval = -22 if cvar.stval != -22: - raise RuntimeError + raise RuntimeError cvar.tsval = -33 if cvar.tsval != -33: - raise RuntimeError + raise RuntimeError cvar.etval = -44 if cvar.etval != -44: - raise RuntimeError + raise RuntimeError cvar.teval = -55 if cvar.teval != -55: - raise RuntimeError + raise RuntimeError cvar.ectval = -66 if cvar.ectval != -66: - raise RuntimeError + raise RuntimeError cvar.ecpptval = -66 if cvar.ecpptval != -66: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/cpp11_type_traits_runme.py b/Examples/test-suite/python/cpp11_type_traits_runme.py index cb58656a6..d0dfb23d7 100644 --- a/Examples/test-suite/python/cpp11_type_traits_runme.py +++ b/Examples/test-suite/python/cpp11_type_traits_runme.py @@ -1,7 +1,7 @@ from cpp11_type_traits import * if Elaborate(0, 0) != 1: - raise RuntimeError("Elaborate should have returned 1") + raise RuntimeError("Elaborate should have returned 1") if Elaborate(0, 0.0) != 2: - raise RuntimeError("Elaborate should have returned 2") + raise RuntimeError("Elaborate should have returned 2") diff --git a/Examples/test-suite/python/cpp11_uniform_initialization_runme.py b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py index 85c3b2478..ecb468ccb 100644 --- a/Examples/test-suite/python/cpp11_uniform_initialization_runme.py +++ b/Examples/test-suite/python/cpp11_uniform_initialization_runme.py @@ -2,20 +2,20 @@ import cpp11_uniform_initialization var1 = cpp11_uniform_initialization.cvar.var1 if var1.x != 5: - raise RuntimeError + raise RuntimeError var2 = cpp11_uniform_initialization.cvar.var2 if var2.getX() != 2: - raise RuntimeError + raise RuntimeError m = cpp11_uniform_initialization.MoreInit() if m.charptr != None: - raise RuntimeError, m.charptr + raise RuntimeError, m.charptr m.charptr = "hello sir" if m.charptr != "hello sir": - raise RuntimeError, m.charptr + raise RuntimeError, m.charptr if m.more1(m.vi) != 15: - raise RuntimeError, m.vi -if m.more1( [-1,1,2] ) != 2: - raise RuntimeError, m.vi + raise RuntimeError, m.vi +if m.more1([-1, 1, 2]) != 2: + raise RuntimeError, m.vi if m.more1() != 10: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/cpp_enum_runme.py b/Examples/test-suite/python/cpp_enum_runme.py index 0054ae281..5f1e91c97 100644 --- a/Examples/test-suite/python/cpp_enum_runme.py +++ b/Examples/test-suite/python/cpp_enum_runme.py @@ -3,21 +3,21 @@ import cpp_enum f = cpp_enum.Foo() if f.hola != f.Hello: - print f.hola - raise RuntimeError + print f.hola + raise RuntimeError f.hola = f.Hi if f.hola != f.Hi: - print f.hola - raise RuntimeError + print f.hola + raise RuntimeError f.hola = f.Hello if f.hola != f.Hello: - print f.hola - raise RuntimeError + print f.hola + raise RuntimeError cpp_enum.cvar.hi = cpp_enum.Hello if cpp_enum.cvar.hi != cpp_enum.Hello: - print cpp_enum.cvar.hi - raise RuntimeError + print cpp_enum.cvar.hi + raise RuntimeError diff --git a/Examples/test-suite/python/cpp_namespace_runme.py b/Examples/test-suite/python/cpp_namespace_runme.py index a454774f5..2ab959aea 100644 --- a/Examples/test-suite/python/cpp_namespace_runme.py +++ b/Examples/test-suite/python/cpp_namespace_runme.py @@ -17,7 +17,7 @@ if cpp_namespace.do_method(t) != "Test::method": if cpp_namespace.do_method2(t) != "Test::method": raise RuntimeError("Bad return value!") - + cpp_namespace.weird("hello", 4) del t @@ -30,16 +30,14 @@ t5 = cpp_namespace.Test5() if cpp_namespace.foo3(42) != 42: raise RuntimeError("Bad return value!") -if cpp_namespace.do_method3(t2,40) != "Test2::method": +if cpp_namespace.do_method3(t2, 40) != "Test2::method": raise RuntimeError("Bad return value!") -if cpp_namespace.do_method3(t3,40) != "Test3::method": +if cpp_namespace.do_method3(t3, 40) != "Test3::method": raise RuntimeError("Bad return value!") -if cpp_namespace.do_method3(t4,40) != "Test4::method": +if cpp_namespace.do_method3(t4, 40) != "Test4::method": raise RuntimeError("Bad return value!") -if cpp_namespace.do_method3(t5,40) != "Test5::method": +if cpp_namespace.do_method3(t5, 40) != "Test5::method": raise RuntimeError("Bad return value!") - - diff --git a/Examples/test-suite/python/cpp_static_runme.py b/Examples/test-suite/python/cpp_static_runme.py index eef921780..b742de285 100644 --- a/Examples/test-suite/python/cpp_static_runme.py +++ b/Examples/test-suite/python/cpp_static_runme.py @@ -1,16 +1,17 @@ #!/usr/bin/evn python from cpp_static import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") if is_new_style_class(StaticFunctionTest): - StaticFunctionTest.static_func() - StaticFunctionTest.static_func_2(1) - StaticFunctionTest.static_func_3(1,2) + StaticFunctionTest.static_func() + StaticFunctionTest.static_func_2(1) + StaticFunctionTest.static_func_3(1, 2) else: - StaticFunctionTest().static_func() - StaticFunctionTest().static_func_2(1) - StaticFunctionTest().static_func_3(1,2) + StaticFunctionTest().static_func() + StaticFunctionTest().static_func_2(1) + StaticFunctionTest().static_func_3(1, 2) StaticMemberTest.static_int = 10 assert StaticMemberTest.static_int == 10 diff --git a/Examples/test-suite/python/default_arg_values_runme.py b/Examples/test-suite/python/default_arg_values_runme.py index 44e9a3b5e..73a738866 100644 --- a/Examples/test-suite/python/default_arg_values_runme.py +++ b/Examples/test-suite/python/default_arg_values_runme.py @@ -3,15 +3,26 @@ from default_arg_values import * d = Display() if d.draw1() != 0: - raise RuntimeError + raise RuntimeError if d.draw1(12) != 12: - raise RuntimeError + raise RuntimeError -p = createPtr(123); +p = createPtr(123) if d.draw2() != 0: - raise RuntimeError + raise RuntimeError if d.draw2(p) != 123: - raise RuntimeError + raise RuntimeError +if d.bool0() != False or type(d.bool0()) != type(False): + raise RuntimeError + +if d.bool1() != True or type(d.bool1()) != type(True): + raise RuntimeError + +if d.mybool0() != False or type(d.mybool0()) != type(False): + raise RuntimeError + +if d.mybool1() != True or type(d.mybool1()) != type(True): + raise RuntimeError diff --git a/Examples/test-suite/python/default_args_runme.py b/Examples/test-suite/python/default_args_runme.py index 25bef14ca..6610a4ec4 100644 --- a/Examples/test-suite/python/default_args_runme.py +++ b/Examples/test-suite/python/default_args_runme.py @@ -1,98 +1,140 @@ -# Note that this test is also used by python_default_args_runme.py hence the use of __main__ and the run function +# Note that this test is also used by python_default_args_runme.py hence +# the use of __main__ and the run function + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") + def run(module_name): - default_args = __import__(module_name) - ec = default_args.EnumClass() - if not ec.blah(): - raise RuntimeError("EnumClass::blah() default arguments don't work") + default_args = __import__(module_name) + ec = default_args.EnumClass() + if not ec.blah(): + raise RuntimeError("EnumClass::blah() default arguments don't work") - de = default_args.DerivedEnumClass() - de.accelerate() - de.accelerate(default_args.EnumClass.SLOW) + de = default_args.DerivedEnumClass() + de.accelerate() + de.accelerate(default_args.EnumClass.SLOW) - if default_args.Statics_staticMethod() != 60: - raise RuntimeError + if default_args.Statics_staticMethod() != 60: + raise RuntimeError - if default_args.cfunc1(1) != 2: - raise RuntimeError + if default_args.cfunc1(1) != 2: + raise RuntimeError - if default_args.cfunc2(1) != 3: - raise RuntimeError + if default_args.cfunc2(1) != 3: + raise RuntimeError - if default_args.cfunc3(1) != 4: - raise RuntimeError + if default_args.cfunc3(1) != 4: + raise RuntimeError + f = default_args.Foo() - f = default_args.Foo() + f.newname() + f.newname(1) - f.newname() - f.newname(1) + if f.double_if_void_ptr_is_null(2, None) != 4: + raise RuntimeError + if f.double_if_void_ptr_is_null(3) != 6: + raise RuntimeError - try: - f = default_args.Foo(1) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::Foo ignore is not working") + if f.double_if_handle_is_null(4, None) != 8: + raise RuntimeError - try: - f = default_args.Foo(1,2) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::Foo ignore is not working") + if f.double_if_handle_is_null(5) != 10: + raise RuntimeError - try: - f = default_args.Foo(1,2,3) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::Foo ignore is not working") + if f.double_if_dbl_ptr_is_null(6, None) != 12: + raise RuntimeError - try: - m = f.meth(1) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::meth ignore is not working") + if f.double_if_dbl_ptr_is_null(7) != 14: + raise RuntimeError - try: - m = f.meth(1,2) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::meth ignore is not working") + try: + f = default_args.Foo(1) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::Foo ignore is not working") - try: - m = f.meth(1,2,3) - error = 1 - except: - error = 0 - if error: raise RuntimeError("Foo::meth ignore is not working") + try: + f = default_args.Foo(1, 2) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::Foo ignore is not working") - if is_new_style_class(default_args.Klass): - Klass_inc = default_args.Klass.inc - else: - Klass_inc = default_args.Klass_inc + try: + f = default_args.Foo(1, 2, 3) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::Foo ignore is not working") - if Klass_inc(100, default_args.Klass(22)).val != 122: - raise RuntimeError("Klass::inc failed") + try: + m = f.meth(1) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::meth ignore is not working") - if Klass_inc(100).val != 99: - raise RuntimeError("Klass::inc failed") + try: + m = f.meth(1, 2) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::meth ignore is not working") - if Klass_inc().val != 0: - raise RuntimeError("Klass::inc failed") + try: + m = f.meth(1, 2, 3) + error = 1 + except: + error = 0 + if error: + raise RuntimeError("Foo::meth ignore is not working") - default_args.trickyvalue1(10); default_args.trickyvalue1(10, 10) - default_args.trickyvalue2(10); default_args.trickyvalue2(10, 10) - default_args.trickyvalue3(10); default_args.trickyvalue3(10, 10) - default_args.seek(); default_args.seek(10) + if is_new_style_class(default_args.Klass): + Klass_inc = default_args.Klass.inc + else: + Klass_inc = default_args.Klass_inc -if __name__=="__main__": - run('default_args') + if Klass_inc(100, default_args.Klass(22)).val != 122: + raise RuntimeError("Klass::inc failed") + if Klass_inc(100).val != 99: + raise RuntimeError("Klass::inc failed") + + if Klass_inc().val != 0: + raise RuntimeError("Klass::inc failed") + + default_args.trickyvalue1(10) + default_args.trickyvalue1(10, 10) + default_args.trickyvalue2(10) + default_args.trickyvalue2(10, 10) + default_args.trickyvalue3(10) + default_args.trickyvalue3(10, 10) + default_args.seek() + default_args.seek(10) + + if default_args.slightly_off_square(10) != 102: + raise RuntimeError + + if default_args.slightly_off_square() != 291: + raise RuntimeError + + # It is difficult to test the python:cdefaultargs feature properly as -builtin + # and -fastproxy do not use the Python layer for default args + if default_args.CDA().cdefaultargs_test1() != 1: + raise RuntimeError + + if default_args.CDA().cdefaultargs_test2() != 1: + raise RuntimeError + +if __name__ == "__main__": + run('default_args') diff --git a/Examples/test-suite/python/default_constructor_runme.py b/Examples/test-suite/python/default_constructor_runme.py index e6532031b..1e877adda 100644 --- a/Examples/test-suite/python/default_constructor_runme.py +++ b/Examples/test-suite/python/default_constructor_runme.py @@ -4,7 +4,7 @@ import _default_constructor # It uses the old static syntax (e.g., dc.new_A() rather than dc.A()), # which is not provided with the -builtin option. if _default_constructor.is_python_builtin(): - exit(0) + exit(0) dc = _default_constructor @@ -23,7 +23,7 @@ except: del_b = dc.delete_B try: - bb = dc.new_BB(); + bb = dc.new_BB() print "Whoa. new_BB created." except: pass @@ -42,7 +42,7 @@ cc = dc.new_CC() dc.delete_CC(cc) try: - d = dc.new_D(); + d = dc.new_D() print "Whoa. new_D created" except: pass @@ -89,15 +89,6 @@ except AttributeError: dc.F_destroy(f) -ff = dc.new_FFF() -try: - del_ff = dc.delete_FFF - print "Whoa. delete_FFF created" -except AttributeError: - pass - -dc.F_destroy(ff) - g = dc.new_G() try: @@ -113,5 +104,4 @@ dc.delete_GG(gg) import default_constructor -hh = default_constructor.HH(1,1) - +hh = default_constructor.HH(1, 1) diff --git a/Examples/test-suite/python/director_abstract_runme.py b/Examples/test-suite/python/director_abstract_runme.py index 886cda0ae..031c476d8 100644 --- a/Examples/test-suite/python/director_abstract_runme.py +++ b/Examples/test-suite/python/director_abstract_runme.py @@ -1,79 +1,91 @@ import director_abstract + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") + class MyFoo(director_abstract.Foo): - def __init__(self): - director_abstract.Foo.__init__(self) - def ping(self): - return "MyFoo::ping()" + + def __init__(self): + director_abstract.Foo.__init__(self) + + def ping(self): + return "MyFoo::ping()" a = MyFoo() if a.ping() != "MyFoo::ping()": - raise RuntimeError, a.ping() + raise RuntimeError, a.ping() if a.pong() != "Foo::pong();MyFoo::ping()": - raise RuntimeError, a.pong() + raise RuntimeError, a.pong() class MyExample1(director_abstract.Example1): - def Color(self, r, g, b): - return r + + def Color(self, r, g, b): + return r + class MyExample2(director_abstract.Example2): - def Color(self, r, g, b): - return g + + def Color(self, r, g, b): + return g + class MyExample3(director_abstract.Example3_i): - def Color(self, r, g, b): - return b + + def Color(self, r, g, b): + return b me1 = MyExample1() -if director_abstract.Example1_get_color(me1, 1,2,3) != 1: - raise RuntimeError +if director_abstract.Example1_get_color(me1, 1, 2, 3) != 1: + raise RuntimeError if is_new_style_class(MyExample2): - MyExample2_static = MyExample2 + MyExample2_static = MyExample2 else: - MyExample2_static = MyExample2(0, 0) -me2 = MyExample2(1,2) -if MyExample2_static.get_color(me2, 1,2,3) != 2: - raise RuntimeError + MyExample2_static = MyExample2(0, 0) +me2 = MyExample2(1, 2) +if MyExample2_static.get_color(me2, 1, 2, 3) != 2: + raise RuntimeError if is_new_style_class(MyExample3): - MyExample3_static = MyExample3 + MyExample3_static = MyExample3 else: - MyExample3_static = MyExample3() + MyExample3_static = MyExample3() me3 = MyExample3() -if MyExample3_static.get_color(me3, 1,2,3) != 3: - raise RuntimeError +if MyExample3_static.get_color(me3, 1, 2, 3) != 3: + raise RuntimeError error = 1 try: - me1 = director_abstract.Example1() + me1 = director_abstract.Example1() except: - error = 0 -if (error): raise RuntimeError + error = 0 +if (error): + raise RuntimeError error = 1 try: - me2 = director_abstract.Example2() + me2 = director_abstract.Example2() except: - error = 0 -if (error): raise RuntimeError + error = 0 +if (error): + raise RuntimeError error = 1 try: - me3 = director_abstract.Example3_i() + me3 = director_abstract.Example3_i() except: - error = 0 -if (error): raise RuntimeError + error = 0 +if (error): + raise RuntimeError try: - f = director_abstract.A.f + f = director_abstract.A.f except: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/director_alternating_runme.py b/Examples/test-suite/python/director_alternating_runme.py index a92ae1c5c..a93ffec34 100644 --- a/Examples/test-suite/python/director_alternating_runme.py +++ b/Examples/test-suite/python/director_alternating_runme.py @@ -2,4 +2,4 @@ from director_alternating import * id = getBar().id() if id != idFromGetBar(): - raise RuntimeError, "Got wrong id: " + str(id) + raise RuntimeError, "Got wrong id: " + str(id) diff --git a/Examples/test-suite/python/director_basic_runme.py b/Examples/test-suite/python/director_basic_runme.py index 541139814..6564c95a2 100644 --- a/Examples/test-suite/python/director_basic_runme.py +++ b/Examples/test-suite/python/director_basic_runme.py @@ -1,41 +1,43 @@ import director_basic + class PyFoo(director_basic.Foo): - def ping(self): - return "PyFoo::ping()" + + def ping(self): + return "PyFoo::ping()" a = PyFoo() if a.ping() != "PyFoo::ping()": - raise RuntimeError, a.ping() + raise RuntimeError, a.ping() if a.pong() != "Foo::pong();PyFoo::ping()": - raise RuntimeError, a.pong() + raise RuntimeError, a.pong() b = director_basic.Foo() if b.ping() != "Foo::ping()": - raise RuntimeError, b.ping() + raise RuntimeError, b.ping() if b.pong() != "Foo::pong();Foo::ping()": - raise RuntimeError, b.pong() + raise RuntimeError, b.pong() a = director_basic.A1(1) if a.rg(2) != 2: - raise RuntimeError - + raise RuntimeError class PyClass(director_basic.MyClass): - def method(self, vptr): - self.cmethod = 7 - pass - - def vmethod(self, b): - b.x = b.x + 31 - return b + + def method(self, vptr): + self.cmethod = 7 + pass + + def vmethod(self, b): + b.x = b.x + 31 + return b b = director_basic.Bar(3) @@ -50,49 +52,42 @@ bd = dd.cmethod(b) cc.method(b) if c.cmethod != 7: - raise RuntimeError + raise RuntimeError if bc.x != 34: - raise RuntimeError + raise RuntimeError if bd.x != 16: - raise RuntimeError - + raise RuntimeError class PyMulti(director_basic.Foo, director_basic.MyClass): - def __init__(self): - director_basic.Foo.__init__(self) - director_basic.MyClass.__init__(self) - pass - - def vmethod(self, b): - b.x = b.x + 31 - return b + def __init__(self): + director_basic.Foo.__init__(self) + director_basic.MyClass.__init__(self) + pass - - def ping(self): - return "PyFoo::ping()" + def vmethod(self, b): + b.x = b.x + 31 + return b + + def ping(self): + return "PyFoo::ping()" a = 0 -for i in range(0,100): +for i in range(0, 100): pymult = PyMulti() pymult.pong() - del pymult - + del pymult pymult = PyMulti() - - p1 = director_basic.Foo_get_self(pymult) p2 = director_basic.MyClass_get_self(pymult) p1.ping() p2.vmethod(bc) - - diff --git a/Examples/test-suite/python/director_classic_runme.py b/Examples/test-suite/python/director_classic_runme.py index 7e18a9a61..9dd5f5967 100644 --- a/Examples/test-suite/python/director_classic_runme.py +++ b/Examples/test-suite/python/director_classic_runme.py @@ -1,53 +1,76 @@ from director_classic import * + class TargetLangPerson(Person): + def __init__(self): Person.__init__(self) + def id(self): identifier = "TargetLangPerson" return identifier + class TargetLangChild(Child): + def __init__(self): Child.__init__(self) + def id(self): identifier = "TargetLangChild" return identifier + class TargetLangGrandChild(GrandChild): + def __init__(self): GrandChild.__init__(self) + def id(self): identifier = "TargetLangGrandChild" return identifier # Semis - don't override id() in target language + + class TargetLangSemiPerson(Person): + def __init__(self): Person.__init__(self) # No id() override + class TargetLangSemiChild(Child): + def __init__(self): Child.__init__(self) # No id() override + class TargetLangSemiGrandChild(GrandChild): + def __init__(self): GrandChild.__init__(self) # No id() override # Orphans - don't override id() in C++ + + class TargetLangOrphanPerson(OrphanPerson): + def __init__(self): OrphanPerson.__init__(self) + def id(self): identifier = "TargetLangOrphanPerson" return identifier + class TargetLangOrphanChild(OrphanChild): + def __init__(self): Child.__init__(self) + def id(self): identifier = "TargetLangOrphanChild" return identifier @@ -55,88 +78,90 @@ class TargetLangOrphanChild(OrphanChild): def check(person, expected): - debug = 0 - # Normal target language polymorphic call - ret = person.id() - if (debug): - print(ret) - if (ret != expected): - raise RuntimeError("Failed. Received: " + str(ret) + " Expected: " + expected) + debug = 0 + # Normal target language polymorphic call + ret = person.id() + if (debug): + print(ret) + if (ret != expected): + raise RuntimeError( + "Failed. Received: " + str(ret) + " Expected: " + expected) - # Polymorphic call from C++ - caller = Caller() - caller.setCallback(person) - ret = caller.call() - if (debug): - print(ret) - if (ret != expected): - raise RuntimeError("Failed. Received: " + str(ret) + " Expected: " + expected) + # Polymorphic call from C++ + caller = Caller() + caller.setCallback(person) + ret = caller.call() + if (debug): + print(ret) + if (ret != expected): + raise RuntimeError( + "Failed. Received: " + str(ret) + " Expected: " + expected) - # Polymorphic call of object created in target language and passed to C++ and back again - baseclass = caller.baseClass() - ret = baseclass.id() - if (debug): - print(ret) - if (ret != expected): - raise RuntimeError("Failed. Received: " + str(ret)+ " Expected: " + expected) + # Polymorphic call of object created in target language and passed to C++ + # and back again + baseclass = caller.baseClass() + ret = baseclass.id() + if (debug): + print(ret) + if (ret != expected): + raise RuntimeError( + "Failed. Received: " + str(ret) + " Expected: " + expected) - caller.resetCallback() - if (debug): - print("----------------------------------------") + caller.resetCallback() + if (debug): + print("----------------------------------------") - -person = Person(); -check(person, "Person"); +person = Person() +check(person, "Person") del person -person = Child(); -check(person, "Child"); +person = Child() +check(person, "Child") del person -person = GrandChild(); -check(person, "GrandChild"); +person = GrandChild() +check(person, "GrandChild") del person -person = TargetLangPerson(); -check(person, "TargetLangPerson"); +person = TargetLangPerson() +check(person, "TargetLangPerson") del person -person = TargetLangChild(); -check(person, "TargetLangChild"); +person = TargetLangChild() +check(person, "TargetLangChild") del person -person = TargetLangGrandChild(); -check(person, "TargetLangGrandChild"); +person = TargetLangGrandChild() +check(person, "TargetLangGrandChild") del person # Semis - don't override id() in target language -person = TargetLangSemiPerson(); -check(person, "Person"); +person = TargetLangSemiPerson() +check(person, "Person") del person -person = TargetLangSemiChild(); -check(person, "Child"); +person = TargetLangSemiChild() +check(person, "Child") del person -person = TargetLangSemiGrandChild(); -check(person, "GrandChild"); +person = TargetLangSemiGrandChild() +check(person, "GrandChild") del person # Orphans - don't override id() in C++ -person = OrphanPerson(); -check(person, "Person"); +person = OrphanPerson() +check(person, "Person") del person -person = OrphanChild(); -check(person, "Child"); +person = OrphanChild() +check(person, "Child") del person -person = TargetLangOrphanPerson(); -check(person, "TargetLangOrphanPerson"); +person = TargetLangOrphanPerson() +check(person, "TargetLangOrphanPerson") del person -person = TargetLangOrphanChild(); -check(person, "TargetLangOrphanChild"); +person = TargetLangOrphanChild() +check(person, "TargetLangOrphanChild") del person - diff --git a/Examples/test-suite/python/director_detect_runme.py b/Examples/test-suite/python/director_detect_runme.py index a90cfe8b4..345051982 100644 --- a/Examples/test-suite/python/director_detect_runme.py +++ b/Examples/test-suite/python/director_detect_runme.py @@ -1,24 +1,26 @@ -import director_detect +import director_detect + class MyBar(director_detect.Bar): - def __init__(self, val = 2): - director_detect.Bar.__init__(self) - self.val = val - def get_value(self): - self.val = self.val + 1 - return self.val - - def get_class(self): - self.val = self.val + 1 - return director_detect.A() + def __init__(self, val=2): + director_detect.Bar.__init__(self) + self.val = val - def just_do_it(self): - self.val = self.val + 1 + def get_value(self): + self.val = self.val + 1 + return self.val - def clone(self): - return MyBar(self.val) - pass + def get_class(self): + self.val = self.val + 1 + return director_detect.A() + + def just_do_it(self): + self.val = self.val + 1 + + def clone(self): + return MyBar(self.val) + pass b = MyBar() @@ -33,4 +35,4 @@ c = b.clone() vc = c.get_value() if (v != 3) or (b.val != 5) or (vc != 6): - raise RuntimeError,"Bad virtual detection" + raise RuntimeError, "Bad virtual detection" diff --git a/Examples/test-suite/python/director_enum_runme.py b/Examples/test-suite/python/director_enum_runme.py index 5692c88b8..faa2d82df 100644 --- a/Examples/test-suite/python/director_enum_runme.py +++ b/Examples/test-suite/python/director_enum_runme.py @@ -1,12 +1,14 @@ import director_enum + class MyFoo(director_enum.Foo): - def say_hi(self, val): - return val + + def say_hi(self, val): + return val b = director_enum.Foo() a = MyFoo() if a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/director_exception_runme.py b/Examples/test-suite/python/director_exception_runme.py index de3ef22a5..892c7e653 100644 --- a/Examples/test-suite/python/director_exception_runme.py +++ b/Examples/test-suite/python/director_exception_runme.py @@ -1,21 +1,29 @@ from director_exception import * + class MyException(Exception): - def __init__(self, a, b): - self.msg = a + b + + def __init__(self, a, b): + self.msg = a + b + class MyFoo(Foo): - def ping(self): - raise NotImplementedError, "MyFoo::ping() EXCEPTION" + + def ping(self): + raise NotImplementedError, "MyFoo::ping() EXCEPTION" + class MyFoo2(Foo): - def ping(self): - return True - pass # error: should return a string + + def ping(self): + return True + pass # error: should return a string + class MyFoo3(Foo): - def ping(self): - raise MyException("foo", "bar") + + def ping(self): + raise MyException("foo", "bar") # Check that the NotImplementedError raised by MyFoo.ping() is returned by # MyFoo.pong(). @@ -23,16 +31,16 @@ ok = 0 a = MyFoo() b = launder(a) try: - b.pong() + b.pong() except NotImplementedError, e: - if str(e) == "MyFoo::ping() EXCEPTION": - ok = 1 - else: - print "Unexpected error message: %s" % str(e) + if str(e) == "MyFoo::ping() EXCEPTION": + ok = 1 + else: + print "Unexpected error message: %s" % str(e) except: - pass + pass if not ok: - raise RuntimeError + raise RuntimeError # Check that the director returns the appropriate TypeError if the return type @@ -41,14 +49,14 @@ ok = 0 a = MyFoo2() b = launder(a) try: - b.pong() + b.pong() except TypeError, e: - if str(e) == "SWIG director type mismatch in output value of type 'std::string'": - ok = 1 - else: - print "Unexpected error message: %s" % str(e) + if str(e) == "SWIG director type mismatch in output value of type 'std::string'": + ok = 1 + else: + print "Unexpected error message: %s" % str(e) if not ok: - raise RuntimeError + raise RuntimeError # Check that the director can return an exception which requires two arguments @@ -57,24 +65,24 @@ ok = 0 a = MyFoo3() b = launder(a) try: - b.pong() + b.pong() except MyException, e: - if e.msg == 'foobar': - ok = 1 - else: - print "Unexpected error message: %s" % str(e) + if e.msg == 'foobar': + ok = 1 + else: + print "Unexpected error message: %s" % str(e) if not ok: - raise RuntimeError + raise RuntimeError # This is expected to fail with -builtin option # Throwing builtin classes as exceptions not supported if not is_python_builtin(): - try: - raise Exception2() - except Exception2: - pass + try: + raise Exception2() + except Exception2: + pass - try: - raise Exception1() - except Exception1: - pass + try: + raise Exception1() + except Exception1: + pass diff --git a/Examples/test-suite/python/director_extend_runme.py b/Examples/test-suite/python/director_extend_runme.py index 1ab58676a..a5aad8245 100644 --- a/Examples/test-suite/python/director_extend_runme.py +++ b/Examples/test-suite/python/director_extend_runme.py @@ -1,20 +1,22 @@ # Test case from bug #1506850 #"When threading is enabled, the interpreter will infinitely wait on a mutex the second -#time this type of extended method is called. Attached is an example -#program that waits on the mutex to be unlocked." +# time this type of extended method is called. Attached is an example +# program that waits on the mutex to be unlocked." from director_extend import * + class MyObject(SpObject): + def __init__(self): SpObject.__init__(self) return def getFoo(self): return 123 - + m = MyObject() if m.dummy() != 666: - raise RuntimeError, "1st call" + raise RuntimeError, "1st call" if m.dummy() != 666: # Locked system - raise RuntimeError, "2nd call" + raise RuntimeError, "2nd call" diff --git a/Examples/test-suite/python/director_finalizer_runme.py b/Examples/test-suite/python/director_finalizer_runme.py index 4cd1f573e..9c9eed693 100644 --- a/Examples/test-suite/python/director_finalizer_runme.py +++ b/Examples/test-suite/python/director_finalizer_runme.py @@ -1,10 +1,14 @@ from director_finalizer import * + class MyFoo(Foo): - def __del__(self): - self.orStatus(2) - try: Foo.__del__(self) - except: pass + + def __del__(self): + self.orStatus(2) + try: + Foo.__del__(self) + except: + pass resetStatus() @@ -13,7 +17,7 @@ a = MyFoo() del a if getStatus() != 3: - raise RuntimeError + raise RuntimeError resetStatus() @@ -21,12 +25,12 @@ a = MyFoo() launder(a) if getStatus() != 0: - raise RuntimeError + raise RuntimeError del a if getStatus() != 3: - raise RuntimeError + raise RuntimeError resetStatus() @@ -34,15 +38,14 @@ a = MyFoo().__disown__() deleteFoo(a) if getStatus() != 3: - raise RuntimeError - + raise RuntimeError + resetStatus() a = MyFoo().__disown__() deleteFoo(launder(a)) if getStatus() != 3: - raise RuntimeError - -resetStatus() + raise RuntimeError +resetStatus() diff --git a/Examples/test-suite/python/director_frob_runme.py b/Examples/test-suite/python/director_frob_runme.py index c2dd734cf..0ef4ad900 100644 --- a/Examples/test-suite/python/director_frob_runme.py +++ b/Examples/test-suite/python/director_frob_runme.py @@ -1,7 +1,7 @@ from director_frob import * -foo = Bravo(); -s = foo.abs_method(); +foo = Bravo() +s = foo.abs_method() if s != "Bravo::abs_method()": - raise RuntimeError, s + raise RuntimeError, s diff --git a/Examples/test-suite/python/director_keywords_runme.py b/Examples/test-suite/python/director_keywords_runme.py index 03a50206a..495d9375e 100644 --- a/Examples/test-suite/python/director_keywords_runme.py +++ b/Examples/test-suite/python/director_keywords_runme.py @@ -2,4 +2,3 @@ from director_keywords import * f = Foo() f.check_self(20) - diff --git a/Examples/test-suite/python/director_nested_runme.py b/Examples/test-suite/python/director_nested_runme.py index cff82f55b..f3d973630 100644 --- a/Examples/test-suite/python/director_nested_runme.py +++ b/Examples/test-suite/python/director_nested_runme.py @@ -2,62 +2,63 @@ from director_nested import * class A(FooBar_int): - def do_step(self): - return "A::do_step;" - - def get_value(self): - return "A::get_value" - pass + def do_step(self): + return "A::do_step;" + + def get_value(self): + return "A::get_value" + + pass a = A() if a.step() != "Bar::step;Foo::advance;Bar::do_advance;A::do_step;": - raise RuntimeError,"Bad A virtual resolution" + raise RuntimeError, "Bad A virtual resolution" class B(FooBar_int): - def do_advance(self): - return "B::do_advance;" + self.do_step() - def do_step(self): - return "B::do_step;" - - def get_value(self): - return 1 + def do_advance(self): + return "B::do_advance;" + self.do_step() - pass + def do_step(self): + return "B::do_step;" + + def get_value(self): + return 1 + + pass b = B() if b.step() != "Bar::step;Foo::advance;B::do_advance;B::do_step;": - raise RuntimeError,"Bad B virtual resolution" - + raise RuntimeError, "Bad B virtual resolution" class C(FooBar_int): - def do_advance(self): - return "C::do_advance;" + FooBar_int.do_advance(self) - def do_step(self): - return "C::do_step;" - - def get_value(self): - return 2 + def do_advance(self): + return "C::do_advance;" + FooBar_int.do_advance(self) - def get_name(self): - return FooBar_int.get_name(self) + " hello" + def do_step(self): + return "C::do_step;" - - pass + def get_value(self): + return 2 + + def get_name(self): + return FooBar_int.get_name(self) + " hello" + + pass cc = C() c = FooBar_int_get_self(cc) c.advance() if c.get_name() != "FooBar::get_name hello": - raise RuntimeError + raise RuntimeError if c.name() != "FooBar::get_name hello": - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/director_profile_runme.py b/Examples/test-suite/python/director_profile_runme.py index 2f67481f5..035007c61 100644 --- a/Examples/test-suite/python/director_profile_runme.py +++ b/Examples/test-suite/python/director_profile_runme.py @@ -1,9 +1,10 @@ import director_profile -class MyB(director_profile.B): - def vfi(self, a): - return a+3 +class MyB(director_profile.B): + + def vfi(self, a): + return a + 3 a = director_profile.A() @@ -15,27 +16,26 @@ fi = b.fi i = 50000 a = 1 while i: - a = fi(a) #1 - a = fi(a) #2 - a = fi(a) #3 - a = fi(a) #4 - a = fi(a) #5 - a = fi(a) #6 - a = fi(a) #7 - a = fi(a) #8 - a = fi(a) #9 - a = fi(a) #10 - a = fi(a) #1 - a = fi(a) #2 - a = fi(a) #3 - a = fi(a) #4 - a = fi(a) #5 - a = fi(a) #6 - a = fi(a) #7 - a = fi(a) #8 - a = fi(a) #9 - a = fi(a) #20 - i -= 1 + a = fi(a) # 1 + a = fi(a) # 2 + a = fi(a) # 3 + a = fi(a) # 4 + a = fi(a) # 5 + a = fi(a) # 6 + a = fi(a) # 7 + a = fi(a) # 8 + a = fi(a) # 9 + a = fi(a) # 10 + a = fi(a) # 1 + a = fi(a) # 2 + a = fi(a) # 3 + a = fi(a) # 4 + a = fi(a) # 5 + a = fi(a) # 6 + a = fi(a) # 7 + a = fi(a) # 8 + a = fi(a) # 9 + a = fi(a) # 20 + i -= 1 print a - diff --git a/Examples/test-suite/python/director_property_runme.py b/Examples/test-suite/python/director_property_runme.py index 303e53b67..5d713c27f 100644 --- a/Examples/test-suite/python/director_property_runme.py +++ b/Examples/test-suite/python/director_property_runme.py @@ -1,18 +1,19 @@ import director_property -class PyFoo(director_property.Foo): - a = property(director_property.Foo.getA, director_property.Foo.setA) - def ping(self): - return "PyFoo::ping()" +class PyFoo(director_property.Foo): + a = property(director_property.Foo.getA, director_property.Foo.setA) + + def ping(self): + return "PyFoo::ping()" foo = PyFoo() foo.setA("BLABLA") if foo.getA() != "BLABLA": - raise RuntimeError + raise RuntimeError foo.a = "BIBI" if foo.a != "BIBI": - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/director_protected_runme.py b/Examples/test-suite/python/director_protected_runme.py index fd3c868a1..c3118a7c0 100644 --- a/Examples/test-suite/python/director_protected_runme.py +++ b/Examples/test-suite/python/director_protected_runme.py @@ -1,129 +1,132 @@ from director_protected import * - class FooBar(Bar): - def ping(self): - return "FooBar::ping();" + + def ping(self): + return "FooBar::ping();" + class FooBar2(Bar): - def ping(self): - return "FooBar2::ping();" - def pang(self): - return "FooBar2::pang();" + + def ping(self): + return "FooBar2::ping();" + + def pang(self): + return "FooBar2::pang();" + class FooBar3(Bar): - def cheer(self): - return "FooBar3::cheer();" + + def cheer(self): + return "FooBar3::cheer();" -b = Bar() -f = b.create() +b = Bar() +f = b.create() fb = FooBar() fb2 = FooBar2() fb3 = FooBar3() try: - s = fb.used() - if s != "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();": - raise RuntimeError - pass + s = fb.used() + if s != "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();": + raise RuntimeError + pass except: - raise RuntimeError, "bad FooBar::used" + raise RuntimeError, "bad FooBar::used" try: - s = fb2.used() - if s != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();": - raise RuntimeError - pass + s = fb2.used() + if s != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();": + raise RuntimeError + pass except: - raise RuntimeError, "bad FooBar2::used" + raise RuntimeError, "bad FooBar2::used" try: - s = b.pong() - if s != "Bar::pong();Foo::pong();Bar::ping();": - raise RuntimeError - pass + s = b.pong() + if s != "Bar::pong();Foo::pong();Bar::ping();": + raise RuntimeError + pass except: - raise RuntimeError, "bad Bar::pong" + raise RuntimeError, "bad Bar::pong" try: - s = f.pong() - if s != "Bar::pong();Foo::pong();Bar::ping();": - raise RuntimeError - pass + s = f.pong() + if s != "Bar::pong();Foo::pong();Bar::ping();": + raise RuntimeError + pass except: - raise RuntimeError," bad Foo::pong" - -try: - s = fb.pong() - if s != "Bar::pong();Foo::pong();FooBar::ping();": - raise RuntimeError - pass -except: - raise RuntimeError," bad FooBar::pong" + raise RuntimeError, " bad Foo::pong" -protected=1 try: - b.ping() - protected=0 + s = fb.pong() + if s != "Bar::pong();Foo::pong();FooBar::ping();": + raise RuntimeError + pass except: - pass + raise RuntimeError, " bad FooBar::pong" + +protected = 1 +try: + b.ping() + protected = 0 +except: + pass if not protected: - raise RuntimeError,"Foo::ping is protected" - -protected=1 + raise RuntimeError, "Foo::ping is protected" + +protected = 1 try: - f.ping() - protected=0 + f.ping() + protected = 0 except: - pass + pass if not protected: - raise RuntimeError,"Foo::ping is protected" + raise RuntimeError, "Foo::ping is protected" -protected=1 +protected = 1 try: - f.pang() - protected=0 + f.pang() + protected = 0 except: - pass + pass if not protected: - raise RuntimeError,"FooBar::pang is protected" + raise RuntimeError, "FooBar::pang is protected" -protected=1 +protected = 1 try: - b.cheer() - protected=0 + b.cheer() + protected = 0 except: - pass + pass if not protected: - raise RuntimeError,"Bar::cheer is protected" + raise RuntimeError, "Bar::cheer is protected" -protected=1 +protected = 1 try: - f.cheer() - protected=0 + f.cheer() + protected = 0 except: - pass + pass if not protected: - raise RuntimeError,"Foo::cheer is protected" + raise RuntimeError, "Foo::cheer is protected" if fb3.cheer() != "FooBar3::cheer();": - raise RuntimeError, "bad fb3::cheer" + raise RuntimeError, "bad fb3::cheer" if fb2.callping() != "FooBar2::ping();": - raise RuntimeError, "bad fb2.callping" + raise RuntimeError, "bad fb2.callping" if fb2.callcheer() != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();": - raise RuntimeError, "bad fb2.callcheer" + raise RuntimeError, "bad fb2.callcheer" if fb3.callping() != "Bar::ping();": - raise RuntimeError, "bad fb3.callping" + raise RuntimeError, "bad fb3.callping" if fb3.callcheer() != "FooBar3::cheer();": - raise RuntimeError, "bad fb3.callcheer" - - + raise RuntimeError, "bad fb3.callcheer" diff --git a/Examples/test-suite/python/director_stl_runme.py b/Examples/test-suite/python/director_stl_runme.py index aaea0362a..0c3e5af97 100644 --- a/Examples/test-suite/python/director_stl_runme.py +++ b/Examples/test-suite/python/director_stl_runme.py @@ -1,20 +1,22 @@ import director_stl + class MyFoo(director_stl.Foo): - def ping(self, s): - return "MyFoo::ping():" + s - def pident(self, arg): - return arg - - def vident(self,v): - return v + def ping(self, s): + return "MyFoo::ping():" + s - def vidents(self,v): - return v + def pident(self, arg): + return arg - def vsecond(self,v1,v2): - return v2 + def vident(self, v): + return v + + def vidents(self, v): + return v + + def vsecond(self, v1, v2): + return v2 a = MyFoo() @@ -22,18 +24,18 @@ a = MyFoo() a.tping("hello") a.tpong("hello") -p = (1,2) +p = (1, 2) a.pident(p) -v = (3,4) +v = (3, 4) a.vident(v) a.tpident(p) a.tvident(v) -v1 = (3,4) -v2 = (5,6) -a.tvsecond(v1,v2) +v1 = (3, 4) +v2 = (5, 6) +a.tvsecond(v1, v2) -vs=("hi", "hello") +vs = ("hi", "hello") vs a.tvidents(vs) diff --git a/Examples/test-suite/python/director_string_runme.py b/Examples/test-suite/python/director_string_runme.py index f2db416ca..dcd47d647 100644 --- a/Examples/test-suite/python/director_string_runme.py +++ b/Examples/test-suite/python/director_string_runme.py @@ -1,29 +1,29 @@ from director_string import * + class B(A): - def __init__(self,string): - A.__init__(self,string) - def get_first(self): - return A.get_first(self) + " world!" + def __init__(self, string): + A.__init__(self, string) - def process_text(self, string): - A.process_text(self, string) - self.smem = "hello" - + def get_first(self): + return A.get_first(self) + " world!" + + def process_text(self, string): + A.process_text(self, string) + self.smem = "hello" b = B("hello") b.get(0) if b.get_first() != "hello world!": - print b.get_first() - raise RuntimeError + print b.get_first() + raise RuntimeError b.call_process_func() if b.smem != "hello": - print smem - raise RuntimeError - + print smem + raise RuntimeError diff --git a/Examples/test-suite/python/director_thread_runme.py b/Examples/test-suite/python/director_thread_runme.py index 15a12ab80..4fcf3bfd1 100644 --- a/Examples/test-suite/python/director_thread_runme.py +++ b/Examples/test-suite/python/director_thread_runme.py @@ -1,6 +1,8 @@ from director_thread import Foo -class Derived(Foo) : + +class Derived(Foo): + def __init__(self): Foo.__init__(self) diff --git a/Examples/test-suite/python/director_unroll_runme.py b/Examples/test-suite/python/director_unroll_runme.py index e2bc93779..60bc05585 100644 --- a/Examples/test-suite/python/director_unroll_runme.py +++ b/Examples/test-suite/python/director_unroll_runme.py @@ -1,8 +1,10 @@ import director_unroll + class MyFoo(director_unroll.Foo): - def ping(self): - return "MyFoo::ping()" + + def ping(self): + return "MyFoo::ping()" a = MyFoo() @@ -14,6 +16,5 @@ c = b.get() if not (a.this == c.this): - print a, c - raise RuntimeError - + print a, c + raise RuntimeError diff --git a/Examples/test-suite/python/director_wstring_runme.py b/Examples/test-suite/python/director_wstring_runme.py index f3f29de5e..242b27582 100644 --- a/Examples/test-suite/python/director_wstring_runme.py +++ b/Examples/test-suite/python/director_wstring_runme.py @@ -1,28 +1,28 @@ from director_wstring import * + class B(A): - def __init__(self,string): - A.__init__(self,string) - def get_first(self): - return A.get_first(self) + u" world!" + def __init__(self, string): + A.__init__(self, string) - def process_text(self, string): - self.smem = u"hello" - + def get_first(self): + return A.get_first(self) + u" world!" + + def process_text(self, string): + self.smem = u"hello" b = B(u"hello") b.get(0) if b.get_first() != u"hello world!": - print b.get_first() - raise RuntimeError + print b.get_first() + raise RuntimeError b.call_process_func() if b.smem != u"hello": - print smem - raise RuntimeError - + print smem + raise RuntimeError diff --git a/Examples/test-suite/python/disown_runme.py b/Examples/test-suite/python/disown_runme.py index b8cae077a..1f355f040 100644 --- a/Examples/test-suite/python/disown_runme.py +++ b/Examples/test-suite/python/disown_runme.py @@ -14,7 +14,7 @@ if (not a.thisown): a.thisown = tmp if (a.thisown != tmp): - raise RuntimeError + raise RuntimeError b = B() diff --git a/Examples/test-suite/python/dynamic_cast_runme.py b/Examples/test-suite/python/dynamic_cast_runme.py index 68b06db50..59e86d34c 100644 --- a/Examples/test-suite/python/dynamic_cast_runme.py +++ b/Examples/test-suite/python/dynamic_cast_runme.py @@ -9,4 +9,3 @@ y = b.blah() a = dynamic_cast.do_test(y) if a != "Bar::test": print "Failed!!" - diff --git a/Examples/test-suite/python/enum_forward_runme.py b/Examples/test-suite/python/enum_forward_runme.py index 9af476f97..130ba715b 100644 --- a/Examples/test-suite/python/enum_forward_runme.py +++ b/Examples/test-suite/python/enum_forward_runme.py @@ -1,10 +1,10 @@ import enum_forward - -f1 = enum_forward.get_enum1(); -f1 = enum_forward.test_function1(f1); -f2 = enum_forward.get_enum2(); -f2 = enum_forward.test_function2(f2); +f1 = enum_forward.get_enum1() +f1 = enum_forward.test_function1(f1) -f3 = enum_forward.get_enum3(); -f3 = enum_forward.test_function3(f3); +f2 = enum_forward.get_enum2() +f2 = enum_forward.test_function2(f2) + +f3 = enum_forward.get_enum3() +f3 = enum_forward.test_function3(f3) diff --git a/Examples/test-suite/python/enum_template_runme.py b/Examples/test-suite/python/enum_template_runme.py index 6ad0a8060..64d06ce87 100644 --- a/Examples/test-suite/python/enum_template_runme.py +++ b/Examples/test-suite/python/enum_template_runme.py @@ -1,7 +1,6 @@ import enum_template if enum_template.MakeETest() != 1: - raise RuntimeError + raise RuntimeError if enum_template.TakeETest(0) != None: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/enums_runme.py b/Examples/test-suite/python/enums_runme.py index 8d491baf4..4870d7c52 100644 --- a/Examples/test-suite/python/enums_runme.py +++ b/Examples/test-suite/python/enums_runme.py @@ -6,14 +6,13 @@ _enums.bar3(1) _enums.bar1(1) if _enums.cvar.enumInstance != 2: - raise RuntimeError + raise RuntimeError if _enums.cvar.Slap != 10: - raise RuntimeError + raise RuntimeError if _enums.cvar.Mine != 11: - raise RuntimeError + raise RuntimeError if _enums.cvar.Thigh != 12: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/exception_order_runme.py b/Examples/test-suite/python/exception_order_runme.py index 8f095eb98..c53521e3e 100644 --- a/Examples/test-suite/python/exception_order_runme.py +++ b/Examples/test-suite/python/exception_order_runme.py @@ -3,43 +3,42 @@ from exception_order import * # This test is expected to fail with -builtin option. # Throwing builtin classes as exceptions not supported if is_python_builtin(): - exit(0) + exit(0) a = A() try: - a.foo() -except E1,e: - pass + a.foo() +except E1, e: + pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError, "bad exception order" try: - a.bar() -except E2,e: - pass + a.bar() +except E2, e: + pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError, "bad exception order" try: - a.foobar() -except RuntimeError,e: - if e.args[0] != "postcatch unknown": - print "bad exception order", - raise RuntimeError, e.args - + a.foobar() +except RuntimeError, e: + if e.args[0] != "postcatch unknown": + print "bad exception order", + raise RuntimeError, e.args try: - a.barfoo(1) -except E1,e: - pass + a.barfoo(1) +except E1, e: + pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError, "bad exception order" try: - a.barfoo(2) -except E2,e: - pass + a.barfoo(2) +except E2, e: + pass except: - raise RuntimeError, "bad exception order" + raise RuntimeError, "bad exception order" diff --git a/Examples/test-suite/python/extend_placement_runme.py b/Examples/test-suite/python/extend_placement_runme.py index 97b7b1654..2c0be2c31 100644 --- a/Examples/test-suite/python/extend_placement_runme.py +++ b/Examples/test-suite/python/extend_placement_runme.py @@ -2,12 +2,12 @@ import extend_placement foo = extend_placement.Foo() foo = extend_placement.Foo(1) -foo = extend_placement.Foo(1,1) +foo = extend_placement.Foo(1, 1) foo.spam() foo.spam("hello") foo.spam(1) -foo.spam(1,1) -foo.spam(1,1,1) +foo.spam(1, 1) +foo.spam(1, 1, 1) foo.spam(extend_placement.Foo()) foo.spam(extend_placement.Foo(), 1.0) @@ -17,20 +17,20 @@ bar = extend_placement.Bar(1) bar.spam() bar.spam("hello") bar.spam(1) -bar.spam(1,1) -bar.spam(1,1,1) +bar.spam(1, 1) +bar.spam(1, 1, 1) bar.spam(extend_placement.Bar()) bar.spam(extend_placement.Bar(), 1.0) foo = extend_placement.FooTi() foo = extend_placement.FooTi(1) -foo = extend_placement.FooTi(1,1) +foo = extend_placement.FooTi(1, 1) foo.spam() foo.spam("hello") foo.spam(1) -foo.spam(1,1) -foo.spam(1,1,1) +foo.spam(1, 1) +foo.spam(1, 1, 1) foo.spam(extend_placement.Foo()) foo.spam(extend_placement.Foo(), 1.0) @@ -40,7 +40,7 @@ bar = extend_placement.BarTi(1) bar.spam() bar.spam("hello") bar.spam(1) -bar.spam(1,1) -bar.spam(1,1,1) +bar.spam(1, 1) +bar.spam(1, 1, 1) bar.spam(extend_placement.Bar()) bar.spam(extend_placement.Bar(), 1.0) diff --git a/Examples/test-suite/python/extern_c_runme.py b/Examples/test-suite/python/extern_c_runme.py index 1a6d2aa12..91a218a87 100644 --- a/Examples/test-suite/python/extern_c_runme.py +++ b/Examples/test-suite/python/extern_c_runme.py @@ -1,4 +1,3 @@ import extern_c extern_c.RealFunction(2) - diff --git a/Examples/test-suite/python/file_test_runme.py b/Examples/test-suite/python/file_test_runme.py index 9b94fa3b3..33ada500b 100644 --- a/Examples/test-suite/python/file_test_runme.py +++ b/Examples/test-suite/python/file_test_runme.py @@ -2,7 +2,7 @@ import sys import file_test if sys.version_info[0:2] < (3, 0): - file_test.nfile(sys.stdout) + file_test.nfile(sys.stdout) cstdout = file_test.GetStdOut() diff --git a/Examples/test-suite/python/friends_runme.py b/Examples/test-suite/python/friends_runme.py index 04897655a..2d377fdd1 100644 --- a/Examples/test-suite/python/friends_runme.py +++ b/Examples/test-suite/python/friends_runme.py @@ -2,27 +2,36 @@ import friends a = friends.A(2) -if friends.get_val1(a) != 2: raise RuntimeError -if friends.get_val2(a) != 4: raise RuntimeError -if friends.get_val3(a) != 6: raise RuntimeError +if friends.get_val1(a) != 2: + raise RuntimeError +if friends.get_val2(a) != 4: + raise RuntimeError +if friends.get_val3(a) != 6: + raise RuntimeError # nice overload working fine -if friends.get_val1(1,2,3) != 1: raise RuntimeError +if friends.get_val1(1, 2, 3) != 1: + raise RuntimeError b = friends.B(3) # David's case -if friends.mix(a,b) != 5: raise RuntimeError +if friends.mix(a, b) != 5: + raise RuntimeError di = friends.D_d(2) dd = friends.D_d(3.3) # incredible template overloading working just fine -if friends.get_val1(di) != 2: raise RuntimeError -if friends.get_val1(dd) != 3.3: raise RuntimeError +if friends.get_val1(di) != 2: + raise RuntimeError +if friends.get_val1(dd) != 3.3: + raise RuntimeError friends.set(di, 4) friends.set(dd, 1.3) -if friends.get_val1(di) != 4: raise RuntimeError -if friends.get_val1(dd) != 1.3: raise RuntimeError +if friends.get_val1(di) != 4: + raise RuntimeError +if friends.get_val1(dd) != 1.3: + raise RuntimeError diff --git a/Examples/test-suite/python/funcptr_cpp_runme.py b/Examples/test-suite/python/funcptr_cpp_runme.py index ae8616e94..08e85ad7b 100644 --- a/Examples/test-suite/python/funcptr_cpp_runme.py +++ b/Examples/test-suite/python/funcptr_cpp_runme.py @@ -1,9 +1,8 @@ from funcptr_cpp import * if call1(ADD_BY_VALUE, 10, 11) != 21: - raise RuntimeError + raise RuntimeError if call2(ADD_BY_POINTER, 12, 13) != 25: - raise RuntimeError + raise RuntimeError if call3(ADD_BY_REFERENCE, 14, 15) != 29: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/fvirtual_runme.py b/Examples/test-suite/python/fvirtual_runme.py index ada3313de..99f5dc6b0 100644 --- a/Examples/test-suite/python/fvirtual_runme.py +++ b/Examples/test-suite/python/fvirtual_runme.py @@ -2,8 +2,7 @@ from fvirtual import * sw = NodeSwitch() n = Node() -i = sw.addChild(n); +i = sw.addChild(n) if i != 2: - raise RuntimeError, "addChild" - + raise RuntimeError, "addChild" diff --git a/Examples/test-suite/python/global_functions_runme.py b/Examples/test-suite/python/global_functions_runme.py index 17b70b725..f411261b6 100644 --- a/Examples/test-suite/python/global_functions_runme.py +++ b/Examples/test-suite/python/global_functions_runme.py @@ -1,52 +1,52 @@ from global_functions import * + def check(a, b): - if a != b: - raise RuntimeError("Failed: " + str(a) + " != " + str(b)) + if a != b: + raise RuntimeError("Failed: " + str(a) + " != " + str(b)) global_void() check(global_one(1), 1) check(global_two(2, 2), 4) fail = True try: - global_void(1) + global_void(1) except TypeError, e: - fail = False + fail = False if fail: - raise RuntimeError("argument count check failed") + raise RuntimeError("argument count check failed") fail = True try: - global_one() + global_one() except TypeError, e: - fail = False + fail = False if fail: - raise RuntimeError("argument count check failed") + raise RuntimeError("argument count check failed") fail = True try: - global_one(2, 2) + global_one(2, 2) except TypeError, e: - fail = False + fail = False if fail: - raise RuntimeError("argument count check failed") + raise RuntimeError("argument count check failed") fail = True try: - global_two(1) + global_two(1) except TypeError, e: - fail = False + fail = False if fail: - raise RuntimeError("argument count check failed") + raise RuntimeError("argument count check failed") fail = True try: - global_two(3, 3, 3) + global_two(3, 3, 3) except TypeError, e: - fail = False + fail = False if fail: - raise RuntimeError("argument count check failed") - + raise RuntimeError("argument count check failed") diff --git a/Examples/test-suite/python/global_namespace_runme.py b/Examples/test-suite/python/global_namespace_runme.py index 8e42e0653..ac12fe2dc 100644 --- a/Examples/test-suite/python/global_namespace_runme.py +++ b/Examples/test-suite/python/global_namespace_runme.py @@ -1,7 +1,8 @@ from global_namespace import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") k1 = Klass1() k2 = Klass2() @@ -12,9 +13,9 @@ k6 = Klass6() k7 = Klass7() if is_new_style_class(KlassMethods): - KlassMethods_static = KlassMethods + KlassMethods_static = KlassMethods else: - KlassMethods_static = KlassMethods() + KlassMethods_static = KlassMethods() KlassMethods_static.methodA(k1, k2, k3, k4, k5, k6, k7) KlassMethods_static.methodB(k1, k2, k3, k4, k5, k6, k7) @@ -41,15 +42,17 @@ KlassMethods_static.methodA(k1, k2, k3, k4, k5, k6, k7) KlassMethods_static.methodB(k1, k2, k3, k4, k5, k6, k7) if is_new_style_class(XYZMethods): - XYZMethods_static = XYZMethods + XYZMethods_static = XYZMethods else: - XYZMethods_static = XYZMethods() -XYZMethods_static.methodA(XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7()) -XYZMethods_static.methodB(XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7()) + XYZMethods_static = XYZMethods() +XYZMethods_static.methodA( + XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7()) +XYZMethods_static.methodB( + XYZ1(), XYZ2(), XYZ3(), XYZ4(), XYZ5(), XYZ6(), XYZ7()) if is_new_style_class(TheEnumMethods): - TheEnumMethods_static = TheEnumMethods + TheEnumMethods_static = TheEnumMethods else: - TheEnumMethods_static = TheEnumMethods() + TheEnumMethods_static = TheEnumMethods() TheEnumMethods_static.methodA(theenum1, theenum2, theenum3) TheEnumMethods_static.methodA(theenum1, theenum2, theenum3) diff --git a/Examples/test-suite/python/global_ns_arg_runme.py b/Examples/test-suite/python/global_ns_arg_runme.py index cf1915648..f7fbc7a9e 100644 --- a/Examples/test-suite/python/global_ns_arg_runme.py +++ b/Examples/test-suite/python/global_ns_arg_runme.py @@ -2,4 +2,3 @@ from global_ns_arg import * a = foo(1) b = bar_fn() - diff --git a/Examples/test-suite/python/global_vars_runme.py b/Examples/test-suite/python/global_vars_runme.py index 5d520b5ce..3ef0b494f 100644 --- a/Examples/test-suite/python/global_vars_runme.py +++ b/Examples/test-suite/python/global_vars_runme.py @@ -3,33 +3,32 @@ import global_vars global_vars.init() b = global_vars.cvar.b if b != "string b": - raise RuntimeError("Unexpected string: " + b) + raise RuntimeError("Unexpected string: " + b) global_vars.cvar.b = "a string value" b = global_vars.cvar.b if b != "a string value": - raise RuntimeError("Unexpected string: " + b) + raise RuntimeError("Unexpected string: " + b) x = global_vars.cvar.x if x != 1234: - raise RuntimeError("Unexpected x: " + str(x)) + raise RuntimeError("Unexpected x: " + str(x)) global_vars.cvar.x = 9876 x = global_vars.cvar.x if x != 9876: - raise RuntimeError("Unexpected string: " + str(x)) + raise RuntimeError("Unexpected string: " + str(x)) fail = True try: - global_vars.cvar.notexist = "something" + global_vars.cvar.notexist = "something" except AttributeError, e: - fail = False + fail = False if fail: - raise RuntimeError("AttributeError should have been thrown") + raise RuntimeError("AttributeError should have been thrown") fail = True try: - g = global_vars.cvar.notexist + g = global_vars.cvar.notexist except AttributeError, e: - fail = False + fail = False if fail: - raise RuntimeError("AttributeError should have been thrown") - + raise RuntimeError("AttributeError should have been thrown") diff --git a/Examples/test-suite/python/iadd_runme.py b/Examples/test-suite/python/iadd_runme.py index fbeb0ec3e..ceaa38860 100644 --- a/Examples/test-suite/python/iadd_runme.py +++ b/Examples/test-suite/python/iadd_runme.py @@ -3,7 +3,7 @@ import iadd f = iadd.Foo() f.AsA.x = 3 -f.AsA += f.AsA +f.AsA += f.AsA if f.AsA.x != 6: raise RuntimeError diff --git a/Examples/test-suite/python/implicittest_runme.py b/Examples/test-suite/python/implicittest_runme.py index 4cad1bb5d..4646d08c0 100644 --- a/Examples/test-suite/python/implicittest_runme.py +++ b/Examples/test-suite/python/implicittest_runme.py @@ -1,11 +1,13 @@ from implicittest import * + def check(a, b): if a != b: raise RuntimeError(str(a) + " does not equal " + str(b)) + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") #### Class #### @@ -20,7 +22,8 @@ try: except ValueError: # ValueError: invalid null reference in method 'new_A', argument 1 of type 'B const &' # Arguably A(char *) should be chosen, but there is a bug to do with None passed to methods overloaded by value, - # references and pointers to different types, where pointers ought to be given a slightly higher precedence. + # references and pointers to different types, where pointers ought to be + # given a slightly higher precedence. pass check(1, get(1)) @@ -43,9 +46,9 @@ check(3, A_int(B()).get()) check(4, A_int("hello").get()) if is_new_style_class(A_int): - A_int_static = A_int + A_int_static = A_int else: - A_int_static = A_int(0) + A_int_static = A_int(0) check(1, A_int_static.sget(1)) check(2, A_int_static.sget(1.0)) check(3, A_int_static.sget(B())) @@ -59,10 +62,14 @@ except TypeError: #### Global variable assignment #### -cvar.foo = Foo(1); check(cvar.foo.ii, 1) -cvar.foo = 1; check(cvar.foo.ii, 1) -cvar.foo = 1.0; check(cvar.foo.ii, 2) -cvar.foo = Foo("hello"); check(cvar.foo.ii, 3) +cvar.foo = Foo(1) +check(cvar.foo.ii, 1) +cvar.foo = 1 +check(cvar.foo.ii, 1) +cvar.foo = 1.0 +check(cvar.foo.ii, 2) +cvar.foo = Foo("hello") +check(cvar.foo.ii, 3) # explicit constructor: try: @@ -74,10 +81,14 @@ except TypeError: #### Member variable assignment #### # Note: also needs naturalvar -b = Bar(); check(b.f.ii, 0) -b.f = Foo("hello"); check(b.f.ii, 3) -b.f = 1; check(b.f.ii, 1) -b.f = 1.0; check(b.f.ii, 2) +b = Bar() +check(b.f.ii, 0) +b.f = Foo("hello") +check(b.f.ii, 3) +b.f = 1 +check(b.f.ii, 1) +b.f = 1.0 +check(b.f.ii, 2) # explicit constructor: try: @@ -129,4 +140,3 @@ ccc = CCC(B()) check(ccc.checkvalue, 10) check(ccc.xx(123), 11) check(ccc.yy(123, 123), 111) - diff --git a/Examples/test-suite/python/import_nomodule_runme.py b/Examples/test-suite/python/import_nomodule_runme.py index efcff9c48..e43c233b4 100644 --- a/Examples/test-suite/python/import_nomodule_runme.py +++ b/Examples/test-suite/python/import_nomodule_runme.py @@ -3,11 +3,11 @@ from import_nomodule import * # This test is expected to fail with -builtin option. # The base class is needed for the builtin class hierarchy if is_python_builtin(): - exit(0) + exit(0) f = create_Foo() -test1(f,42) +test1(f, 42) delete_Foo(f) b = Bar() -test1(b,37) +test1(b, 37) diff --git a/Examples/test-suite/python/import_stl_runme.py b/Examples/test-suite/python/import_stl_runme.py index 90c411455..69fe812b9 100644 --- a/Examples/test-suite/python/import_stl_runme.py +++ b/Examples/test-suite/python/import_stl_runme.py @@ -1,7 +1,6 @@ import import_stl_b import import_stl_a -v_new = import_stl_b.process_vector([1,2,3]) -if v_new != (1,2,3,4): - raise RuntimeError, v_new - +v_new = import_stl_b.process_vector([1, 2, 3]) +if v_new != (1, 2, 3, 4): + raise RuntimeError, v_new diff --git a/Examples/test-suite/python/imports_runme.py b/Examples/test-suite/python/imports_runme.py index 50a3ab59f..3eec965a6 100644 --- a/Examples/test-suite/python/imports_runme.py +++ b/Examples/test-suite/python/imports_runme.py @@ -14,4 +14,4 @@ a1 = c.get_a(c) a2 = c.get_a_type(c) if a1.hello() != a2.hello(): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/inctest_runme.py b/Examples/test-suite/python/inctest_runme.py index e10f4544c..fa3492932 100644 --- a/Examples/test-suite/python/inctest_runme.py +++ b/Examples/test-suite/python/inctest_runme.py @@ -2,31 +2,30 @@ import inctest error = 0 try: - a = inctest.A() + a = inctest.A() except: - print "didn't find A" - print "therefore, I didn't include 'testdir/subdir1/hello.i'" - error = 1 + print "didn't find A" + print "therefore, I didn't include 'testdir/subdir1/hello.i'" + error = 1 pass try: - b = inctest.B() + b = inctest.B() except: - print "didn't find B" - print "therefore, I didn't include 'testdir/subdir2/hello.i'" - error = 1 + print "didn't find B" + print "therefore, I didn't include 'testdir/subdir2/hello.i'" + error = 1 pass if error == 1: - raise RuntimeError + raise RuntimeError # Check the import in subdirectory worked if inctest.importtest1(5) != 15: - print "import test 1 failed" - raise RuntimeError + print "import test 1 failed" + raise RuntimeError if inctest.importtest2("black") != "white": - print "import test 2 failed" - raise RuntimeError - + print "import test 2 failed" + raise RuntimeError diff --git a/Examples/test-suite/python/inout_runme.py b/Examples/test-suite/python/inout_runme.py index fb290f62f..bb198d774 100644 --- a/Examples/test-suite/python/inout_runme.py +++ b/Examples/test-suite/python/inout_runme.py @@ -2,21 +2,20 @@ import inout a = inout.AddOne1(1) if a != 2: - raise RuntimeError + raise RuntimeError -a = inout.AddOne3(1,1,1) -if a != [2,2,2]: - raise RuntimeError +a = inout.AddOne3(1, 1, 1) +if a != [2, 2, 2]: + raise RuntimeError -a = inout.AddOne1p((1,1)) -if a != (2,2): - raise RuntimeError +a = inout.AddOne1p((1, 1)) +if a != (2, 2): + raise RuntimeError -a = inout.AddOne2p((1,1),1) -if a != [(2,2),2]: - raise RuntimeError - -a = inout.AddOne3p(1,(1,1),1) -if a != [2,(2,2),2]: - raise RuntimeError +a = inout.AddOne2p((1, 1), 1) +if a != [(2, 2), 2]: + raise RuntimeError +a = inout.AddOne3p(1, (1, 1), 1) +if a != [2, (2, 2), 2]: + raise RuntimeError diff --git a/Examples/test-suite/python/inplaceadd_runme.py b/Examples/test-suite/python/inplaceadd_runme.py index b703c56c7..7f292cbb5 100644 --- a/Examples/test-suite/python/inplaceadd_runme.py +++ b/Examples/test-suite/python/inplaceadd_runme.py @@ -3,18 +3,18 @@ a = inplaceadd.A(7) a += 5 if a.val != 12: - print a.val - raise RuntimeError + print a.val + raise RuntimeError a -= 5 if a.val != 7: - raise RuntimeError + raise RuntimeError a *= 2 if a.val != 14: - raise RuntimeError + raise RuntimeError a += a if a.val != 28: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/input_runme.py b/Examples/test-suite/python/input_runme.py index f5ef6dc8b..1a06e8b7b 100644 --- a/Examples/test-suite/python/input_runme.py +++ b/Examples/test-suite/python/input_runme.py @@ -2,19 +2,19 @@ from input import * f = Foo() if f.foo(2) != 4: - raise RuntimeError - -if f.foo(None)!= None: - raise RuntimeError + raise RuntimeError -if f.foo()!= None: - raise RuntimeError +if f.foo(None) != None: + raise RuntimeError + +if f.foo() != None: + raise RuntimeError if sfoo("Hello") != "Hello world": - raise RuntimeError + raise RuntimeError if sfoo(None) != None: - raise RuntimeError + raise RuntimeError if sfoo() != None: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/kwargs_feature_runme.py b/Examples/test-suite/python/kwargs_feature_runme.py index 37457c976..a2d4731ab 100644 --- a/Examples/test-suite/python/kwargs_feature_runme.py +++ b/Examples/test-suite/python/kwargs_feature_runme.py @@ -1,81 +1,81 @@ from kwargs_feature import * -class MyFoo(Foo): - def __init__(self, a , b = 0): - Foo.__init__(self, a, b) - +class MyFoo(Foo): + + def __init__(self, a, b=0): + Foo.__init__(self, a, b) + # Simple class f1 = MyFoo(2) -f = Foo(b=2,a=1) +f = Foo(b=2, a=1) -if f.foo(b=1,a=2) != 3: - raise RuntimeError +if f.foo(b=1, a=2) != 3: + raise RuntimeError if Foo_statfoo(b=2) != 3: - raise RuntimeError + raise RuntimeError if f.efoo(b=2) != 3: - raise RuntimeError + raise RuntimeError if Foo_sfoo(b=2) != 3: - raise RuntimeError + raise RuntimeError # Templated class -b = BarInt(b=2,a=1) +b = BarInt(b=2, a=1) -if b.bar(b=1,a=2) != 3: - raise RuntimeError +if b.bar(b=1, a=2) != 3: + raise RuntimeError if BarInt_statbar(b=2) != 3: - raise RuntimeError + raise RuntimeError if b.ebar(b=2) != 3: - raise RuntimeError + raise RuntimeError if BarInt_sbar(b=2) != 3: - raise RuntimeError + raise RuntimeError # Functions if templatedfunction(b=2) != 3: - raise RuntimeError + raise RuntimeError -if foo_fn(a=1,b=2) != 3: - raise RuntimeError +if foo_fn(a=1, b=2) != 3: + raise RuntimeError if foo_fn(b=2) != 3: - raise RuntimeError + raise RuntimeError -#Functions with keywords +# Functions with keywords if foo_kw(_from=2) != 4: - raise RuntimeError + raise RuntimeError if foo_nu(_from=2, arg2=3) != 2: - raise RuntimeError + raise RuntimeError if foo_mm(min=2) != 4: - raise RuntimeError + raise RuntimeError if foo_mm(max=3) != 4: - raise RuntimeError - -#Default args with references + raise RuntimeError + +# Default args with references if rfoo(n=123) != 120: - raise RuntimeError + raise RuntimeError if rfoo(x=10) != -10: - raise RuntimeError + raise RuntimeError if rfoo(n=11, x=22) != -11: - raise RuntimeError + raise RuntimeError if rfoo(x=11, n=22) != 11: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/langobj_runme.py b/Examples/test-suite/python/langobj_runme.py index c10e19303..b32d5a18a 100644 --- a/Examples/test-suite/python/langobj_runme.py +++ b/Examples/test-suite/python/langobj_runme.py @@ -2,7 +2,7 @@ import sys from langobj import * -x ="hello" +x = "hello" rx = sys.getrefcount(x) v = identity(x) rv = sys.getrefcount(v) diff --git a/Examples/test-suite/python/li_attribute_runme.py b/Examples/test-suite/python/li_attribute_runme.py index db40b9b2a..13a01c97d 100644 --- a/Examples/test-suite/python/li_attribute_runme.py +++ b/Examples/test-suite/python/li_attribute_runme.py @@ -2,73 +2,72 @@ import li_attribute -aa = li_attribute.A(1,2,3) +aa = li_attribute.A(1, 2, 3) if aa.a != 1: - raise RuntimeError + raise RuntimeError aa.a = 3 if aa.a != 3: - print aa.a - raise RuntimeError + print aa.a + raise RuntimeError if aa.b != 2: - print aa.b - raise RuntimeError + print aa.b + raise RuntimeError aa.b = 5 if aa.b != 5: - raise RuntimeError + raise RuntimeError if aa.d != aa.b: - raise RuntimeError + raise RuntimeError if aa.c != 3: - raise RuntimeError + raise RuntimeError #aa.c = 5 -#if aa.c != 3: +# if aa.c != 3: # raise RuntimeError pi = li_attribute.Param_i(7) if pi.value != 7: - raise RuntimeError + raise RuntimeError -pi.value=3 +pi.value = 3 if pi.value != 3: - raise RuntimeError + raise RuntimeError b = li_attribute.B(aa) if b.a.c != 3: - raise RuntimeError - + raise RuntimeError + # class/struct attribute with get/set methods using return/pass by reference myFoo = li_attribute.MyFoo() myFoo.x = 8 myClass = li_attribute.MyClass() myClass.Foo = myFoo if myClass.Foo.x != 8: - raise RuntimeError + raise RuntimeError # class/struct attribute with get/set methods using return/pass by value myClassVal = li_attribute.MyClassVal() if myClassVal.ReadWriteFoo.x != -1: - raise RuntimeError + raise RuntimeError if myClassVal.ReadOnlyFoo.x != -1: - raise RuntimeError + raise RuntimeError myClassVal.ReadWriteFoo = myFoo if myClassVal.ReadWriteFoo.x != 8: - raise RuntimeError + raise RuntimeError if myClassVal.ReadOnlyFoo.x != 8: - raise RuntimeError + raise RuntimeError # string attribute with get/set methods using return/pass by value myStringyClass = li_attribute.MyStringyClass("initial string") if myStringyClass.ReadWriteString != "initial string": - raise RuntimeError + raise RuntimeError if myStringyClass.ReadOnlyString != "initial string": - raise RuntimeError + raise RuntimeError myStringyClass.ReadWriteString = "changed string" if myStringyClass.ReadWriteString != "changed string": - raise RuntimeError + raise RuntimeError if myStringyClass.ReadOnlyString != "changed string": - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/li_attribute_template_runme.py b/Examples/test-suite/python/li_attribute_template_runme.py index 7423053f9..d33b12309 100644 --- a/Examples/test-suite/python/li_attribute_template_runme.py +++ b/Examples/test-suite/python/li_attribute_template_runme.py @@ -2,66 +2,67 @@ import li_attribute_template -chell = li_attribute_template.Cintint(1,2,3) +chell = li_attribute_template.Cintint(1, 2, 3) -def rassert( what, master ): + +def rassert(what, master): if what != master: print what raise RuntimeError -## Testing primitive by value attribute -rassert( chell.a, 1 ) +# Testing primitive by value attribute +rassert(chell.a, 1) chell.a = 3 -rassert( chell.a, 3 ) +rassert(chell.a, 3) -## Testing primitive by ref attribute +# Testing primitive by ref attribute -rassert( chell.b, 2 ) +rassert(chell.b, 2) chell.b = 5 -rassert( chell.b,5 ) +rassert(chell.b, 5) -## Testing string +# Testing string chell.str = "abc" -rassert( chell.str, "abc" ) +rassert(chell.str, "abc") # Testing class by value -rassert( chell.d.value, 1 ) +rassert(chell.d.value, 1) chell.d = li_attribute_template.Foo(2) -rassert( chell.d.value, 2 ) +rassert(chell.d.value, 2) # Testing class by reference -rassert( chell.e.value, 2 ) +rassert(chell.e.value, 2) -chell.e= li_attribute_template.Foo(3) -rassert( chell.e.value, 3 ) +chell.e = li_attribute_template.Foo(3) +rassert(chell.e.value, 3) chell.e.value = 4 -rassert( chell.e.value, 4 ) +rassert(chell.e.value, 4) # Testing moderately complex template by value -rassert( chell.f.first, 1 ) -rassert( chell.f.second, 2 ) +rassert(chell.f.first, 1) +rassert(chell.f.second, 2) -pair = li_attribute_template.pair_intint(3,4) +pair = li_attribute_template.pair_intint(3, 4) chell.f = pair -rassert( chell.f.first, 3 ) -rassert( chell.f.second, 4 ) +rassert(chell.f.first, 3) +rassert(chell.f.second, 4) # Testing moderately complex template by ref -rassert( chell.g.first, 2 ) -rassert( chell.g.second, 3 ) +rassert(chell.g.first, 2) +rassert(chell.g.second, 3) -pair = li_attribute_template.pair_intint(4,5) +pair = li_attribute_template.pair_intint(4, 5) chell.g = pair -rassert( chell.g.first, 4 ) -rassert( chell.g.second, 5 ) +rassert(chell.g.first, 4) +rassert(chell.g.second, 5) chell.g.first = 6 chell.g.second = 7 -rassert( chell.g.first, 6 ) -rassert( chell.g.second, 7 ) +rassert(chell.g.first, 6) +rassert(chell.g.second, 7) diff --git a/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py index a05432925..9b9c7d683 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_bits_runme.py @@ -1,20 +1,22 @@ from li_boost_shared_ptr_bits import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") + def check(nd): - nd.i = 200 - i = nd.i + nd.i = 200 + i = nd.i - try: - nd.notexist = 100 - passed = 0 - except: - passed = 1 + try: + nd.notexist = 100 + passed = 0 + except: + passed = 1 - if not passed: - raise "Test failed" + if not passed: + raise "Test failed" nd = NonDynamic() check(nd) @@ -30,11 +32,10 @@ v.push_back(IntHolder(33)) sum = sum(v) if sum != 66: - raise "sum is wrong" + raise "sum is wrong" ################################ if is_new_style_class(HiddenDestructor): - p = HiddenDestructor.create() + p = HiddenDestructor.create() else: - p = HiddenDestructor_create() - + p = HiddenDestructor_create() diff --git a/Examples/test-suite/python/li_boost_shared_ptr_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_runme.py index 0e025d546..7214add3e 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_runme.py @@ -4,541 +4,559 @@ import gc debug = False # simple shared_ptr usage - created in C++ + + class li_boost_shared_ptr_runme: - def main(self): - if (debug): - print "Started" - - li_boost_shared_ptr.cvar.debug_shared = debug - - # Change loop count to run for a long time to monitor memory - loopCount = 1 #5000 - for i in range (0,loopCount): - self.runtest() - - # Expect 1 instance - the one global variable (GlobalValue) - if (li_boost_shared_ptr.Klass_getTotal_count() != 1): - raise RuntimeError("Klass.total_count=%s" % li_boost_shared_ptr.Klass.getTotal_count()) - - wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count() - if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING): - # Expect 1 instance - the one global variable (GlobalSmartValue) - if (wrapper_count != 1): - raise RuntimeError("shared_ptr wrapper count=%s" % wrapper_count) - - if (debug): - print "Finished" - - def runtest(self): - # simple shared_ptr usage - created in C++ - k = li_boost_shared_ptr.Klass("me oh my") - val = k.getValue() - self.verifyValue("me oh my", val) - self.verifyCount(1, k) - - # simple shared_ptr usage - not created in C++ - k = li_boost_shared_ptr.factorycreate() - val = k.getValue() - self.verifyValue("factorycreate", val) - self.verifyCount(1, k) - - # pass by shared_ptr - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.smartpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointertest", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr pointer - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.smartpointerpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerpointertest", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr reference - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.smartpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerreftest", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr pointer reference - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.smartpointerpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerpointerreftest", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # const pass by shared_ptr - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.constsmartpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # const pass by shared_ptr pointer - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.constsmartpointerpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # const pass by shared_ptr reference - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.constsmartpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by value - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.valuetest(k) - val = kret.getValue() - self.verifyValue("me oh my valuetest", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # pass by pointer - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.pointertest(k) - val = kret.getValue() - self.verifyValue("me oh my pointertest", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # pass by reference - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.reftest(k) - val = kret.getValue() - self.verifyValue("me oh my reftest", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # pass by pointer reference - k = li_boost_shared_ptr.Klass("me oh my") - kret = li_boost_shared_ptr.pointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my pointerreftest", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # null tests - k = None - - if (li_boost_shared_ptr.smartpointertest(k) != None): - raise RuntimeError("return was not null") - - if (li_boost_shared_ptr.smartpointerpointertest(k) != None): - raise RuntimeError("return was not null") - - if (li_boost_shared_ptr.smartpointerreftest(k) != None): - raise RuntimeError("return was not null") - - if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None): - raise RuntimeError("return was not null") - - if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"): - raise RuntimeError("not null smartpointer pointer") - - try: - li_boost_shared_ptr.valuetest(k) - raise RuntimeError("Failed to catch null pointer") - except ValueError: - pass - - if (li_boost_shared_ptr.pointertest(k) != None): - raise RuntimeError("return was not null") - - try: - li_boost_shared_ptr.reftest(k) - raise RuntimeError("Failed to catch null pointer") - except ValueError: - pass - - # $owner - k = li_boost_shared_ptr.pointerownertest() - val = k.getValue() - self.verifyValue("pointerownertest", val) - self.verifyCount(1, k) - k = li_boost_shared_ptr.smartpointerpointerownertest() - val = k.getValue() - self.verifyValue("smartpointerpointerownertest", val) - self.verifyCount(1, k) - - # //////////////////////////////// Derived class //////////////////////////////////////// - # derived pass by shared_ptr - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedsmartptrtest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedsmartptrtest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # derived pass by shared_ptr pointer - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedsmartptrpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # derived pass by shared_ptr ref - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedsmartptrreftest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedsmartptrreftest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # derived pass by shared_ptr pointer ref - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # derived pass by pointer - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedpointertest-Derived", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # derived pass by ref - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.derivedreftest(k) - val = kret.getValue() - self.verifyValue("me oh my derivedreftest-Derived", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # //////////////////////////////// Derived and base class mixed //////////////////////////////////////// - # pass by shared_ptr (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.smartpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointertest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr pointer (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.smartpointerpointertest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerpointertest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr reference (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.smartpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerreftest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by shared_ptr pointer reference (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.smartpointerpointerreftest(k) - val = kret.getValue() - self.verifyValue("me oh my smartpointerpointerreftest-Derived", val) - self.verifyCount(2, k) - self.verifyCount(2, kret) - - # pass by value (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.valuetest(k) - val = kret.getValue() - self.verifyValue("me oh my valuetest", val) # note slicing - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # pass by pointer (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.pointertest(k) - val = kret.getValue() - self.verifyValue("me oh my pointertest-Derived", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # pass by ref (mixed) - k = li_boost_shared_ptr.KlassDerived("me oh my") - kret = li_boost_shared_ptr.reftest(k) - val = kret.getValue() - self.verifyValue("me oh my reftest-Derived", val) - self.verifyCount(1, k) - self.verifyCount(1, kret) - - # //////////////////////////////// Overloading tests //////////////////////////////////////// - # Base class - k = li_boost_shared_ptr.Klass("me oh my") - self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") - self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") - self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") - self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") - - self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") - self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") - self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") - self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") - - # Derived class - k = li_boost_shared_ptr.KlassDerived("me oh my") - self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") - self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") - self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") - self.verifyValue(li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") - - self.verifyValue(li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") - self.verifyValue(li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") - self.verifyValue(li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") - self.verifyValue(li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") - - # 3rd derived class - k = li_boost_shared_ptr.Klass3rdDerived("me oh my") - val = k.getValue() - self.verifyValue("me oh my-3rdDerived", val) - self.verifyCount(1, k) - val = li_boost_shared_ptr.test3rdupcast(k) - self.verifyValue("me oh my-3rdDerived", val) - self.verifyCount(1, k) - - # //////////////////////////////// Member variables //////////////////////////////////////// - # smart pointer by value - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("smart member value") - m.SmartMemberValue = k - val = k.getValue() - self.verifyValue("smart member value", val) - self.verifyCount(2, k) - - kmember = m.SmartMemberValue - val = kmember.getValue() - self.verifyValue("smart member value", val) - self.verifyCount(3, kmember) - self.verifyCount(3, k) - - del m - self.verifyCount(2, kmember) - self.verifyCount(2, k) - - # smart pointer by pointer - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("smart member pointer") - m.SmartMemberPointer = k - val = k.getValue() - self.verifyValue("smart member pointer", val) - self.verifyCount(1, k) - - kmember = m.SmartMemberPointer - val = kmember.getValue() - self.verifyValue("smart member pointer", val) - self.verifyCount(2, kmember) - self.verifyCount(2, k) - - del m - self.verifyCount(2, kmember) - self.verifyCount(2, k) - - # smart pointer by reference - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("smart member reference") - m.SmartMemberReference = k - val = k.getValue() - self.verifyValue("smart member reference", val) - self.verifyCount(2, k) - - kmember = m.SmartMemberReference - val = kmember.getValue() - self.verifyValue("smart member reference", val) - self.verifyCount(3, kmember) - self.verifyCount(3, k) - - # The C++ reference refers to SmartMemberValue... - kmemberVal = m.SmartMemberValue - val = kmember.getValue() - self.verifyValue("smart member reference", val) - self.verifyCount(4, kmemberVal) - self.verifyCount(4, kmember) - self.verifyCount(4, k) - - del m - self.verifyCount(3, kmemberVal) - self.verifyCount(3, kmember) - self.verifyCount(3, k) - - # plain by value - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("plain member value") - m.MemberValue = k - val = k.getValue() - self.verifyValue("plain member value", val) - self.verifyCount(1, k) - - kmember = m.MemberValue - val = kmember.getValue() - self.verifyValue("plain member value", val) - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - del m - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - # plain by pointer - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("plain member pointer") - m.MemberPointer = k - val = k.getValue() - self.verifyValue("plain member pointer", val) - self.verifyCount(1, k) - - kmember = m.MemberPointer - val = kmember.getValue() - self.verifyValue("plain member pointer", val) - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - del m - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - # plain by reference - m = li_boost_shared_ptr.MemberVariables() - k = li_boost_shared_ptr.Klass("plain member reference") - m.MemberReference = k - val = k.getValue() - self.verifyValue("plain member reference", val) - self.verifyCount(1, k) - - kmember = m.MemberReference - val = kmember.getValue() - self.verifyValue("plain member reference", val) - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - del m - self.verifyCount(1, kmember) - self.verifyCount(1, k) - - # null member variables - m = li_boost_shared_ptr.MemberVariables() - - # shared_ptr by value - k = m.SmartMemberValue - if (k != None): - raise RuntimeError("expected null") - m.SmartMemberValue = None - k = m.SmartMemberValue - if (k != None): - raise RuntimeError("expected null") - self.verifyCount(0, k) - - # plain by value - try: - m.MemberValue = None - raise RuntimeError("Failed to catch null pointer") - except ValueError: - pass - - # ////////////////////////////////// Global variables //////////////////////////////////////// - # smart pointer - kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue - if (kglobal != None): - raise RuntimeError("expected null") - - k = li_boost_shared_ptr.Klass("smart global value") - li_boost_shared_ptr.cvar.GlobalSmartValue = k - self.verifyCount(2, k) - - kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue - val = kglobal.getValue() - self.verifyValue("smart global value", val) - self.verifyCount(3, kglobal) - self.verifyCount(3, k) - self.verifyValue("smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue()) - li_boost_shared_ptr.cvar.GlobalSmartValue = None - - # plain value - k = li_boost_shared_ptr.Klass("global value") - li_boost_shared_ptr.cvar.GlobalValue = k - self.verifyCount(1, k) - - kglobal = li_boost_shared_ptr.cvar.GlobalValue - val = kglobal.getValue() - self.verifyValue("global value", val) - self.verifyCount(1, kglobal) - self.verifyCount(1, k) - self.verifyValue("global value", li_boost_shared_ptr.cvar.GlobalValue.getValue()) - - try: - li_boost_shared_ptr.cvar.GlobalValue = None - raise RuntimeError("Failed to catch null pointer") - except ValueError: - pass - - # plain pointer - kglobal = li_boost_shared_ptr.cvar.GlobalPointer - if (kglobal != None): - raise RuntimeError("expected null") - - k = li_boost_shared_ptr.Klass("global pointer") - li_boost_shared_ptr.cvar.GlobalPointer = k - self.verifyCount(1, k) - - kglobal = li_boost_shared_ptr.cvar.GlobalPointer - val = kglobal.getValue() - self.verifyValue("global pointer", val) - self.verifyCount(1, kglobal) - self.verifyCount(1, k) - li_boost_shared_ptr.cvar.GlobalPointer = None - - # plain reference - kglobal - - k = li_boost_shared_ptr.Klass("global reference") - li_boost_shared_ptr.cvar.GlobalReference = k - self.verifyCount(1, k) - - kglobal = li_boost_shared_ptr.cvar.GlobalReference - val = kglobal.getValue() - self.verifyValue("global reference", val) - self.verifyCount(1, kglobal) - self.verifyCount(1, k) - - try: - li_boost_shared_ptr.cvar.GlobalReference = None - raise RuntimeError("Failed to catch null pointer") - except ValueError: - pass - - # ////////////////////////////////// Templates //////////////////////////////////////// - pid = li_boost_shared_ptr.PairIntDouble(10, 20.2) - if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4): - raise RuntimeError("Base values wrong") - if (pid.val1 != 10 or pid.val2 != 20.2): - raise RuntimeError("Derived Values wrong") - - def verifyValue(self, expected, got): - if (expected != got): - raise RuntimeError("verify value failed. Expected: ", expected, " Got: ", got) - - def verifyCount(self, expected, k): - got = li_boost_shared_ptr.use_count(k) - if (expected != got): - raise RuntimeError("verify use_count failed. Expected: ", expected, " Got: ", got) + + def main(self): + if (debug): + print "Started" + + li_boost_shared_ptr.cvar.debug_shared = debug + + # Change loop count to run for a long time to monitor memory + loopCount = 1 # 5000 + for i in range(0, loopCount): + self.runtest() + + # Expect 1 instance - the one global variable (GlobalValue) + if (li_boost_shared_ptr.Klass_getTotal_count() != 1): + raise RuntimeError("Klass.total_count=%s" % + li_boost_shared_ptr.Klass.getTotal_count()) + + wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count() + if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING): + # Expect 1 instance - the one global variable (GlobalSmartValue) + if (wrapper_count != 1): + raise RuntimeError( + "shared_ptr wrapper count=%s" % wrapper_count) + + if (debug): + print "Finished" + + def runtest(self): + # simple shared_ptr usage - created in C++ + k = li_boost_shared_ptr.Klass("me oh my") + val = k.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(1, k) + + # simple shared_ptr usage - not created in C++ + k = li_boost_shared_ptr.factorycreate() + val = k.getValue() + self.verifyValue("factorycreate", val) + self.verifyCount(1, k) + + # pass by shared_ptr + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.smartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointertest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.smartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointertest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr reference + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.smartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerreftest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer reference + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.smartpointerpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointerreftest", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.constsmartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr pointer + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.constsmartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # const pass by shared_ptr reference + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.constsmartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by value + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.valuetest(k) + val = kret.getValue() + self.verifyValue("me oh my valuetest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.pointertest(k) + val = kret.getValue() + self.verifyValue("me oh my pointertest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by reference + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.reftest(k) + val = kret.getValue() + self.verifyValue("me oh my reftest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer reference + k = li_boost_shared_ptr.Klass("me oh my") + kret = li_boost_shared_ptr.pointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my pointerreftest", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # null tests + k = None + + if (li_boost_shared_ptr.smartpointertest(k) != None): + raise RuntimeError("return was not null") + + if (li_boost_shared_ptr.smartpointerpointertest(k) != None): + raise RuntimeError("return was not null") + + if (li_boost_shared_ptr.smartpointerreftest(k) != None): + raise RuntimeError("return was not null") + + if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None): + raise RuntimeError("return was not null") + + if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"): + raise RuntimeError("not null smartpointer pointer") + + try: + li_boost_shared_ptr.valuetest(k) + raise RuntimeError("Failed to catch null pointer") + except ValueError: + pass + + if (li_boost_shared_ptr.pointertest(k) != None): + raise RuntimeError("return was not null") + + try: + li_boost_shared_ptr.reftest(k) + raise RuntimeError("Failed to catch null pointer") + except ValueError: + pass + + # $owner + k = li_boost_shared_ptr.pointerownertest() + val = k.getValue() + self.verifyValue("pointerownertest", val) + self.verifyCount(1, k) + k = li_boost_shared_ptr.smartpointerpointerownertest() + val = k.getValue() + self.verifyValue("smartpointerpointerownertest", val) + self.verifyCount(1, k) + + # //////////////////////////////// Derived class ////////////////////// + # derived pass by shared_ptr + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedsmartptrtest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrtest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr pointer + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedsmartptrpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr ref + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedsmartptrreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by shared_ptr pointer ref + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # derived pass by pointer + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedpointertest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # derived pass by ref + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.derivedreftest(k) + val = kret.getValue() + self.verifyValue("me oh my derivedreftest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # //////////////////////////////// Derived and base class mixed /////// + # pass by shared_ptr (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.smartpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.smartpointerpointertest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointertest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr reference (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.smartpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by shared_ptr pointer reference (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.smartpointerpointerreftest(k) + val = kret.getValue() + self.verifyValue("me oh my smartpointerpointerreftest-Derived", val) + self.verifyCount(2, k) + self.verifyCount(2, kret) + + # pass by value (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.valuetest(k) + val = kret.getValue() + self.verifyValue("me oh my valuetest", val) # note slicing + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by pointer (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.pointertest(k) + val = kret.getValue() + self.verifyValue("me oh my pointertest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # pass by ref (mixed) + k = li_boost_shared_ptr.KlassDerived("me oh my") + kret = li_boost_shared_ptr.reftest(k) + val = kret.getValue() + self.verifyValue("me oh my reftest-Derived", val) + self.verifyCount(1, k) + self.verifyCount(1, kret) + + # //////////////////////////////// Overloading tests ////////////////// + # Base class + k = li_boost_shared_ptr.Klass("me oh my") + self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") + self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") + self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") + self.verifyValue( + li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") + + self.verifyValue( + li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") + + # Derived class + k = li_boost_shared_ptr.KlassDerived("me oh my") + self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval") + self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref") + self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr") + self.verifyValue( + li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref") + + self.verifyValue( + li_boost_shared_ptr.overload_smartbyval(k), "smartbyval") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyref(k), "smartbyref") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr") + self.verifyValue( + li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref") + + # 3rd derived class + k = li_boost_shared_ptr.Klass3rdDerived("me oh my") + val = k.getValue() + self.verifyValue("me oh my-3rdDerived", val) + self.verifyCount(1, k) + val = li_boost_shared_ptr.test3rdupcast(k) + self.verifyValue("me oh my-3rdDerived", val) + self.verifyCount(1, k) + + # //////////////////////////////// Member variables /////////////////// + # smart pointer by value + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("smart member value") + m.SmartMemberValue = k + val = k.getValue() + self.verifyValue("smart member value", val) + self.verifyCount(2, k) + + kmember = m.SmartMemberValue + val = kmember.getValue() + self.verifyValue("smart member value", val) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + del m + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + # smart pointer by pointer + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("smart member pointer") + m.SmartMemberPointer = k + val = k.getValue() + self.verifyValue("smart member pointer", val) + self.verifyCount(1, k) + + kmember = m.SmartMemberPointer + val = kmember.getValue() + self.verifyValue("smart member pointer", val) + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + del m + self.verifyCount(2, kmember) + self.verifyCount(2, k) + + # smart pointer by reference + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("smart member reference") + m.SmartMemberReference = k + val = k.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(2, k) + + kmember = m.SmartMemberReference + val = kmember.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + # The C++ reference refers to SmartMemberValue... + kmemberVal = m.SmartMemberValue + val = kmember.getValue() + self.verifyValue("smart member reference", val) + self.verifyCount(4, kmemberVal) + self.verifyCount(4, kmember) + self.verifyCount(4, k) + + del m + self.verifyCount(3, kmemberVal) + self.verifyCount(3, kmember) + self.verifyCount(3, k) + + # plain by value + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("plain member value") + m.MemberValue = k + val = k.getValue() + self.verifyValue("plain member value", val) + self.verifyCount(1, k) + + kmember = m.MemberValue + val = kmember.getValue() + self.verifyValue("plain member value", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + del m + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # plain by pointer + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("plain member pointer") + m.MemberPointer = k + val = k.getValue() + self.verifyValue("plain member pointer", val) + self.verifyCount(1, k) + + kmember = m.MemberPointer + val = kmember.getValue() + self.verifyValue("plain member pointer", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + del m + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # plain by reference + m = li_boost_shared_ptr.MemberVariables() + k = li_boost_shared_ptr.Klass("plain member reference") + m.MemberReference = k + val = k.getValue() + self.verifyValue("plain member reference", val) + self.verifyCount(1, k) + + kmember = m.MemberReference + val = kmember.getValue() + self.verifyValue("plain member reference", val) + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + del m + self.verifyCount(1, kmember) + self.verifyCount(1, k) + + # null member variables + m = li_boost_shared_ptr.MemberVariables() + + # shared_ptr by value + k = m.SmartMemberValue + if (k != None): + raise RuntimeError("expected null") + m.SmartMemberValue = None + k = m.SmartMemberValue + if (k != None): + raise RuntimeError("expected null") + self.verifyCount(0, k) + + # plain by value + try: + m.MemberValue = None + raise RuntimeError("Failed to catch null pointer") + except ValueError: + pass + + # ////////////////////////////////// Global variables ///////////////// + # smart pointer + kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue + if (kglobal != None): + raise RuntimeError("expected null") + + k = li_boost_shared_ptr.Klass("smart global value") + li_boost_shared_ptr.cvar.GlobalSmartValue = k + self.verifyCount(2, k) + + kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue + val = kglobal.getValue() + self.verifyValue("smart global value", val) + self.verifyCount(3, kglobal) + self.verifyCount(3, k) + self.verifyValue( + "smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue()) + li_boost_shared_ptr.cvar.GlobalSmartValue = None + + # plain value + k = li_boost_shared_ptr.Klass("global value") + li_boost_shared_ptr.cvar.GlobalValue = k + self.verifyCount(1, k) + + kglobal = li_boost_shared_ptr.cvar.GlobalValue + val = kglobal.getValue() + self.verifyValue("global value", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + self.verifyValue( + "global value", li_boost_shared_ptr.cvar.GlobalValue.getValue()) + + try: + li_boost_shared_ptr.cvar.GlobalValue = None + raise RuntimeError("Failed to catch null pointer") + except ValueError: + pass + + # plain pointer + kglobal = li_boost_shared_ptr.cvar.GlobalPointer + if (kglobal != None): + raise RuntimeError("expected null") + + k = li_boost_shared_ptr.Klass("global pointer") + li_boost_shared_ptr.cvar.GlobalPointer = k + self.verifyCount(1, k) + + kglobal = li_boost_shared_ptr.cvar.GlobalPointer + val = kglobal.getValue() + self.verifyValue("global pointer", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + li_boost_shared_ptr.cvar.GlobalPointer = None + + # plain reference + kglobal + + k = li_boost_shared_ptr.Klass("global reference") + li_boost_shared_ptr.cvar.GlobalReference = k + self.verifyCount(1, k) + + kglobal = li_boost_shared_ptr.cvar.GlobalReference + val = kglobal.getValue() + self.verifyValue("global reference", val) + self.verifyCount(1, kglobal) + self.verifyCount(1, k) + + try: + li_boost_shared_ptr.cvar.GlobalReference = None + raise RuntimeError("Failed to catch null pointer") + except ValueError: + pass + + # ////////////////////////////////// Templates //////////////////////// + pid = li_boost_shared_ptr.PairIntDouble(10, 20.2) + if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4): + raise RuntimeError("Base values wrong") + if (pid.val1 != 10 or pid.val2 != 20.2): + raise RuntimeError("Derived Values wrong") + + def verifyValue(self, expected, got): + if (expected != got): + raise RuntimeError( + "verify value failed. Expected: ", expected, " Got: ", got) + + def verifyCount(self, expected, k): + got = li_boost_shared_ptr.use_count(k) + if (expected != got): + raise RuntimeError( + "verify use_count failed. Expected: ", expected, " Got: ", got) runme = li_boost_shared_ptr_runme() runme.main() - diff --git a/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py b/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py index c10627f36..6b56ec479 100644 --- a/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py +++ b/Examples/test-suite/python/li_boost_shared_ptr_template_runme.py @@ -3,28 +3,28 @@ from li_boost_shared_ptr_template import * b = BaseINTEGER() d = DerivedINTEGER() if b.bar() != 1: - raise RuntimeError + raise RuntimeError if d.bar() != 2: - raise RuntimeError + raise RuntimeError if bar_getter(b) != 1: - raise RuntimeError + raise RuntimeError # Fix reverted in rev 12953 -#if bar_getter(d) != 2: +# if bar_getter(d) != 2: # raise RuntimeError b = BaseDefaultInt() d = DerivedDefaultInt() d2 = DerivedDefaultInt2() if b.bar2() != 3: - raise RuntimeError + raise RuntimeError if d.bar2() != 4: - raise RuntimeError + raise RuntimeError if d2.bar2() != 4: - raise RuntimeError + raise RuntimeError if bar2_getter(b) != 3: - raise RuntimeError + raise RuntimeError # Fix reverted in rev 12953 -#if bar2_getter(d) != 4: +# if bar2_getter(d) != 4: # raise RuntimeError -#if bar2_getter(d2) != 4: +# if bar2_getter(d2) != 4: # raise RuntimeError diff --git a/Examples/test-suite/python/li_cdata_runme.py b/Examples/test-suite/python/li_cdata_runme.py index 061ca6f68..8a132e7dd 100644 --- a/Examples/test-suite/python/li_cdata_runme.py +++ b/Examples/test-suite/python/li_cdata_runme.py @@ -6,5 +6,4 @@ m = malloc(256) memmove(m, s) ss = cdata(m, 7) if ss != "ABC abc": - raise "failed" - + raise "failed" diff --git a/Examples/test-suite/python/li_cpointer_runme.py b/Examples/test-suite/python/li_cpointer_runme.py index ac95ff4b9..1565069cf 100644 --- a/Examples/test-suite/python/li_cpointer_runme.py +++ b/Examples/test-suite/python/li_cpointer_runme.py @@ -2,7 +2,7 @@ from li_cpointer import * p = new_intp() -intp_assign(p,3) +intp_assign(p, 3) if intp_value(p) != 3: raise RuntimeError diff --git a/Examples/test-suite/python/li_cstring_runme.py b/Examples/test-suite/python/li_cstring_runme.py index 6503744bd..55b51d1c7 100644 --- a/Examples/test-suite/python/li_cstring_runme.py +++ b/Examples/test-suite/python/li_cstring_runme.py @@ -2,7 +2,7 @@ from li_cstring import * if count("ab\0ab\0ab\0", 0) != 3: - raise RuntimeError + raise RuntimeError if test1() != "Hello World": raise RuntimeError @@ -17,16 +17,15 @@ if test3("hello") != "hello-suffix": if test4("hello") != "hello-suffix": print test4("hello") raise RuntimeError - + if test5(4) != 'xxxx': raise RuntimeError if test6(10) != 'xxxxx': raise RuntimeError - -if test7() !="Hello world!": + +if test7() != "Hello world!": raise RuntimeError if test8() != " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_": raise RuntimeError - diff --git a/Examples/test-suite/python/li_cwstring_runme.py b/Examples/test-suite/python/li_cwstring_runme.py index 4ab590882..aaa5b6e62 100644 --- a/Examples/test-suite/python/li_cwstring_runme.py +++ b/Examples/test-suite/python/li_cwstring_runme.py @@ -1,7 +1,7 @@ from li_cwstring import * if count(u"ab\0ab\0ab\0", 0) != 3: - raise RuntimeError + raise RuntimeError if test1() != u"Hello World": raise RuntimeError @@ -14,16 +14,15 @@ if test3("hello") != u"hello-suffix": if test4("hello") != u"hello-suffix": raise RuntimeError - + if test5(4) != u'xxxx': raise RuntimeError if test6(10) != u'xxxxx': raise RuntimeError - + if test7() != u"Hello world!": raise RuntimeError if test8() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_": raise RuntimeError - diff --git a/Examples/test-suite/python/li_implicit_runme.py b/Examples/test-suite/python/li_implicit_runme.py index a0672e016..d8dd0fdcc 100644 --- a/Examples/test-suite/python/li_implicit_runme.py +++ b/Examples/test-suite/python/li_implicit_runme.py @@ -9,9 +9,8 @@ ad, get(ad) ab, get(ab) if get(ai) != get(1): - raise RuntimeError,"bad implicit type" + raise RuntimeError, "bad implicit type" if get(ad) != get(2.0): - raise RuntimeError,"bad implicit type" + raise RuntimeError, "bad implicit type" if get(ab) != get(b): - raise RuntimeError,"bad implicit type" - + raise RuntimeError, "bad implicit type" diff --git a/Examples/test-suite/python/li_std_auto_ptr_runme.py b/Examples/test-suite/python/li_std_auto_ptr_runme.py index d82a89f42..6d2479f87 100644 --- a/Examples/test-suite/python/li_std_auto_ptr_runme.py +++ b/Examples/test-suite/python/li_std_auto_ptr_runme.py @@ -3,15 +3,15 @@ from li_std_auto_ptr import * k1 = makeKlassAutoPtr("first") k2 = makeKlassAutoPtr("second") if Klass_getTotal_count() != 2: - raise "number of objects should be 2" + raise "number of objects should be 2" del k1 if Klass_getTotal_count() != 1: - raise "number of objects should be 1" + raise "number of objects should be 1" if k2.getLabel() != "second": - raise "wrong object label" + raise "wrong object label" del k2 if Klass_getTotal_count() != 0: - raise "no objects should be left" + raise "no objects should be left" diff --git a/Examples/test-suite/python/li_std_carray_runme.py b/Examples/test-suite/python/li_std_carray_runme.py index 803bc96c5..36eeaf173 100644 --- a/Examples/test-suite/python/li_std_carray_runme.py +++ b/Examples/test-suite/python/li_std_carray_runme.py @@ -2,7 +2,7 @@ from li_std_carray import * v3 = Vector3() -for i in range(0,len(v3)): +for i in range(0, len(v3)): v3[i] = i i = 0 @@ -14,9 +14,9 @@ for d in v3: m3 = Matrix3() -for i in range(0,len(m3)): +for i in range(0, len(m3)): v3 = m3[i] - for j in range(0,len(v3)): + for j in range(0, len(v3)): v3[j] = i + j i = 0 @@ -30,12 +30,10 @@ for v3 in m3: i = i + 1 pass -for i in range(0,len(m3)): - for j in range(0,len(m3)): +for i in range(0, len(m3)): + for j in range(0, len(m3)): if m3[i][j] != i + j: raise RuntimeError -da = Vector3((1,2,3)) -ma = Matrix3(((1,2,3),(4,5,6),(7,8,9))) - - +da = Vector3((1, 2, 3)) +ma = Matrix3(((1, 2, 3), (4, 5, 6), (7, 8, 9))) diff --git a/Examples/test-suite/python/li_std_containers_int_runme.py b/Examples/test-suite/python/li_std_containers_int_runme.py index 3cbbb2862..c7d262f60 100644 --- a/Examples/test-suite/python/li_std_containers_int_runme.py +++ b/Examples/test-suite/python/li_std_containers_int_runme.py @@ -1,158 +1,170 @@ -# Check std::vector and std::list behaves the same as Python iterable types (list) +# Check std::vector and std::list behaves the same as Python iterable +# types (list) from li_std_containers_int import * import sys + def failed(a, b, msg): - raise RuntimeError, msg + " " + str(list(a)) + " " + str(list(b)) + raise RuntimeError, msg + " " + str(list(a)) + " " + str(list(b)) + def compare_sequences(a, b): - if len(a) != len(b): - failed(a, b, "different sizes") - for i in range(len(a)): - if a[i] != b[i]: - failed(a, b, "elements are different") + if len(a) != len(b): + failed(a, b, "different sizes") + for i in range(len(a)): + if a[i] != b[i]: + failed(a, b, "elements are different") + def compare_containers(pythonlist, swigvector, swiglist): - compare_sequences(pythonlist, swigvector) - compare_sequences(pythonlist, swiglist) + compare_sequences(pythonlist, swigvector) + compare_sequences(pythonlist, swiglist) + +# Check std::vector and std::list assignment behaves same as Python list +# assignment including exceptions + -# Check std::vector and std::list assignment behaves same as Python list assignment including exceptions def container_insert_step(i, j, step, newval): - ps = range(6) - iv = vector_int(ps) - il = list_int(ps) + ps = range(6) + iv = vector_int(ps) + il = list_int(ps) - # Python slice - try: - if step == None: - if j == None: - ps[i] = newval - else: - ps[i:j] = newval - else: - if j == None: - ps[i::step] = newval - else: - ps[i:j:step] = newval - ps_error = None - except ValueError, e: - ps_error = e - except IndexError, e: - ps_error = e + # Python slice + try: + if step == None: + if j == None: + ps[i] = newval + else: + ps[i:j] = newval + else: + if j == None: + ps[i::step] = newval + else: + ps[i:j:step] = newval + ps_error = None + except ValueError, e: + ps_error = e + except IndexError, e: + ps_error = e - # std::vector - try: - if step == None: - if j == None: - iv[i] = newval - else: - iv[i:j] = newval - else: - if j == None: - iv[i::step] = newval - else: - iv[i:j:step] = newval - iv_error = None - except ValueError, e: - iv_error = e - except IndexError, e: - iv_error = e + # std::vector + try: + if step == None: + if j == None: + iv[i] = newval + else: + iv[i:j] = newval + else: + if j == None: + iv[i::step] = newval + else: + iv[i:j:step] = newval + iv_error = None + except ValueError, e: + iv_error = e + except IndexError, e: + iv_error = e - # std::list - try: - if step == None: - if j == None: - il[i] = newval - else: - il[i:j] = newval - else: - if j == None: - il[i::step] = newval - else: - il[i:j:step] = newval - il_error = None - except ValueError, e: - il_error = e - except IndexError, e: - il_error = e + # std::list + try: + if step == None: + if j == None: + il[i] = newval + else: + il[i:j] = newval + else: + if j == None: + il[i::step] = newval + else: + il[i:j:step] = newval + il_error = None + except ValueError, e: + il_error = e + except IndexError, e: + il_error = e + + # Python 2.6 contains bug fixes in extended slicing syntax: + # http://docs.python.org/2/whatsnew/2.6.html + skip_check = ps_error != None and( + iv_error == il_error == None) and step > 0 and (sys.version_info[0:2] < (2, 6)) + if not(skip_check): + if not((type(ps_error) == type(iv_error)) and (type(ps_error) == type(il_error))): + raise RuntimeError, "ValueError exception not consistently thrown: " + \ + str(ps_error) + " " + str(iv_error) + " " + str(il_error) + + compare_containers(ps, iv, il) + + +# Check std::vector and std::list delete behaves same as Python list +# delete including exceptions +def container_delete_step(i, j, step): + ps = range(6) + iv = vector_int(ps) + il = list_int(ps) + + # Python slice + try: + if step == None: + if j == None: + del ps[i] + else: + del ps[i:j] + else: + if j == None: + del ps[i::step] + else: + del ps[i:j:step] + ps_error = None + except ValueError, e: + ps_error = e + except IndexError, e: + ps_error = e + + # std::vector + try: + if step == None: + if j == None: + del iv[i] + else: + del iv[i:j] + else: + if j == None: + del iv[i::step] + else: + del iv[i:j:step] + iv_error = None + except ValueError, e: + iv_error = e + except IndexError, e: + iv_error = e + + # std::list + try: + if step == None: + if j == None: + del il[i] + else: + del il[i:j] + else: + if j == None: + del il[i::step] + else: + del il[i:j:step] + il_error = None + except ValueError, e: + il_error = e + except IndexError, e: + il_error = e - # Python 2.6 contains bug fixes in extended slicing syntax: http://docs.python.org/2/whatsnew/2.6.html - skip_check = ps_error != None and(iv_error == il_error == None) and step > 0 and (sys.version_info[0:2] < (2, 6)) - if not(skip_check): if not((type(ps_error) == type(iv_error)) and (type(ps_error) == type(il_error))): - raise RuntimeError, "ValueError exception not consistently thrown: " + str(ps_error) + " " + str(iv_error) + " " + str(il_error) + raise RuntimeError, "ValueError exception not consistently thrown: " + \ + str(ps_error) + " " + str(iv_error) + " " + str(il_error) compare_containers(ps, iv, il) -# Check std::vector and std::list delete behaves same as Python list delete including exceptions -def container_delete_step(i, j, step): - ps = range(6) - iv = vector_int(ps) - il = list_int(ps) - - # Python slice - try: - if step == None: - if j == None: - del ps[i] - else: - del ps[i:j] - else: - if j == None: - del ps[i::step] - else: - del ps[i:j:step] - ps_error = None - except ValueError, e: - ps_error = e - except IndexError, e: - ps_error = e - - # std::vector - try: - if step == None: - if j == None: - del iv[i] - else: - del iv[i:j] - else: - if j == None: - del iv[i::step] - else: - del iv[i:j:step] - iv_error = None - except ValueError, e: - iv_error = e - except IndexError, e: - iv_error = e - - # std::list - try: - if step == None: - if j == None: - del il[i] - else: - del il[i:j] - else: - if j == None: - del il[i::step] - else: - del il[i:j:step] - il_error = None - except ValueError, e: - il_error = e - except IndexError, e: - il_error = e - - if not((type(ps_error) == type(iv_error)) and (type(ps_error) == type(il_error))): - raise RuntimeError, "ValueError exception not consistently thrown: " + str(ps_error) + " " + str(iv_error) + " " + str(il_error) - - compare_containers(ps, iv, il) - - -ps = [0,1,2,3,4,5] +ps = [0, 1, 2, 3, 4, 5] iv = vector_int(ps) il = list_int(ps) @@ -164,7 +176,7 @@ compare_containers(ps[1:3], iv[1:3], il[1:3]) compare_containers(ps[2:4], iv[2:4], il[2:4]) compare_containers(ps[0:3], iv[0:3], il[0:3]) compare_containers(ps[3:6], iv[3:6], il[3:6]) -compare_containers(ps[3:10], iv[3:10], il[3:10]) # beyond end of range +compare_containers(ps[3:10], iv[3:10], il[3:10]) # beyond end of range # before beginning of range (negative indexing) compare_containers(ps[-1:7], iv[-1:7], il[-1:7]) @@ -172,7 +184,8 @@ compare_containers(ps[-2:7], iv[-2:7], il[-2:7]) compare_containers(ps[-5:7], iv[-5:7], il[-5:7]) compare_containers(ps[-6:7], iv[-6:7], il[-6:7]) -# before beginning of range (negative indexing, negative index is > container size) +# before beginning of range (negative indexing, negative index is > +# container size) compare_containers(ps[-7:7], iv[-7:7], il[-7:7]) compare_containers(ps[-100:7], iv[-100:7], il[-100:7]) @@ -222,48 +235,52 @@ compare_containers(ps[::-5], iv[::-5], il[::-5]) # insert sequences (growing, shrinking and staying same size) for start in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: - # single element set/replace - container_insert_step(start, None, None, 111) - for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: - container_insert_step(start, end, None, [111, 222, 333, 444, 555, 666, 777]) - container_insert_step(start, end, None, [111, 222, 333, 444, 555, 666]) - container_insert_step(start, end, None, [111, 222, 333, 444, 555]) - container_insert_step(start, end, None, [111, 222, 333, 444]) - container_insert_step(start, end, None, [111, 222, 333]) - container_insert_step(start, end, None, [111, 222]) - container_insert_step(start, end, None, [111]) - container_insert_step(start, end, None, []) + # single element set/replace + container_insert_step(start, None, None, 111) + for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: + container_insert_step( + start, end, None, [111, 222, 333, 444, 555, 666, 777]) + container_insert_step(start, end, None, [111, 222, 333, 444, 555, 666]) + container_insert_step(start, end, None, [111, 222, 333, 444, 555]) + container_insert_step(start, end, None, [111, 222, 333, 444]) + container_insert_step(start, end, None, [111, 222, 333]) + container_insert_step(start, end, None, [111, 222]) + container_insert_step(start, end, None, [111]) + container_insert_step(start, end, None, []) # delete sequences (growing, shrinking and staying same size) for start in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: - # single element delete - container_delete_step(start, None, None) - for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: - container_delete_step(start, end, None) - for step in range(-7,7): - container_delete_step(start, end, step) + # single element delete + container_delete_step(start, None, None) + for end in [-102, -100, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 100, 102]: + container_delete_step(start, end, None) + for step in range(-7, 7): + container_delete_step(start, end, step) ps = range(6) iv = vector_int(ps) il = list_int(ps) -del ps[:]; del iv[:]; del il[:] +del ps[:] +del iv[:] +del il[:] compare_containers(ps, iv, il) for end in range(7): - for step in range(-7,7): - for start in range(7): - container_insert_step(start, end, step, [111, 222, 333, 444, 555, 666, 777]) - container_insert_step(start, end, step, [111, 222, 333, 444, 555, 666]) - container_insert_step(start, end, step, [111, 222, 333, 444, 555]) - container_insert_step(start, end, step, [111, 222, 333, 444]) - container_insert_step(start, end, step, [111, 222, 333]) - container_insert_step(start, end, step, [111, 222]) - container_insert_step(start, end, step, [111]) - container_insert_step(start, end, step, []) + for step in range(-7, 7): + for start in range(7): + container_insert_step( + start, end, step, [111, 222, 333, 444, 555, 666, 777]) + container_insert_step( + start, end, step, [111, 222, 333, 444, 555, 666]) + container_insert_step(start, end, step, [111, 222, 333, 444, 555]) + container_insert_step(start, end, step, [111, 222, 333, 444]) + container_insert_step(start, end, step, [111, 222, 333]) + container_insert_step(start, end, step, [111, 222]) + container_insert_step(start, end, step, [111]) + container_insert_step(start, end, step, []) try: - x = iv[::0] - raise RuntimeError("Zero step not caught") + x = iv[::0] + raise RuntimeError("Zero step not caught") except ValueError: - pass - + pass diff --git a/Examples/test-suite/python/li_std_except_as_class_runme.py b/Examples/test-suite/python/li_std_except_as_class_runme.py index a86e7a562..36abb33f4 100644 --- a/Examples/test-suite/python/li_std_except_as_class_runme.py +++ b/Examples/test-suite/python/li_std_except_as_class_runme.py @@ -3,17 +3,29 @@ from li_std_except_as_class import * # This test is expected to fail with -builtin option. # Throwing builtin classes as exceptions not supported if is_python_builtin(): - try: test_domain_error() - except RuntimeError: pass - try: test_domain_error() - except RuntimeError: pass - try: test_domain_error() - except RuntimeError: pass + try: + test_domain_error() + except RuntimeError: + pass + try: + test_domain_error() + except RuntimeError: + pass + try: + test_domain_error() + except RuntimeError: + pass else: - # std::domain_error hierarchy - try: test_domain_error() - except domain_error: pass - try: test_domain_error() - except logic_error: pass - try: test_domain_error() - except exception: pass + # std::domain_error hierarchy + try: + test_domain_error() + except domain_error: + pass + try: + test_domain_error() + except logic_error: + pass + try: + test_domain_error() + except exception: + pass diff --git a/Examples/test-suite/python/li_std_map_member_runme.py b/Examples/test-suite/python/li_std_map_member_runme.py index 8b5877dae..d20442472 100644 --- a/Examples/test-suite/python/li_std_map_member_runme.py +++ b/Examples/test-suite/python/li_std_map_member_runme.py @@ -3,9 +3,9 @@ import li_std_map_member a = li_std_map_member.mapita() a[1] = li_std_map_member.TestA() -if (a[1].i != 1) : +if (a[1].i != 1): raise RuntimeError("a[1] != 1") a[1].i = 2 -if (a[1].i != 2) : +if (a[1].i != 2): raise RuntimeError("a[1] != 2") diff --git a/Examples/test-suite/python/li_std_map_runme.py b/Examples/test-suite/python/li_std_map_runme.py index ae75bdda0..af3e1d989 100644 --- a/Examples/test-suite/python/li_std_map_runme.py +++ b/Examples/test-suite/python/li_std_map_runme.py @@ -4,8 +4,8 @@ a1 = li_std_map.A(3) a2 = li_std_map.A(7) -p0 = li_std_map.pairii(1,2) -p1 = li_std_map.pairA(1,a1.this) +p0 = li_std_map.pairii(1, 2) +p1 = li_std_map.pairA(1, a1.this) m = {} m[1] = a1 m[2] = a2 @@ -14,38 +14,33 @@ pp1 = li_std_map.p_identa(p1) mm = li_std_map.m_identa(m) - m = li_std_map.mapA() m[1] = a1 m[2] = a2 -pm ={} +pm = {} for k in m: - pm[k] = m[k] - -for k in m: - if pm[k].this != m[k].this: - print pm[k], m[k] - raise RuntimeError - - + pm[k] = m[k] +for k in m: + if pm[k].this != m[k].this: + print pm[k], m[k] + raise RuntimeError m = {} -m[1] = (1,2) +m[1] = (1, 2) m["foo"] = "hello" pm = li_std_map.pymap() -for k in m: - pm[k] = m[k] - -for k in pm: - if (pm[k] != m[k]): - raise RuntimeError +for k in m: + pm[k] = m[k] +for k in pm: + if (pm[k] != m[k]): + raise RuntimeError mii = li_std_map.IntIntMap() @@ -54,5 +49,4 @@ mii[1] = 1 mii[1] = 2 if mii[1] != 2: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_pair_extra_runme.py b/Examples/test-suite/python/li_std_pair_extra_runme.py index dc6e31b76..f26badf08 100644 --- a/Examples/test-suite/python/li_std_pair_extra_runme.py +++ b/Examples/test-suite/python/li_std_pair_extra_runme.py @@ -1,59 +1,58 @@ import li_std_pair_extra -p = (1,2) +p = (1, 2) p1 = li_std_pair_extra.p_inout(p) p2 = li_std_pair_extra.p_inoutd(p1) d1 = li_std_pair_extra.d_inout(2) -i,d2 = li_std_pair_extra.d_inout2(2) +i, d2 = li_std_pair_extra.d_inout2(2) -i,p = li_std_pair_extra.p_inout2(p) -p3,p4 = li_std_pair_extra.p_inout3(p1,p1) +i, p = li_std_pair_extra.p_inout2(p) +p3, p4 = li_std_pair_extra.p_inout3(p1, p1) -psi = li_std_pair_extra.SIPair("hello",1) -pci = li_std_pair_extra.CIPair(1,1) +psi = li_std_pair_extra.SIPair("hello", 1) +pci = li_std_pair_extra.CIPair(1, 1) #psi.first = "hi" -psi = li_std_pair_extra.SIPair("hi",1) -if psi != ("hi",1): - raise RuntimeError +psi = li_std_pair_extra.SIPair("hi", 1) +if psi != ("hi", 1): + raise RuntimeError -psii = li_std_pair_extra.SIIPair(psi,1) +psii = li_std_pair_extra.SIIPair(psi, 1) a = li_std_pair_extra.A() b = li_std_pair_extra.B() -pab = li_std_pair_extra.ABPair(a,b); +pab = li_std_pair_extra.ABPair(a, b) pab.first = a pab.first.val = 2 if pab.first.val != 2: - raise RuntimeError - + raise RuntimeError -pci = li_std_pair_extra.CIntPair(1,0) + +pci = li_std_pair_extra.CIntPair(1, 0) a = li_std_pair_extra.A(5) -p1 = li_std_pair_extra.pairP1(1,a.this) -p2 = li_std_pair_extra.pairP2(a,1) -p3 = li_std_pair_extra.pairP3(a,a) +p1 = li_std_pair_extra.pairP1(1, a.this) +p2 = li_std_pair_extra.pairP2(a, 1) +p3 = li_std_pair_extra.pairP3(a, a) if a.val != li_std_pair_extra.p_identa(p1.this)[1].val: - raise RuntimeError - -p = li_std_pair_extra.IntPair(1,10) + raise RuntimeError + +p = li_std_pair_extra.IntPair(1, 10) p.first = 1 -p = li_std_pair_extra.paircA1(1,a) +p = li_std_pair_extra.paircA1(1, a) p.first p.second -p = li_std_pair_extra.paircA2(1,a) -pp = li_std_pair_extra.pairiiA(1,p) - +p = li_std_pair_extra.paircA2(1, a) +pp = li_std_pair_extra.pairiiA(1, p) diff --git a/Examples/test-suite/python/li_std_pair_using_runme.py b/Examples/test-suite/python/li_std_pair_using_runme.py index a8b261035..18f962235 100644 --- a/Examples/test-suite/python/li_std_pair_using_runme.py +++ b/Examples/test-suite/python/li_std_pair_using_runme.py @@ -6,5 +6,4 @@ two_tuple = ("two", 2) two = StringIntPair(two_tuple) if bounce(one) != one_tuple: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_set_runme.py b/Examples/test-suite/python/li_std_set_runme.py index 449333e73..ad3c6d881 100644 --- a/Examples/test-suite/python/li_std_set_runme.py +++ b/Examples/test-suite/python/li_std_set_runme.py @@ -25,7 +25,7 @@ if i.next() != "c": b = s.begin() e = s.end() sum = "" -while (b != e): +while (b != e): sum = sum + b.next() if sum != "abc": raise RuntimeError @@ -33,14 +33,13 @@ if sum != "abc": b = s.rbegin() e = s.rend() sum = "" -while (b != e): - sum = sum + b.next() +while (b != e): + sum = sum + b.next() if sum != "cba": raise RuntimeError - si = set_int() si.append(1) @@ -56,8 +55,6 @@ if i.next() != 3: raise RuntimeError - - i = s.begin() i.next() s.erase(i) @@ -65,7 +62,7 @@ s.erase(i) b = s.begin() e = s.end() sum = "" -while (b != e): +while (b != e): sum = sum + b.next() if sum != "ac": raise RuntimeError @@ -75,22 +72,21 @@ b = s.begin() e = s.end() if e - b != 2: raise RuntimeError - + m = b + 1 if m.value() != "c": raise RuntimeError - s = pyset() -s.insert((1,2)) +s.insert((1, 2)) s.insert(1) s.insert("hello") sum = () for i in s: - sum = sum + (i,) + sum = sum + (i,) -if (len(sum) != 3 or (not 1 in sum) or (not 'hello' in sum) or (not (1, 2) in sum)) : +if (len(sum) != 3 or (not 1 in sum) or (not 'hello' in sum) or (not (1, 2) in sum)): raise RuntimeError diff --git a/Examples/test-suite/python/li_std_stream_runme.py b/Examples/test-suite/python/li_std_stream_runme.py index d41e41f4a..08c308856 100644 --- a/Examples/test-suite/python/li_std_stream_runme.py +++ b/Examples/test-suite/python/li_std_stream_runme.py @@ -1,7 +1,6 @@ from li_std_stream import * - a = A() o = ostringstream() @@ -9,6 +8,6 @@ o = ostringstream() o << a << " " << 2345 << " " << 1.435 -if o.str() != "A class 2345 1.435": - print "\"%s\"" % (o.str(),) - raise RuntimeError +if o.str() != "A class 2345 1.435": + print "\"%s\"" % (o.str(),) + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_string_extra_runme.py b/Examples/test-suite/python/li_std_string_extra_runme.py index 503d09eb5..b65f0774a 100644 --- a/Examples/test-suite/python/li_std_string_extra_runme.py +++ b/Examples/test-suite/python/li_std_string_extra_runme.py @@ -1,135 +1,134 @@ import li_std_string_extra -x="hello" - +x = "hello" if li_std_string_extra.test_ccvalue(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_cvalue(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_value(x) != x: - print x, li_std_string_extra.test_value(x) - raise RuntimeError, "bad string mapping" + print x, li_std_string_extra.test_value(x) + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_const_reference(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" s = li_std_string_extra.string("he") #s += "ll" -#s.append('o') +# s.append('o') s = s + "llo" if s != x: - print s, x - raise RuntimeError, "bad string mapping" + print s, x + raise RuntimeError, "bad string mapping" if s[1:4] != x[1:4]: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_value(s) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_const_reference(s) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" a = li_std_string_extra.A(s) if li_std_string_extra.test_value(a) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_const_reference(a) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" b = li_std_string_extra.string(" world") s = a + b if a + b != "hello world": - print a + b - raise RuntimeError, "bad string mapping" - + print a + b + raise RuntimeError, "bad string mapping" + if a + " world" != "hello world": - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" # This is expected to fail with -builtin option # Reverse operators not supported in builtin types if not li_std_string_extra.is_python_builtin(): - if "hello" + b != "hello world": - raise RuntimeError, "bad string mapping" + if "hello" + b != "hello world": + raise RuntimeError, "bad string mapping" + + c = "hello" + b + if c.find_last_of("l") != 9: + raise RuntimeError, "bad string mapping" - c = "hello" + b - if c.find_last_of("l") != 9: - raise RuntimeError, "bad string mapping" - s = "hello world" b = li_std_string_extra.B("hi") b.name = li_std_string_extra.string("hello") if b.name != "hello": - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" b.a = li_std_string_extra.A("hello") if b.a != "hello": - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_value_basic1(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_value_basic2(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" if li_std_string_extra.test_value_basic3(x) != x: - raise RuntimeError, "bad string mapping" + raise RuntimeError, "bad string mapping" # Global variables s = "initial string" if li_std_string_extra.cvar.GlobalString2 != "global string 2": - raise RuntimeError, "GlobalString2 test 1" + raise RuntimeError, "GlobalString2 test 1" li_std_string_extra.cvar.GlobalString2 = s if li_std_string_extra.cvar.GlobalString2 != s: - raise RuntimeError, "GlobalString2 test 2" + raise RuntimeError, "GlobalString2 test 2" if li_std_string_extra.cvar.ConstGlobalString != "const global string": - raise RuntimeError, "ConstGlobalString test" + raise RuntimeError, "ConstGlobalString test" # Member variables myStructure = li_std_string_extra.Structure() if myStructure.MemberString2 != "member string 2": - raise RuntimeError, "MemberString2 test 1" + raise RuntimeError, "MemberString2 test 1" myStructure.MemberString2 = s if myStructure.MemberString2 != s: - raise RuntimeError, "MemberString2 test 2" + raise RuntimeError, "MemberString2 test 2" if myStructure.ConstMemberString != "const member string": - raise RuntimeError, "ConstMemberString test" + raise RuntimeError, "ConstMemberString test" if li_std_string_extra.cvar.Structure_StaticMemberString2 != "static member string 2": - raise RuntimeError, "StaticMemberString2 test 1" + raise RuntimeError, "StaticMemberString2 test 1" li_std_string_extra.cvar.Structure_StaticMemberString2 = s if li_std_string_extra.cvar.Structure_StaticMemberString2 != s: - raise RuntimeError, "StaticMemberString2 test 2" + raise RuntimeError, "StaticMemberString2 test 2" if li_std_string_extra.cvar.Structure_ConstStaticMemberString != "const static member string": - raise RuntimeError, "ConstStaticMemberString test" + raise RuntimeError, "ConstStaticMemberString test" if li_std_string_extra.test_reference_input("hello") != "hello": - raise RuntimeError + raise RuntimeError s = li_std_string_extra.test_reference_inout("hello") if s != "hellohello": - raise RuntimeError + raise RuntimeError if li_std_string_extra.stdstring_empty() != "": - raise RuntimeError - + raise RuntimeError + if li_std_string_extra.c_empty() != "": - raise RuntimeError + raise RuntimeError if li_std_string_extra.c_null() != None: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_vector_enum_runme.py b/Examples/test-suite/python/li_std_vector_enum_runme.py index a2c8534f3..318d1bff6 100644 --- a/Examples/test-suite/python/li_std_vector_enum_runme.py +++ b/Examples/test-suite/python/li_std_vector_enum_runme.py @@ -1,8 +1,9 @@ import li_std_vector_enum + def check(a, b): - if (a != b): - raise RuntimeError("Not equal: ", a, b) + if (a != b): + raise RuntimeError("Not equal: ", a, b) ev = li_std_vector_enum.EnumVector() @@ -17,8 +18,7 @@ it.next() v = it.value() check(v, 20) -expected = 10 +expected = 10 for val in ev.nums: - check(val, expected) - expected += 10 - + check(val, expected) + expected += 10 diff --git a/Examples/test-suite/python/li_std_vector_extra_runme.py b/Examples/test-suite/python/li_std_vector_extra_runme.py index d24d36cb6..d541de6db 100644 --- a/Examples/test-suite/python/li_std_vector_extra_runme.py +++ b/Examples/test-suite/python/li_std_vector_extra_runme.py @@ -1,110 +1,108 @@ from li_std_vector_extra import * iv = IntVector(4) -for i in range(0,4): +for i in range(0, 4): iv[i] = i x = average(iv) -y = average([1,2,3,4]) +y = average([1, 2, 3, 4]) -a = half([10,10.5,11,11.5]) +a = half([10, 10.5, 11, 11.5]) dv = DoubleVector(10) -for i in range(0,10): - dv[i] = i/2.0 +for i in range(0, 10): + dv[i] = i / 2.0 halve_in_place(dv) bv = BoolVector(4) -bv[0]= bool(1) -bv[1]= bool(0) -bv[2]= bool(4) -bv[3]= bool(0) +bv[0] = bool(1) +bv[1] = bool(0) +bv[2] = bool(4) +bv[3] = bool(0) if bv[0] != bv[2]: - raise RuntimeError,"bad std::vector mapping" + raise RuntimeError, "bad std::vector mapping" b = B(5) -va = VecA([b,None,b,b]) +va = VecA([b, None, b, b]) if va[0].f(1) != 6: - raise RuntimeError,"bad std::vector mapping" + raise RuntimeError, "bad std::vector mapping" if vecAptr(va) != 6: - raise RuntimeError,"bad std::vector mapping" + raise RuntimeError, "bad std::vector mapping" b.val = 7 if va[3].f(1) != 8: - raise RuntimeError,"bad std::vector mapping" + raise RuntimeError, "bad std::vector mapping" ip = PtrInt() ap = new_ArrInt(10) -ArrInt_setitem(ip,0,123) -ArrInt_setitem(ap,2,123) +ArrInt_setitem(ip, 0, 123) +ArrInt_setitem(ap, 2, 123) -vi = IntPtrVector((ip,ap,None)) -if ArrInt_getitem(vi[0],0) != ArrInt_getitem(vi[1],2): - raise RuntimeError,"bad std::vector mapping" +vi = IntPtrVector((ip, ap, None)) +if ArrInt_getitem(vi[0], 0) != ArrInt_getitem(vi[1], 2): + raise RuntimeError, "bad std::vector mapping" -delete_ArrInt(ap) +delete_ArrInt(ap) -a = halfs([10,8,4,3]) +a = halfs([10, 8, 4, 3]) v = IntVector() -v[0:2] = [1,2] +v[0:2] = [1, 2] if v[0] != 1 or v[1] != 2: - raise RuntimeError,"bad setslice" + raise RuntimeError, "bad setslice" if v[0:-1][0] != 1: - raise RuntimeError,"bad getslice" + raise RuntimeError, "bad getslice" if v[0:-2].size() != 0: - raise RuntimeError,"bad getslice" + raise RuntimeError, "bad getslice" v[0:1] = [2] if v[0] != 2: - raise RuntimeError,"bad setslice" + raise RuntimeError, "bad setslice" v[1:] = [3] if v[1] != 3: - raise RuntimeError,"bad setslice" + raise RuntimeError, "bad setslice" v[2:] = [3] if v[2] != 3: - raise RuntimeError,"bad setslice" + raise RuntimeError, "bad setslice" if v[0:][0] != v[0]: - raise RuntimeError,"bad getslice" + raise RuntimeError, "bad getslice" del v[:] if v.size() != 0: - raise RuntimeError,"bad getslice" + raise RuntimeError, "bad getslice" del v[:] if v.size() != 0: - raise RuntimeError,"bad getslice" - + raise RuntimeError, "bad getslice" v = vecStr(["hello ", "world"]) if v[0] != 'hello world': - raise RuntimeError,"bad std::string+std::vector" - + raise RuntimeError, "bad std::string+std::vector" -pv = pyvector([1, "hello", (1,2)]) +pv = pyvector([1, "hello", (1, 2)]) if pv[1] != "hello": raise RuntimeError iv = IntVector(5) -for i in range(0,5): +for i in range(0, 5): iv[i] = i iv[1:3] = [] @@ -113,25 +111,25 @@ if iv[1] != 3: # Overloading checks if overloaded1(iv) != "vector": - raise RuntimeError + raise RuntimeError if overloaded1(dv) != "vector": - raise RuntimeError + raise RuntimeError if overloaded2(iv) != "vector": - raise RuntimeError + raise RuntimeError if overloaded2(dv) != "vector": - raise RuntimeError + raise RuntimeError if overloaded3(iv) != "vector *": - raise RuntimeError + raise RuntimeError if overloaded3(None) != "vector *": - raise RuntimeError + raise RuntimeError if overloaded3(100) != "int": - raise RuntimeError + raise RuntimeError # vector pointer checks @@ -139,38 +137,39 @@ ip = makeIntPtr(11) dp = makeDoublePtr(33.3) error = 0 try: - vi = IntPtrVector((ip, dp)) # check vector does not accept double * element - error = 1 + # check vector does not accept double * element + vi = IntPtrVector((ip, dp)) + error = 1 except: - pass + pass if error: - raise RuntimeError + raise RuntimeError vi = IntPtrVector((ip, makeIntPtr(22))) if extractInt(vi[0]) != 11: - raise RuntimeError + raise RuntimeError if extractInt(vi[1]) != 22: - raise RuntimeError + raise RuntimeError # vector const pointer checks csp = makeConstShortPtr(111) error = 0 try: - vcs = ConstShortPtrVector((csp, dp)) # check vector does not accept double * element - error = 1 + # check vector does not accept double * element + vcs = ConstShortPtrVector((csp, dp)) + error = 1 except: - pass + pass if error: - raise RuntimeError + raise RuntimeError vcs = ConstShortPtrVector((csp, makeConstShortPtr(222))) if extractConstShort(vcs[0]) != 111: - raise RuntimeError + raise RuntimeError if extractConstShort(vcs[1]) != 222: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_vector_ptr_runme.py b/Examples/test-suite/python/li_std_vector_ptr_runme.py index c5f72fde4..01c654109 100644 --- a/Examples/test-suite/python/li_std_vector_ptr_runme.py +++ b/Examples/test-suite/python/li_std_vector_ptr_runme.py @@ -5,4 +5,3 @@ ip2 = makeIntPtr(22) vi = IntPtrVector((ip1, ip2)) displayVector(vi) - diff --git a/Examples/test-suite/python/li_std_wstream_runme.py b/Examples/test-suite/python/li_std_wstream_runme.py index f7379bdf8..045645b61 100644 --- a/Examples/test-suite/python/li_std_wstream_runme.py +++ b/Examples/test-suite/python/li_std_wstream_runme.py @@ -1,13 +1,12 @@ from li_std_wstream import * - a = A() o = wostringstream() o << a << u" " << 2345 << u" " << 1.435 << wends -if o.str() != "A class 2345 1.435\0": - print "\"%s\"" % (o.str(),) - raise RuntimeError +if o.str() != "A class 2345 1.435\0": + print "\"%s\"" % (o.str(),) + raise RuntimeError diff --git a/Examples/test-suite/python/li_std_wstring_runme.py b/Examples/test-suite/python/li_std_wstring_runme.py index a467ae8bc..e93196b80 100644 --- a/Examples/test-suite/python/li_std_wstring_runme.py +++ b/Examples/test-suite/python/li_std_wstring_runme.py @@ -1,85 +1,83 @@ import li_std_wstring -x=u"h" +x = u"h" if li_std_wstring.test_wcvalue(x) != x: - print li_std_wstring.test_wcvalue(x) - raise RuntimeError("bad string mapping") + print li_std_wstring.test_wcvalue(x) + raise RuntimeError("bad string mapping") -x=u"hello" +x = u"hello" if li_std_wstring.test_ccvalue(x) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_cvalue(x) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_wchar_overload(x) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_wchar_overload("not unicode") != "not unicode": - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_value(x) != x: - print x, li_std_wstring.test_value(x) - raise RuntimeError("bad string mapping") + print x, li_std_wstring.test_value(x) + raise RuntimeError("bad string mapping") if li_std_wstring.test_const_reference(x) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") s = li_std_wstring.wstring(u"he") s = s + u"llo" if s != x: - print s, x - raise RuntimeError("bad string mapping") + print s, x + raise RuntimeError("bad string mapping") if s[1:4] != x[1:4]: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_value(s) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_const_reference(s) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") a = li_std_wstring.A(s) if li_std_wstring.test_value(a) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") if li_std_wstring.test_const_reference(a) != x: - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") b = li_std_wstring.wstring(" world") if a + b != "hello world": - raise RuntimeError("bad string mapping") - + raise RuntimeError("bad string mapping") + if a + " world" != "hello world": - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") # This is expected to fail if -builtin is used # Reverse operators not supported in builtin types if not li_std_wstring.is_python_builtin(): - if "hello" + b != "hello world": - raise RuntimeError("bad string mapping") + if "hello" + b != "hello world": + raise RuntimeError("bad string mapping") + + c = "hello" + b + if c.find_last_of("l") != 9: + raise RuntimeError("bad string mapping") - c = "hello" + b - if c.find_last_of("l") != 9: - raise RuntimeError("bad string mapping") - s = "hello world" b = li_std_wstring.B("hi") b.name = li_std_wstring.wstring(u"hello") if b.name != "hello": - raise RuntimeError("bad string mapping") + raise RuntimeError("bad string mapping") b.a = li_std_wstring.A("hello") if b.a != u"hello": - raise RuntimeError("bad string mapping") - - + raise RuntimeError("bad string mapping") diff --git a/Examples/test-suite/python/member_pointer_runme.py b/Examples/test-suite/python/member_pointer_runme.py index 3d68e916d..5ae7ab9a4 100644 --- a/Examples/test-suite/python/member_pointer_runme.py +++ b/Examples/test-suite/python/member_pointer_runme.py @@ -2,9 +2,11 @@ from member_pointer import * + def check(what, expected, actual): - if expected != actual: - raise RuntimeError ("Failed: " , what , " Expected: " , expected , " Actual: " , actual) + if expected != actual: + raise RuntimeError( + "Failed: ", what, " Expected: ", expected, " Actual: ", actual) # Get the pointers @@ -17,20 +19,20 @@ s = Square(10) # Do some calculations -check ("Square area ", 100.0, do_op(s,area_pt)) -check ("Square perim", 40.0, do_op(s,perim_pt)) +check("Square area ", 100.0, do_op(s, area_pt)) +check("Square perim", 40.0, do_op(s, perim_pt)) memberPtr = cvar.areavar memberPtr = cvar.perimetervar # Try the variables -check ("Square area ", 100.0, do_op(s,cvar.areavar)) -check ("Square perim", 40.0, do_op(s,cvar.perimetervar)) +check("Square area ", 100.0, do_op(s, cvar.areavar)) +check("Square perim", 40.0, do_op(s, cvar.perimetervar)) # Modify one of the variables cvar.areavar = perim_pt -check ("Square perimeter", 40.0, do_op(s,cvar.areavar)) +check("Square perimeter", 40.0, do_op(s, cvar.areavar)) # Try the constants @@ -38,9 +40,9 @@ memberPtr = AREAPT memberPtr = PERIMPT memberPtr = NULLPT -check ("Square area ", 100.0, do_op(s,AREAPT)) -check ("Square perim", 40.0, do_op(s,PERIMPT)) +check("Square area ", 100.0, do_op(s, AREAPT)) +check("Square perim", 40.0, do_op(s, PERIMPT)) -check ("Add by value", 3, call1(ADD_BY_VALUE, 1, 2)) -check ("Add by pointer", 7, call2(ADD_BY_POINTER, 3, 4)) -check ("Add by reference", 11, call3(ADD_BY_REFERENCE, 5, 6)) +check("Add by value", 3, call1(ADD_BY_VALUE, 1, 2)) +check("Add by pointer", 7, call2(ADD_BY_POINTER, 3, 4)) +check("Add by reference", 11, call3(ADD_BY_REFERENCE, 5, 6)) diff --git a/Examples/test-suite/python/memberin_extend_c_runme.py b/Examples/test-suite/python/memberin_extend_c_runme.py index 314761f89..da601ae2a 100644 --- a/Examples/test-suite/python/memberin_extend_c_runme.py +++ b/Examples/test-suite/python/memberin_extend_c_runme.py @@ -3,4 +3,4 @@ import memberin_extend_c t = memberin_extend_c.Person() t.name = "Fred Bloggs" if t.name != "FRED BLOGGS": - raise RuntimeError("name wrong") + raise RuntimeError("name wrong") diff --git a/Examples/test-suite/python/minherit_runme.py b/Examples/test-suite/python/minherit_runme.py index d7ad0b36b..b7e7d019c 100644 --- a/Examples/test-suite/python/minherit_runme.py +++ b/Examples/test-suite/python/minherit_runme.py @@ -10,26 +10,28 @@ if a.xget() != 1: raise RuntimeError, "Bad attribute value" if b.yget() != 2: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if c.xget() != 1 or c.yget() != 2 or c.zget() != 3: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if d.xget() != 1 or d.yget() != 2 or d.zget() != 3 or d.wget() != 4: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if minherit.xget(a) != 1: - raise RuntimeError, "Bad attribute value %d" % (minherit.xget(a)) + raise RuntimeError, "Bad attribute value %d" % (minherit.xget(a)) if minherit.yget(b) != 2: - raise RuntimeError, "Bad attribute value %d" % (minherit.yget(b)) + raise RuntimeError, "Bad attribute value %d" % (minherit.yget(b)) if minherit.xget(c) != 1 or minherit.yget(c) != 2 or minherit.zget(c) != 3: - raise RuntimeError, "Bad attribute value %d %d %d" % (minherit.xget(c), minherit.yget(c), minherit.zget(c)) + raise RuntimeError, "Bad attribute value %d %d %d" % ( + minherit.xget(c), minherit.yget(c), minherit.zget(c)) if minherit.xget(d) != 1 or minherit.yget(d) != 2 or minherit.zget(d) != 3 or minherit.wget(d) != 4: - raise RuntimeError, "Bad attribute value %d %d %d %d" % (minherit.xget(d), minherit.yget(d), minherit.zget(d), minherit.wget(d)) + raise RuntimeError, "Bad attribute value %d %d %d %d" % ( + minherit.xget(d), minherit.yget(d), minherit.zget(d), minherit.wget(d)) # Cleanse all of the pointers and see what happens @@ -42,30 +44,24 @@ if aa.xget() != 1: raise RuntimeError, "Bad attribute value" if bb.yget() != 2: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if cc.xget() != 1 or cc.yget() != 2 or cc.zget() != 3: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if dd.xget() != 1 or dd.yget() != 2 or dd.zget() != 3 or dd.wget() != 4: - raise RuntimeError, "Bad attribute value" + raise RuntimeError, "Bad attribute value" if minherit.xget(aa) != 1: - raise RuntimeError, "Bad attribute value %d" % (minherit.xget(aa)) + raise RuntimeError, "Bad attribute value %d" % (minherit.xget(aa)) if minherit.yget(bb) != 2: - raise RuntimeError, "Bad attribute value %d" % (minherit.yget(bb)) + raise RuntimeError, "Bad attribute value %d" % (minherit.yget(bb)) if minherit.xget(cc) != 1 or minherit.yget(cc) != 2 or minherit.zget(cc) != 3: - raise RuntimeError, "Bad attribute value %d %d %d" % (minherit.xget(cc), minherit.yget(cc), minherit.zget(cc)) + raise RuntimeError, "Bad attribute value %d %d %d" % ( + minherit.xget(cc), minherit.yget(cc), minherit.zget(cc)) if minherit.xget(dd) != 1 or minherit.yget(dd) != 2 or minherit.zget(dd) != 3 or minherit.wget(dd) != 4: - raise RuntimeError, "Bad attribute value %d %d %d %d" % (minherit.xget(dd), minherit.yget(dd), minherit.zget(dd), minherit.wget(dd)) - - - - - - - - + raise RuntimeError, "Bad attribute value %d %d %d %d" % ( + minherit.xget(dd), minherit.yget(dd), minherit.zget(dd), minherit.wget(dd)) diff --git a/Examples/test-suite/python/multi_import_runme.py b/Examples/test-suite/python/multi_import_runme.py index f8a2f19c7..27f86a9ef 100644 --- a/Examples/test-suite/python/multi_import_runme.py +++ b/Examples/test-suite/python/multi_import_runme.py @@ -3,16 +3,16 @@ import multi_import_b x = multi_import_b.XXX() if x.testx() != 0: - raise RuntimeError + raise RuntimeError y = multi_import_b.YYY() if y.testx() != 0: - raise RuntimeError + raise RuntimeError if y.testy() != 1: - raise RuntimeError + raise RuntimeError z = multi_import_a.ZZZ() if z.testx() != 0: - raise RuntimeError + raise RuntimeError if z.testz() != 2: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/namespace_class_runme.py b/Examples/test-suite/python/namespace_class_runme.py index e009f9515..e0bd3ca09 100644 --- a/Examples/test-suite/python/namespace_class_runme.py +++ b/Examples/test-suite/python/namespace_class_runme.py @@ -1,30 +1,31 @@ from namespace_class import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") try: - p = Private1() - error = 1 + p = Private1() + error = 1 except: - error = 0 + error = 0 if (error): - raise RuntimeError, "Private1 is private" + raise RuntimeError, "Private1 is private" try: - p = Private2() - error = 1 + p = Private2() + error = 1 except: - error = 0 + error = 0 if (error): - raise RuntimeError, "Private2 is private" + raise RuntimeError, "Private2 is private" if is_new_style_class(EulerT3D): - EulerT3D.toFrame(1,1,1) + EulerT3D.toFrame(1, 1, 1) else: - EulerT3D().toFrame(1,1,1) + EulerT3D().toFrame(1, 1, 1) b = BooT_i() b = BooT_H() @@ -40,6 +41,6 @@ f = FooT_H() f.foo(Hi) if is_new_style_class(FooT_H): - f_type = str(type(f)) - if f_type.find("'namespace_class.FooT_H'") == -1: - raise RuntimeError("Incorrect type: " + f_type) + f_type = str(type(f)) + if f_type.find("'namespace_class.FooT_H'") == -1: + raise RuntimeError("Incorrect type: " + f_type) diff --git a/Examples/test-suite/python/namespace_typemap_runme.py b/Examples/test-suite/python/namespace_typemap_runme.py index 682ad3bb1..14379496d 100644 --- a/Examples/test-suite/python/namespace_typemap_runme.py +++ b/Examples/test-suite/python/namespace_typemap_runme.py @@ -36,7 +36,7 @@ if stest11("hello") != "hello": if stest12("hello") != "hello": raise RuntimeError -c = complex(2,3) +c = complex(2, 3) r = c.real if ctest1(c) != r: diff --git a/Examples/test-suite/python/nested_template_base_runme.py b/Examples/test-suite/python/nested_template_base_runme.py index 3d54b8391..fc5844300 100644 --- a/Examples/test-suite/python/nested_template_base_runme.py +++ b/Examples/test-suite/python/nested_template_base_runme.py @@ -1,13 +1,13 @@ from nested_template_base import * -ois = InnerS(123); -oic = InnerC(); +ois = InnerS(123) +oic = InnerC() # Check base method is available if (oic.outer(ois).val != 123): - raise RuntimeError("Wrong value calling outer"); + raise RuntimeError("Wrong value calling outer") # Check non-derived class using base class if (oic.innerc().outer(ois).val != 123): - raise RuntimeError("Wrong value calling innerc"); + raise RuntimeError("Wrong value calling innerc") diff --git a/Examples/test-suite/python/nested_workaround_runme.py b/Examples/test-suite/python/nested_workaround_runme.py index a8a75d370..c11299ed4 100644 --- a/Examples/test-suite/python/nested_workaround_runme.py +++ b/Examples/test-suite/python/nested_workaround_runme.py @@ -4,10 +4,10 @@ inner = Inner(5) outer = Outer() newInner = outer.doubleInnerValue(inner) if newInner.getValue() != 10: - raise RuntimeError + raise RuntimeError outer = Outer() inner = outer.createInner(3) newInner = outer.doubleInnerValue(inner) if outer.getInnerValue(newInner) != 6: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/operbool_runme.py b/Examples/test-suite/python/operbool_runme.py index 4218b5dd4..708dea786 100644 --- a/Examples/test-suite/python/operbool_runme.py +++ b/Examples/test-suite/python/operbool_runme.py @@ -1,4 +1,3 @@ #!/usr/bin/env python import operbool assert not operbool.Test() - diff --git a/Examples/test-suite/python/overload_bool_runme.py b/Examples/test-suite/python/overload_bool_runme.py index ed7d1b5a1..8192b37ce 100644 --- a/Examples/test-suite/python/overload_bool_runme.py +++ b/Examples/test-suite/python/overload_bool_runme.py @@ -2,25 +2,25 @@ import overload_bool # Overloading bool, int, string if overload_bool.overloaded(True) != "bool": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded(False) != "bool": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded(0) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded(1) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded(2) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded("1234") != "string": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") # Test bool masquerading as int if overload_bool.intfunction(True) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.intfunction(False) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") # Test int masquerading as bool # Not possible @@ -30,26 +30,25 @@ if overload_bool.intfunction(False) != "int": # Overloading bool, int, string if overload_bool.overloaded_ref(True) != "bool": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded_ref(False) != "bool": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded_ref(0) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded_ref(1) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded_ref(2) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.overloaded_ref("1234") != "string": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") # Test bool masquerading as int if overload_bool.intfunction_ref(True) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") if overload_bool.intfunction_ref(False) != "int": - raise RuntimeError("wrong!") + raise RuntimeError("wrong!") # Test int masquerading as bool # Not possible - diff --git a/Examples/test-suite/python/overload_complicated_runme.py b/Examples/test-suite/python/overload_complicated_runme.py index 2b7467d4d..9c039a0a5 100644 --- a/Examples/test-suite/python/overload_complicated_runme.py +++ b/Examples/test-suite/python/overload_complicated_runme.py @@ -7,41 +7,41 @@ p = Pop(pInt) p = Pop(pInt, 0) -# Check overloaded in const only and pointers/references which target languages cannot disambiguate +# Check overloaded in const only and pointers/references which target +# languages cannot disambiguate if p.hip(0) != 701: - raise RuntimeError,"Test 1 failed" + raise RuntimeError, "Test 1 failed" if p.hip(pInt) != 702: - raise RuntimeError,"Test 2 failed" + raise RuntimeError, "Test 2 failed" # Reverse the order for the above if p.hop(pInt) != 805: - raise RuntimeError,"Test 3 failed" + raise RuntimeError, "Test 3 failed" if p.hop(0) != 801: - raise RuntimeError,"Test 4 failed" + raise RuntimeError, "Test 4 failed" # Few more variations and order shuffled if p.pop(0) != 901: - raise RuntimeError,"Test 5 failed" + raise RuntimeError, "Test 5 failed" if p.pop(pInt) != 902: - raise RuntimeError,"Test 6 failed" + raise RuntimeError, "Test 6 failed" if p.pop() != 905: - raise RuntimeError,"Test 7 failed" + raise RuntimeError, "Test 7 failed" # Overload on const only if p.bop(pInt) != 1001: - raise RuntimeError,"Test 8 failed" + raise RuntimeError, "Test 8 failed" if p.bip(pInt) != 2001: - raise RuntimeError,"Test 9 failed" + raise RuntimeError, "Test 9 failed" # Globals if muzak(0) != 3001: - raise RuntimeError,"Test 10 failed" + raise RuntimeError, "Test 10 failed" if muzak(pInt) != 3002: - raise RuntimeError,"Test 11 failed" - + raise RuntimeError, "Test 11 failed" diff --git a/Examples/test-suite/python/overload_extend_runme.py b/Examples/test-suite/python/overload_extend_runme.py index 7d08d482b..4a8a0165e 100644 --- a/Examples/test-suite/python/overload_extend_runme.py +++ b/Examples/test-suite/python/overload_extend_runme.py @@ -7,8 +7,7 @@ if f.test(3) != 1: raise RuntimeError if f.test("hello") != 2: raise RuntimeError -if f.test(3,2) != 5: +if f.test(3, 2) != 5: raise RuntimeError if f.test(3.0) != 1003: raise RuntimeError - diff --git a/Examples/test-suite/python/overload_extendc_runme.py b/Examples/test-suite/python/overload_extendc_runme.py index cea3ea618..ffd074a9d 100644 --- a/Examples/test-suite/python/overload_extendc_runme.py +++ b/Examples/test-suite/python/overload_extendc_runme.py @@ -5,18 +5,17 @@ if f.test(3) != 1: raise RuntimeError if f.test("hello") != 2: raise RuntimeError -if f.test(3.5,2.5) != 3: +if f.test(3.5, 2.5) != 3: raise RuntimeError -if f.test("hello",20) != 1020: +if f.test("hello", 20) != 1020: raise RuntimeError -if f.test("hello",20,100) != 120: +if f.test("hello", 20, 100) != 120: raise RuntimeError # C default args if f.test(f) != 30: raise RuntimeError -if f.test(f,100) != 120: +if f.test(f, 100) != 120: raise RuntimeError -if f.test(f,100,200) != 300: +if f.test(f, 100, 200) != 300: raise RuntimeError - diff --git a/Examples/test-suite/python/overload_numeric_runme.py b/Examples/test-suite/python/overload_numeric_runme.py index 639fb5e5d..9f3382d86 100644 --- a/Examples/test-suite/python/overload_numeric_runme.py +++ b/Examples/test-suite/python/overload_numeric_runme.py @@ -5,9 +5,10 @@ import math nums = Nums() limits = Limits() + def check(got, expected): - if got != expected: - raise RuntimeError("got: " + got + " expected: " + expected) + if got != expected: + raise RuntimeError("got: " + got + " expected: " + expected) check(nums.over(0), "signed char") check(nums.over(0.0), "float") @@ -15,21 +16,21 @@ check(nums.over(0.0), "float") check(nums.over(limits.schar_min()), "signed char") check(nums.over(limits.schar_max()), "signed char") -check(nums.over(limits.schar_min()-1), "short") -check(nums.over(limits.schar_max()+1), "short") +check(nums.over(limits.schar_min() - 1), "short") +check(nums.over(limits.schar_max() + 1), "short") check(nums.over(limits.shrt_min()), "short") check(nums.over(limits.shrt_max()), "short") -check(nums.over(limits.shrt_min()-1), "int") -check(nums.over(limits.shrt_max()+1), "int") +check(nums.over(limits.shrt_min() - 1), "int") +check(nums.over(limits.shrt_max() + 1), "int") check(nums.over(limits.int_min()), "int") check(nums.over(limits.int_max()), "int") check(nums.over(limits.flt_min()), "float") check(nums.over(limits.flt_max()), "float") -check(nums.over(limits.flt_max()*10), "double") -check(nums.over(-limits.flt_max()*10), "double") +check(nums.over(limits.flt_max() * 10), "double") +check(nums.over(-limits.flt_max() * 10), "double") check(nums.over(limits.dbl_max()), "double") check(nums.over(-limits.dbl_max()), "double") diff --git a/Examples/test-suite/python/overload_rename_runme.py b/Examples/test-suite/python/overload_rename_runme.py index b192f7d5d..dcad1b95a 100644 --- a/Examples/test-suite/python/overload_rename_runme.py +++ b/Examples/test-suite/python/overload_rename_runme.py @@ -2,7 +2,6 @@ import overload_rename f = overload_rename.Foo(1) -f = overload_rename.Foo(1,1) -f = overload_rename.Foo_int(1,1) -f = overload_rename.Foo_int(1,1,1) - +f = overload_rename.Foo(1, 1) +f = overload_rename.Foo_int(1, 1) +f = overload_rename.Foo_int(1, 1, 1) diff --git a/Examples/test-suite/python/overload_simple_runme.py b/Examples/test-suite/python/overload_simple_runme.py index a78f3720a..6d72ec081 100644 --- a/Examples/test-suite/python/overload_simple_runme.py +++ b/Examples/test-suite/python/overload_simple_runme.py @@ -70,7 +70,7 @@ if s.type != "none": s = Spam(3) if s.type != "int": raise RuntimeError, "Spam(int)" - + s = Spam(3.4) if s.type != "double": raise RuntimeError, "Spam(double)" @@ -92,9 +92,6 @@ if s.type != "void *": raise RuntimeError, "Spam(void *)" - - - free_void(v) diff --git a/Examples/test-suite/python/overload_subtype_runme.py b/Examples/test-suite/python/overload_subtype_runme.py index 6bf77dc59..3f32a5583 100644 --- a/Examples/test-suite/python/overload_subtype_runme.py +++ b/Examples/test-suite/python/overload_subtype_runme.py @@ -8,4 +8,3 @@ if spam(f) != 1: if spam(b) != 2: raise RuntimeError, "bar" - diff --git a/Examples/test-suite/python/overload_template_fast_runme.py b/Examples/test-suite/python/overload_template_fast_runme.py index 299b91db8..95349a9b1 100644 --- a/Examples/test-suite/python/overload_template_fast_runme.py +++ b/Examples/test-suite/python/overload_template_fast_runme.py @@ -1,83 +1,84 @@ from overload_template_fast import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") f = foo() -a = maximum(3,4) -b = maximum(3.4,5.2) +a = maximum(3, 4) +b = maximum(3.4, 5.2) # mix 1 if (mix1("hi") != 101): - raise RuntimeError, ("mix1(const char*)") + raise RuntimeError, ("mix1(const char*)") if (mix1(1.0, 1.0) != 102): - raise RuntimeError, ("mix1(double, const double &)") + raise RuntimeError, ("mix1(double, const double &)") if (mix1(1.0) != 103): - raise RuntimeError, ("mix1(double)") + raise RuntimeError, ("mix1(double)") # mix 2 if (mix2("hi") != 101): - raise RuntimeError, ("mix2(const char*)") + raise RuntimeError, ("mix2(const char*)") if (mix2(1.0, 1.0) != 102): - raise RuntimeError, ("mix2(double, const double &)") + raise RuntimeError, ("mix2(double, const double &)") if (mix2(1.0) != 103): - raise RuntimeError, ("mix2(double)") + raise RuntimeError, ("mix2(double)") # mix 3 if (mix3("hi") != 101): - raise RuntimeError, ("mix3(const char*)") + raise RuntimeError, ("mix3(const char*)") if (mix3(1.0, 1.0) != 102): - raise RuntimeError, ("mix3(double, const double &)") + raise RuntimeError, ("mix3(double, const double &)") if (mix3(1.0) != 103): - raise RuntimeError, ("mix3(double)") + raise RuntimeError, ("mix3(double)") # Combination 1 if (overtparams1(100) != 10): - raise RuntimeError, ("overtparams1(int)") + raise RuntimeError, ("overtparams1(int)") if (overtparams1(100.0, 100) != 20): - raise RuntimeError, ("overtparams1(double, int)") + raise RuntimeError, ("overtparams1(double, int)") # Combination 2 if (overtparams2(100.0, 100) != 40): - raise RuntimeError, ("overtparams2(double, int)") + raise RuntimeError, ("overtparams2(double, int)") # Combination 3 if (overloaded() != 60): - raise RuntimeError, ("overloaded()") + raise RuntimeError, ("overloaded()") if (overloaded(100.0, 100) != 70): - raise RuntimeError, ("overloaded(double, int)") + raise RuntimeError, ("overloaded(double, int)") # Combination 4 if (overloadedagain("hello") != 80): - raise RuntimeError, ("overloadedagain(const char *)") + raise RuntimeError, ("overloadedagain(const char *)") if (overloadedagain() != 90): - raise RuntimeError, ("overloadedagain(double)") + raise RuntimeError, ("overloadedagain(double)") # specializations if (specialization(10) != 202): - raise RuntimeError, ("specialization(int)") + raise RuntimeError, ("specialization(int)") if (specialization(10.0) != 203): - raise RuntimeError, ("specialization(double)") + raise RuntimeError, ("specialization(double)") if (specialization(10, 10) != 204): - raise RuntimeError, ("specialization(int, int)") + raise RuntimeError, ("specialization(int, int)") if (specialization(10.0, 10.0) != 205): - raise RuntimeError, ("specialization(double, double)") + raise RuntimeError, ("specialization(double, double)") if (specialization("hi", "hi") != 201): - raise RuntimeError, ("specialization(const char *, const char *)") + raise RuntimeError, ("specialization(const char *, const char *)") # simple specialization @@ -87,66 +88,66 @@ xyz_double() # a bit of everything if (overload("hi") != 0): - raise RuntimeError, ("overload()") + raise RuntimeError, ("overload()") if (overload(1) != 10): - raise RuntimeError, ("overload(int t)") + raise RuntimeError, ("overload(int t)") if (overload(1, 1) != 20): - raise RuntimeError, ("overload(int t, const int &)") + raise RuntimeError, ("overload(int t, const int &)") if (overload(1, "hello") != 30): - raise RuntimeError, ("overload(int t, const char *)") + raise RuntimeError, ("overload(int t, const char *)") k = Klass() if (overload(k) != 10): - raise RuntimeError, ("overload(Klass t)") + raise RuntimeError, ("overload(Klass t)") if (overload(k, k) != 20): - raise RuntimeError, ("overload(Klass t, const Klass &)") + raise RuntimeError, ("overload(Klass t, const Klass &)") if (overload(k, "hello") != 30): - raise RuntimeError, ("overload(Klass t, const char *)") + raise RuntimeError, ("overload(Klass t, const char *)") if (overload(10.0, "hi") != 40): - raise RuntimeError, ("overload(double t, const char *)") + raise RuntimeError, ("overload(double t, const char *)") if (overload() != 50): - raise RuntimeError, ("overload(const char *)") + raise RuntimeError, ("overload(const char *)") # everything put in a namespace if (nsoverload("hi") != 1000): - raise RuntimeError, ("nsoverload()") + raise RuntimeError, ("nsoverload()") if (nsoverload(1) != 1010): - raise RuntimeError, ("nsoverload(int t)") + raise RuntimeError, ("nsoverload(int t)") if (nsoverload(1, 1) != 1020): - raise RuntimeError, ("nsoverload(int t, const int &)") + raise RuntimeError, ("nsoverload(int t, const int &)") if (nsoverload(1, "hello") != 1030): - raise RuntimeError, ("nsoverload(int t, const char *)") + raise RuntimeError, ("nsoverload(int t, const char *)") if (nsoverload(k) != 1010): - raise RuntimeError, ("nsoverload(Klass t)") + raise RuntimeError, ("nsoverload(Klass t)") if (nsoverload(k, k) != 1020): - raise RuntimeError, ("nsoverload(Klass t, const Klass &)") + raise RuntimeError, ("nsoverload(Klass t, const Klass &)") if (nsoverload(k, "hello") != 1030): - raise RuntimeError, ("nsoverload(Klass t, const char *)") + raise RuntimeError, ("nsoverload(Klass t, const char *)") if (nsoverload(10.0, "hi") != 1040): - raise RuntimeError, ("nsoverload(double t, const char *)") + raise RuntimeError, ("nsoverload(double t, const char *)") if (nsoverload() != 1050): - raise RuntimeError, ("nsoverload(const char *)") + raise RuntimeError, ("nsoverload(const char *)") if is_new_style_class(A): - A.foo(1) + A.foo(1) else: - A_foo(1) + A_foo(1) b = B() b.foo(1) diff --git a/Examples/test-suite/python/overload_template_runme.py b/Examples/test-suite/python/overload_template_runme.py index c1337ba6a..014ec71cb 100644 --- a/Examples/test-suite/python/overload_template_runme.py +++ b/Examples/test-suite/python/overload_template_runme.py @@ -1,79 +1,79 @@ from overload_template import * f = foo() -a = maximum(3,4) -b = maximum(3.4,5.2) +a = maximum(3, 4) +b = maximum(3.4, 5.2) # mix 1 if (mix1("hi") != 101): - raise RuntimeError, ("mix1(const char*)") + raise RuntimeError, ("mix1(const char*)") if (mix1(1.0, 1.0) != 102): - raise RuntimeError, ("mix1(double, const double &)") + raise RuntimeError, ("mix1(double, const double &)") if (mix1(1.0) != 103): - raise RuntimeError, ("mix1(double)") + raise RuntimeError, ("mix1(double)") # mix 2 if (mix2("hi") != 101): - raise RuntimeError, ("mix2(const char*)") + raise RuntimeError, ("mix2(const char*)") if (mix2(1.0, 1.0) != 102): - raise RuntimeError, ("mix2(double, const double &)") + raise RuntimeError, ("mix2(double, const double &)") if (mix2(1.0) != 103): - raise RuntimeError, ("mix2(double)") + raise RuntimeError, ("mix2(double)") # mix 3 if (mix3("hi") != 101): - raise RuntimeError, ("mix3(const char*)") + raise RuntimeError, ("mix3(const char*)") if (mix3(1.0, 1.0) != 102): - raise RuntimeError, ("mix3(double, const double &)") + raise RuntimeError, ("mix3(double, const double &)") if (mix3(1.0) != 103): - raise RuntimeError, ("mix3(double)") + raise RuntimeError, ("mix3(double)") # Combination 1 if (overtparams1(100) != 10): - raise RuntimeError, ("overtparams1(int)") + raise RuntimeError, ("overtparams1(int)") if (overtparams1(100.0, 100) != 20): - raise RuntimeError, ("overtparams1(double, int)") + raise RuntimeError, ("overtparams1(double, int)") # Combination 2 if (overtparams2(100.0, 100) != 40): - raise RuntimeError, ("overtparams2(double, int)") + raise RuntimeError, ("overtparams2(double, int)") # Combination 3 if (overloaded() != 60): - raise RuntimeError, ("overloaded()") + raise RuntimeError, ("overloaded()") if (overloaded(100.0, 100) != 70): - raise RuntimeError, ("overloaded(double, int)") + raise RuntimeError, ("overloaded(double, int)") # Combination 4 if (overloadedagain("hello") != 80): - raise RuntimeError, ("overloadedagain(const char *)") + raise RuntimeError, ("overloadedagain(const char *)") if (overloadedagain() != 90): - raise RuntimeError, ("overloadedagain(double)") + raise RuntimeError, ("overloadedagain(double)") # specializations if (specialization(10) != 202): - raise RuntimeError, ("specialization(int)") + raise RuntimeError, ("specialization(int)") if (specialization(10.0) != 203): - raise RuntimeError, ("specialization(double)") + raise RuntimeError, ("specialization(double)") if (specialization(10, 10) != 204): - raise RuntimeError, ("specialization(int, int)") + raise RuntimeError, ("specialization(int, int)") if (specialization(10.0, 10.0) != 205): - raise RuntimeError, ("specialization(double, double)") + raise RuntimeError, ("specialization(double, double)") if (specialization("hi", "hi") != 201): - raise RuntimeError, ("specialization(const char *, const char *)") + raise RuntimeError, ("specialization(const char *, const char *)") # simple specialization @@ -83,61 +83,61 @@ xyz_double() # a bit of everything if (overload("hi") != 0): - raise RuntimeError, ("overload()") + raise RuntimeError, ("overload()") if (overload(1) != 10): - raise RuntimeError, ("overload(int t)") + raise RuntimeError, ("overload(int t)") if (overload(1, 1) != 20): - raise RuntimeError, ("overload(int t, const int &)") + raise RuntimeError, ("overload(int t, const int &)") if (overload(1, "hello") != 30): - raise RuntimeError, ("overload(int t, const char *)") + raise RuntimeError, ("overload(int t, const char *)") k = Klass() if (overload(k) != 10): - raise RuntimeError, ("overload(Klass t)") + raise RuntimeError, ("overload(Klass t)") if (overload(k, k) != 20): - raise RuntimeError, ("overload(Klass t, const Klass &)") + raise RuntimeError, ("overload(Klass t, const Klass &)") if (overload(k, "hello") != 30): - raise RuntimeError, ("overload(Klass t, const char *)") + raise RuntimeError, ("overload(Klass t, const char *)") if (overload(10.0, "hi") != 40): - raise RuntimeError, ("overload(double t, const char *)") + raise RuntimeError, ("overload(double t, const char *)") if (overload() != 50): - raise RuntimeError, ("overload(const char *)") + raise RuntimeError, ("overload(const char *)") # everything put in a namespace if (nsoverload("hi") != 1000): - raise RuntimeError, ("nsoverload()") + raise RuntimeError, ("nsoverload()") if (nsoverload(1) != 1010): - raise RuntimeError, ("nsoverload(int t)") + raise RuntimeError, ("nsoverload(int t)") if (nsoverload(1, 1) != 1020): - raise RuntimeError, ("nsoverload(int t, const int &)") + raise RuntimeError, ("nsoverload(int t, const int &)") if (nsoverload(1, "hello") != 1030): - raise RuntimeError, ("nsoverload(int t, const char *)") + raise RuntimeError, ("nsoverload(int t, const char *)") if (nsoverload(k) != 1010): - raise RuntimeError, ("nsoverload(Klass t)") + raise RuntimeError, ("nsoverload(Klass t)") if (nsoverload(k, k) != 1020): - raise RuntimeError, ("nsoverload(Klass t, const Klass &)") + raise RuntimeError, ("nsoverload(Klass t, const Klass &)") if (nsoverload(k, "hello") != 1030): - raise RuntimeError, ("nsoverload(Klass t, const char *)") + raise RuntimeError, ("nsoverload(Klass t, const char *)") if (nsoverload(10.0, "hi") != 1040): - raise RuntimeError, ("nsoverload(double t, const char *)") + raise RuntimeError, ("nsoverload(double t, const char *)") if (nsoverload() != 1050): - raise RuntimeError, ("nsoverload(const char *)") + raise RuntimeError, ("nsoverload(const char *)") A_foo(1) diff --git a/Examples/test-suite/python/pointer_reference_runme.py b/Examples/test-suite/python/pointer_reference_runme.py index e1a1a1f4b..b9b47881d 100644 --- a/Examples/test-suite/python/pointer_reference_runme.py +++ b/Examples/test-suite/python/pointer_reference_runme.py @@ -2,15 +2,15 @@ import pointer_reference s = pointer_reference.get() if s.value != 10: - raise RuntimeError, "get test failed" + raise RuntimeError, "get test failed" ss = pointer_reference.Struct(20) pointer_reference.set(ss) if pointer_reference.cvar.Struct_instance.value != 20: - raise RuntimeError, "set test failed" + raise RuntimeError, "set test failed" if pointer_reference.overloading(1) != 111: - raise RuntimeError, "overload test 1 failed" + raise RuntimeError, "overload test 1 failed" if pointer_reference.overloading(ss) != 222: - raise RuntimeError, "overload test 2 failed" + raise RuntimeError, "overload test 2 failed" diff --git a/Examples/test-suite/python/preproc_defined_runme.py b/Examples/test-suite/python/preproc_defined_runme.py index 9a295533a..af46816be 100644 --- a/Examples/test-suite/python/preproc_defined_runme.py +++ b/Examples/test-suite/python/preproc_defined_runme.py @@ -1,7 +1,7 @@ import preproc_defined if preproc_defined.call_checking() != 1: - raise RuntimeError + raise RuntimeError d = preproc_defined.Defined() d.defined = 10 diff --git a/Examples/test-suite/python/preproc_include_runme.py b/Examples/test-suite/python/preproc_include_runme.py index 778de3c87..7c3a360ce 100644 --- a/Examples/test-suite/python/preproc_include_runme.py +++ b/Examples/test-suite/python/preproc_include_runme.py @@ -1,23 +1,22 @@ import preproc_include if preproc_include.multiply10(10) != 100: - raise RuntimeError + raise RuntimeError if preproc_include.multiply20(10) != 200: - raise RuntimeError + raise RuntimeError if preproc_include.multiply30(10) != 300: - raise RuntimeError + raise RuntimeError if preproc_include.multiply40(10) != 400: - raise RuntimeError + raise RuntimeError if preproc_include.multiply50(10) != 500: - raise RuntimeError + raise RuntimeError if preproc_include.multiply60(10) != 600: - raise RuntimeError + raise RuntimeError if preproc_include.multiply70(10) != 700: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/preproc_runme.py b/Examples/test-suite/python/preproc_runme.py index 3049f00ab..99a6d0307 100644 --- a/Examples/test-suite/python/preproc_runme.py +++ b/Examples/test-suite/python/preproc_runme.py @@ -1,16 +1,16 @@ import preproc if preproc.endif != 1: - raise RuntimeError + raise RuntimeError if preproc.define != 1: - raise RuntimeError + raise RuntimeError if preproc.defined != 1: - raise RuntimeError + raise RuntimeError -if 2*preproc.one != preproc.two: - raise RuntimeError +if 2 * preproc.one != preproc.two: + raise RuntimeError if preproc.methodX(99) != 199: - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/primitive_types_runme.py b/Examples/test-suite/python/primitive_types_runme.py index d4173b7d3..2e7ed7db7 100644 --- a/Examples/test-suite/python/primitive_types_runme.py +++ b/Examples/test-suite/python/primitive_types_runme.py @@ -28,81 +28,142 @@ cvar.var_paramc = sct_paramc v_check() -def pyerror(name, val, cte): - print "bad val/cte", name, val, cte - raise RuntimeError - pass -if cvar.var_bool != cct_bool: pyerror("bool", cvar.var_bool, cct_bool) -if cvar.var_schar != cct_schar: pyerror("schar", cvar.var_schar, cct_schar) -if cvar.var_uchar != cct_uchar: pyerror("uchar", cvar.var_uchar, cct_uchar) -if cvar.var_int != cct_int: pyerror("int", cvar.var_int, cct_int) -if cvar.var_uint != cct_uint: pyerror("uint", cvar.var_uint, cct_uint) -if cvar.var_short != cct_short: pyerror("short", cvar.var_short, cct_short) -if cvar.var_ushort != cct_ushort: pyerror("ushort", cvar.var_ushort, cct_ushort) -if cvar.var_long != cct_long: pyerror("long", cvar.var_long, cct_long) -if cvar.var_ulong != cct_ulong: pyerror("ulong", cvar.var_ulong, cct_ulong) -if cvar.var_llong != cct_llong: pyerror("llong", cvar.var_llong, cct_llong) -if cvar.var_ullong != cct_ullong: pyerror("ullong", cvar.var_ullong, cct_ullong) -if cvar.var_char != cct_char: pyerror("char", cvar.var_char, cct_char) -if cvar.var_pchar != cct_pchar: pyerror("pchar", cvar.var_pchar, cct_pchar) -if cvar.var_pcharc != cct_pcharc: pyerror("pchar", cvar.var_pcharc, cct_pcharc) -if cvar.var_pint != cct_pint: pyerror("pint", cvar.var_pint, cct_pint) -if cvar.var_sizet != cct_sizet: pyerror("sizet", cvar.var_sizet, cct_sizet) -if cvar.var_hello != cct_hello: pyerror("hello", cvar.var_hello, cct_hello) -if cvar.var_myint != cct_myint: pyerror("myint", cvar.var_myint, cct_myint) -if cvar.var_namet != def_namet: pyerror("name", cvar.var_namet, def_namet) +def pyerror(name, val, cte): + print "bad val/cte", name, val, cte + raise RuntimeError + pass + +if cvar.var_bool != cct_bool: + pyerror("bool", cvar.var_bool, cct_bool) +if cvar.var_schar != cct_schar: + pyerror("schar", cvar.var_schar, cct_schar) +if cvar.var_uchar != cct_uchar: + pyerror("uchar", cvar.var_uchar, cct_uchar) +if cvar.var_int != cct_int: + pyerror("int", cvar.var_int, cct_int) +if cvar.var_uint != cct_uint: + pyerror("uint", cvar.var_uint, cct_uint) +if cvar.var_short != cct_short: + pyerror("short", cvar.var_short, cct_short) +if cvar.var_ushort != cct_ushort: + pyerror("ushort", cvar.var_ushort, cct_ushort) +if cvar.var_long != cct_long: + pyerror("long", cvar.var_long, cct_long) +if cvar.var_ulong != cct_ulong: + pyerror("ulong", cvar.var_ulong, cct_ulong) +if cvar.var_llong != cct_llong: + pyerror("llong", cvar.var_llong, cct_llong) +if cvar.var_ullong != cct_ullong: + pyerror("ullong", cvar.var_ullong, cct_ullong) +if cvar.var_char != cct_char: + pyerror("char", cvar.var_char, cct_char) +if cvar.var_pchar != cct_pchar: + pyerror("pchar", cvar.var_pchar, cct_pchar) +if cvar.var_pcharc != cct_pcharc: + pyerror("pchar", cvar.var_pcharc, cct_pcharc) +if cvar.var_pint != cct_pint: + pyerror("pint", cvar.var_pint, cct_pint) +if cvar.var_sizet != cct_sizet: + pyerror("sizet", cvar.var_sizet, cct_sizet) +if cvar.var_hello != cct_hello: + pyerror("hello", cvar.var_hello, cct_hello) +if cvar.var_myint != cct_myint: + pyerror("myint", cvar.var_myint, cct_myint) +if cvar.var_namet != def_namet: + pyerror("name", cvar.var_namet, def_namet) + class PyTest (TestDirector): - def __init__(self): - TestDirector.__init__(self) + + def __init__(self): + TestDirector.__init__(self) + pass + + def ident(self, x): + return x + + def vval_bool(self, x): return self.ident(x) + + def vval_schar(self, x): return self.ident(x) + + def vval_uchar(self, x): return self.ident(x) + + def vval_int(self, x): return self.ident(x) + + def vval_uint(self, x): return self.ident(x) + + def vval_short(self, x): return self.ident(x) + + def vval_ushort(self, x): return self.ident(x) + + def vval_long(self, x): return self.ident(x) + + def vval_ulong(self, x): return self.ident(x) + + def vval_llong(self, x): return self.ident(x) + + def vval_ullong(self, x): return self.ident(x) + + def vval_float(self, x): return self.ident(x) + + def vval_double(self, x): return self.ident(x) + + def vval_char(self, x): return self.ident(x) + + def vval_pchar(self, x): return self.ident(x) + + def vval_pcharc(self, x): return self.ident(x) + + def vval_pint(self, x): return self.ident(x) + + def vval_sizet(self, x): return self.ident(x) + + def vval_hello(self, x): return self.ident(x) + + def vval_myint(self, x): return self.ident(x) + + def vref_bool(self, x): return self.ident(x) + + def vref_schar(self, x): return self.ident(x) + + def vref_uchar(self, x): return self.ident(x) + + def vref_int(self, x): return self.ident(x) + + def vref_uint(self, x): return self.ident(x) + + def vref_short(self, x): return self.ident(x) + + def vref_ushort(self, x): return self.ident(x) + + def vref_long(self, x): return self.ident(x) + + def vref_ulong(self, x): return self.ident(x) + + def vref_llong(self, x): return self.ident(x) + + def vref_ullong(self, x): return self.ident(x) + + def vref_float(self, x): return self.ident(x) + + def vref_double(self, x): return self.ident(x) + + def vref_char(self, x): return self.ident(x) + + def vref_pchar(self, x): return self.ident(x) + + def vref_pcharc(self, x): return self.ident(x) + + def vref_pint(self, x): return self.ident(x) + + def vref_sizet(self, x): return self.ident(x) + + def vref_hello(self, x): return self.ident(x) + + def vref_myint(self, x): return self.ident(x) + pass - def ident(self, x): - return x - - def vval_bool(self, x): return self.ident(x) - def vval_schar(self, x): return self.ident(x) - def vval_uchar(self, x): return self.ident(x) - def vval_int(self, x): return self.ident(x) - def vval_uint(self, x): return self.ident(x) - def vval_short(self, x): return self.ident(x) - def vval_ushort(self, x): return self.ident(x) - def vval_long(self, x): return self.ident(x) - def vval_ulong(self, x): return self.ident(x) - def vval_llong(self, x): return self.ident(x) - def vval_ullong(self, x): return self.ident(x) - def vval_float(self, x): return self.ident(x) - def vval_double(self, x): return self.ident(x) - def vval_char(self, x): return self.ident(x) - def vval_pchar(self, x): return self.ident(x) - def vval_pcharc(self, x): return self.ident(x) - def vval_pint(self, x): return self.ident(x) - def vval_sizet(self, x): return self.ident(x) - def vval_hello(self, x): return self.ident(x) - def vval_myint(self, x): return self.ident(x) - - def vref_bool(self, x): return self.ident(x) - def vref_schar(self, x): return self.ident(x) - def vref_uchar(self, x): return self.ident(x) - def vref_int(self, x): return self.ident(x) - def vref_uint(self, x): return self.ident(x) - def vref_short(self, x): return self.ident(x) - def vref_ushort(self, x): return self.ident(x) - def vref_long(self, x): return self.ident(x) - def vref_ulong(self, x): return self.ident(x) - def vref_llong(self, x): return self.ident(x) - def vref_ullong(self, x): return self.ident(x) - def vref_float(self, x): return self.ident(x) - def vref_double(self, x): return self.ident(x) - def vref_char(self, x): return self.ident(x) - def vref_pchar(self, x): return self.ident(x) - def vref_pcharc(self, x): return self.ident(x) - def vref_pint(self, x): return self.ident(x) - def vref_sizet(self, x): return self.ident(x) - def vref_hello(self, x): return self.ident(x) - def vref_myint(self, x): return self.ident(x) - - pass t = Test() @@ -111,7 +172,7 @@ p = PyTest() # internal call check if t.c_check() != p.c_check(): - raise RuntimeError, "bad director" + raise RuntimeError, "bad director" p.var_bool = p.stc_bool p.var_schar = p.stc_schar @@ -166,63 +227,63 @@ t.v_check() # this value contains a '0' char! if def_namet != 'hola': - print "bad namet", def_namet - raise RuntimeError + print "bad namet", def_namet + raise RuntimeError t.var_namet = def_namet if t.var_namet != def_namet: - print "bad namet", t.var_namet, def_namet - raise RuntimeError + print "bad namet", t.var_namet, def_namet + raise RuntimeError t.var_namet = 'hola' if t.var_namet != 'hola': - print "bad namet", t.var_namet - raise RuntimeError + print "bad namet", t.var_namet + raise RuntimeError t.var_namet = 'hol' if t.var_namet != 'hol': -#if t.var_namet != 'hol\0\0': - print "bad namet", t.var_namet - raise RuntimeError + # if t.var_namet != 'hol\0\0': + print "bad namet", t.var_namet + raise RuntimeError cvar.var_char = '\0' if cvar.var_char != '\0': - raise RuntimeError, "bad char '0' case" - + raise RuntimeError, "bad char '0' case" + cvar.var_char = 0 if cvar.var_char != '\0': - raise RuntimeError, "bad char '0' case" + raise RuntimeError, "bad char '0' case" cvar.var_namet = '\0' -#if cvar.var_namet != '\0\0\0\0\0': +# if cvar.var_namet != '\0\0\0\0\0': if cvar.var_namet != '': - print 'hola', '', cvar.var_namet - raise RuntimeError, "bad char '\0' case" + print 'hola', '', cvar.var_namet + raise RuntimeError, "bad char '\0' case" cvar.var_namet = '' -#if cvar.var_namet != '\0\0\0\0\0': +# if cvar.var_namet != '\0\0\0\0\0': if cvar.var_namet != '': - raise RuntimeError, "bad char empty case" + raise RuntimeError, "bad char empty case" cvar.var_pchar = None if cvar.var_pchar != None: - raise RuntimeError, "bad None case" + raise RuntimeError, "bad None case" cvar.var_pchar = '' if cvar.var_pchar != '': - print '%c' % (cvar.var_pchar[0],) - raise RuntimeError, "bad char empty case" + print '%c' % (cvar.var_pchar[0],) + raise RuntimeError, "bad char empty case" cvar.var_pcharc = None if cvar.var_pcharc != None: - raise RuntimeError, "bad None case" + raise RuntimeError, "bad None case" cvar.var_pcharc = '' if cvar.var_pcharc != '': - raise RuntimeError, "bad char empty case" + raise RuntimeError, "bad char empty case" # @@ -238,13 +299,13 @@ pchar_setitem(pc, 4, 0) cvar.var_pchar = pc if cvar.var_pchar != "hola": - print cvar.var_pchar - raise RuntimeError, "bad pointer case" + print cvar.var_pchar + raise RuntimeError, "bad pointer case" cvar.var_namet = pc -#if cvar.var_namet != "hola\0": +# if cvar.var_namet != "hola\0": if cvar.var_namet != "hola": - raise RuntimeError, "bad pointer case" + raise RuntimeError, "bad pointer case" delete_pchar(pc) @@ -254,125 +315,124 @@ delete_pchar(pc) try: - error = 0 - a = t.var_uchar - t.var_uchar = 10000 - error = 1 -except OverflowError: - if a != t.var_uchar: + error = 0 + a = t.var_uchar + t.var_uchar = 10000 error = 1 - pass +except OverflowError: + if a != t.var_uchar: + error = 1 + pass if error: - raise RuntimeError, "bad uchar typemap" - + raise RuntimeError, "bad uchar typemap" try: - error = 0 - a = t.var_char - t.var_char = '23' - error = 1 + error = 0 + a = t.var_char + t.var_char = '23' + error = 1 except TypeError: - if a != t.var_char: - error = 1 - pass + if a != t.var_char: + error = 1 + pass if error: - raise RuntimeError, "bad char typemap" + raise RuntimeError, "bad char typemap" try: - error = 0 - a = t.var_ushort - t.var_ushort = -1 - error = 1 -except OverflowError: - if a != t.var_ushort: + error = 0 + a = t.var_ushort + t.var_ushort = -1 error = 1 - pass +except OverflowError: + if a != t.var_ushort: + error = 1 + pass if error: - raise RuntimeError, "bad ushort typemap" + raise RuntimeError, "bad ushort typemap" try: - error = 0 - a = t.var_uint - t.var_uint = -1 - error = 1 -except OverflowError: - if a != t.var_uint: + error = 0 + a = t.var_uint + t.var_uint = -1 error = 1 - pass +except OverflowError: + if a != t.var_uint: + error = 1 + pass if error: - raise RuntimeError, "bad uint typemap" + raise RuntimeError, "bad uint typemap" try: - error = 0 - a = t.var_sizet - t.var_sizet = -1 - error = 1 -except OverflowError: - if a != t.var_sizet: + error = 0 + a = t.var_sizet + t.var_sizet = -1 error = 1 - pass +except OverflowError: + if a != t.var_sizet: + error = 1 + pass if error: - raise RuntimeError, "bad sizet typemap" + raise RuntimeError, "bad sizet typemap" try: - error = 0 - a = t.var_ulong - t.var_ulong = -1 - error = 1 -except OverflowError: - if a != t.var_ulong: + error = 0 + a = t.var_ulong + t.var_ulong = -1 error = 1 - pass +except OverflowError: + if a != t.var_ulong: + error = 1 + pass if error: - raise RuntimeError, "bad ulong typemap" + raise RuntimeError, "bad ulong typemap" # # try: - error = 0 - a = t.var_namet - t.var_namet = '123456' - error = 1 -except TypeError: - if a != t.var_namet: + error = 0 + a = t.var_namet + t.var_namet = '123456' error = 1 - pass +except TypeError: + if a != t.var_namet: + error = 1 + pass if error: - raise RuntimeError, "bad namet typemap" + raise RuntimeError, "bad namet typemap" # # # t2 = p.vtest(t) -if t.var_namet != t2.var_namet: - raise RuntimeError, "bad SWIGTYPE* typemap" - +if t.var_namet != t2.var_namet: + raise RuntimeError, "bad SWIGTYPE* typemap" + if cvar.fixsize != 'ho\0la\0\0\0': - raise RuntimeError, "bad FIXSIZE typemap" + raise RuntimeError, "bad FIXSIZE typemap" cvar.fixsize = 'ho' if cvar.fixsize != 'ho\0\0\0\0\0\0': - raise RuntimeError, "bad FIXSIZE typemap" + raise RuntimeError, "bad FIXSIZE typemap" f = Foo(3) f1 = fptr_val(f) f2 = fptr_ref(f) if f1._a != f2._a: - raise RuntimeError, "bad const ptr& typemap" - + raise RuntimeError, "bad const ptr& typemap" -v = char_foo(1,3) -if v !=3: - raise RuntimeError, "bad int typemap" -s = char_foo(1,"hello") -if s !="hello": - raise RuntimeError, "bad char* typemap" - +v = char_foo(1, 3) +if v != 3: + raise RuntimeError, "bad int typemap" -v = SetPos(1,3) -if v !=4: - raise RuntimeError, "bad int typemap" +s = char_foo(1, "hello") +if s != "hello": + raise RuntimeError, "bad char* typemap" + + +v = SetPos(1, 3) +if v != 4: + raise RuntimeError, "bad int typemap" diff --git a/Examples/test-suite/python/profiletest_runme.py b/Examples/test-suite/python/profiletest_runme.py index d4f07dc11..1e5851e88 100644 --- a/Examples/test-suite/python/profiletest_runme.py +++ b/Examples/test-suite/python/profiletest_runme.py @@ -1,5 +1,5 @@ -import _profiletest -import profiletest +import _profiletest +import profiletest a = profiletest.A() print a @@ -9,24 +9,24 @@ b = profiletest.B() fn = b.fn i = 50000 while i: - a = fn(a) #1 - a = fn(a) #2 - a = fn(a) #3 - a = fn(a) #4 - a = fn(a) #5 - a = fn(a) #6 - a = fn(a) #7 - a = fn(a) #8 - a = fn(a) #9 - a = fn(a) #10 - a = fn(a) #1 - a = fn(a) #2 - a = fn(a) #3 - a = fn(a) #4 - a = fn(a) #5 - a = fn(a) #6 - a = fn(a) #7 - a = fn(a) #8 - a = fn(a) #9 - a = fn(a) #20 - i -= 1 + a = fn(a) # 1 + a = fn(a) # 2 + a = fn(a) # 3 + a = fn(a) # 4 + a = fn(a) # 5 + a = fn(a) # 6 + a = fn(a) # 7 + a = fn(a) # 8 + a = fn(a) # 9 + a = fn(a) # 10 + a = fn(a) # 1 + a = fn(a) # 2 + a = fn(a) # 3 + a = fn(a) # 4 + a = fn(a) # 5 + a = fn(a) # 6 + a = fn(a) # 7 + a = fn(a) # 8 + a = fn(a) # 9 + a = fn(a) # 20 + i -= 1 diff --git a/Examples/test-suite/python/profiletestc_runme.py b/Examples/test-suite/python/profiletestc_runme.py index 33461e484..fe64f969a 100644 --- a/Examples/test-suite/python/profiletestc_runme.py +++ b/Examples/test-suite/python/profiletestc_runme.py @@ -1,54 +1,54 @@ -import _profiletest -#import profiletest +import _profiletest +#import profiletest pa = _profiletest.new_A() -pb = _profiletest.new_B() +pb = _profiletest.new_B() fn = _profiletest.B_fn destroy = _profiletest.delete_A i = 50000 a = pa while i: - a = fn(pb,a) #1 - destroy(a) - a = fn(pb,a) #2 - destroy(a) - a = fn(pb,a) #3 - destroy(a) - a = fn(pb,a) #4 - destroy(a) - a = fn(pb,a) #5 - destroy(a) - a = fn(pb,a) #6 - destroy(a) - a = fn(pb,a) #7 - destroy(a) - a = fn(pb,a) #8 - destroy(a) - a = fn(pb,a) #9 - destroy(a) - a = fn(pb,a) #10 - destroy(a) - a = fn(pb,a) #1 - destroy(a) - a = fn(pb,a) #2 - destroy(a) - a = fn(pb,a) #3 - destroy(a) - a = fn(pb,a) #4 - destroy(a) - a = fn(pb,a) #5 - destroy(a) - a = fn(pb,a) #6 - destroy(a) - a = fn(pb,a) #7 - destroy(a) - a = fn(pb,a) #8 - destroy(a) - a = fn(pb,a) #9 - destroy(a) - a = fn(pb,a) #20 - destroy(a) - i -= 1 + a = fn(pb, a) # 1 + destroy(a) + a = fn(pb, a) # 2 + destroy(a) + a = fn(pb, a) # 3 + destroy(a) + a = fn(pb, a) # 4 + destroy(a) + a = fn(pb, a) # 5 + destroy(a) + a = fn(pb, a) # 6 + destroy(a) + a = fn(pb, a) # 7 + destroy(a) + a = fn(pb, a) # 8 + destroy(a) + a = fn(pb, a) # 9 + destroy(a) + a = fn(pb, a) # 10 + destroy(a) + a = fn(pb, a) # 1 + destroy(a) + a = fn(pb, a) # 2 + destroy(a) + a = fn(pb, a) # 3 + destroy(a) + a = fn(pb, a) # 4 + destroy(a) + a = fn(pb, a) # 5 + destroy(a) + a = fn(pb, a) # 6 + destroy(a) + a = fn(pb, a) # 7 + destroy(a) + a = fn(pb, a) # 8 + destroy(a) + a = fn(pb, a) # 9 + destroy(a) + a = fn(pb, a) # 20 + destroy(a) + i -= 1 _profiletest.delete_A(pa) _profiletest.delete_B(pb) diff --git a/Examples/test-suite/python/python_abstractbase_runme3.py b/Examples/test-suite/python/python_abstractbase_runme3.py index 9b189964d..b4a20f085 100644 --- a/Examples/test-suite/python/python_abstractbase_runme3.py +++ b/Examples/test-suite/python/python_abstractbase_runme3.py @@ -4,7 +4,7 @@ from collections import * # This is expected to fail with -builtin option # Builtin types can't inherit from pure-python abstract bases if is_python_builtin(): - exit(0) + exit(0) assert issubclass(Mapii, MutableMapping) assert issubclass(Multimapii, MutableMapping) @@ -19,4 +19,3 @@ intset = IntSet() intmultiset = IntMultiset() intvector = IntVector() intlist = IntList() - diff --git a/Examples/test-suite/python/python_append_runme.py b/Examples/test-suite/python/python_append_runme.py index 15b0297e9..2f6d94d9c 100644 --- a/Examples/test-suite/python/python_append_runme.py +++ b/Examples/test-suite/python/python_append_runme.py @@ -1,22 +1,22 @@ from python_append import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") # test not relevant for -builtin if is_python_builtin(): - exit(0) + exit(0) -t=Test() +t = Test() t.func() if is_new_style_class(Test): - t.static_func() + t.static_func() else: - Test_static_func() + Test_static_func() if grabpath() != os.path.dirname(mypath): - raise RuntimeError("grabpath failed") + raise RuntimeError("grabpath failed") if grabstaticpath() != os.path.basename(mypath): - raise RuntimeError("grabstaticpath failed") - + raise RuntimeError("grabstaticpath failed") diff --git a/Examples/test-suite/python/python_nondynamic_runme.py b/Examples/test-suite/python/python_nondynamic_runme.py index b860ba0d7..6a430961e 100644 --- a/Examples/test-suite/python/python_nondynamic_runme.py +++ b/Examples/test-suite/python/python_nondynamic_runme.py @@ -5,42 +5,44 @@ aa = python_nondynamic.A() aa.a = 1 aa.b = 2 try: - aa.c = 2 - err = 0 + aa.c = 2 + err = 0 except: - err = 1 + err = 1 + +if not err: + raise RuntimeError, "A is not static" -if not err: - raise RuntimeError, "A is not static" class B(python_nondynamic.A): - c = 4 - def __init__(self): - python_nondynamic.A.__init__(self) + c = 4 + + def __init__(self): + python_nondynamic.A.__init__(self) + pass pass - pass bb = B() try: - bb.c = 3 - err = 0 + bb.c = 3 + err = 0 except: - err = 1 + err = 1 if not err: - print "bb.c = %d" % bb.c - print "B.c = %d" % B.c - raise RuntimeError, "B.c class variable messes up nondynamic-ness of B" + print "bb.c = %d" % bb.c + print "B.c = %d" % B.c + raise RuntimeError, "B.c class variable messes up nondynamic-ness of B" try: - bb.d = 2 - err = 0 + bb.d = 2 + err = 0 except: - err = 1 + err = 1 + +if not err: + raise RuntimeError, "B is not static" -if not err: - raise RuntimeError, "B is not static" - cc = python_nondynamic.C() cc.d = 3 diff --git a/Examples/test-suite/python/python_overload_simple_cast_runme.py b/Examples/test-suite/python/python_overload_simple_cast_runme.py index 1b3a5482c..79ef6cd2e 100644 --- a/Examples/test-suite/python/python_overload_simple_cast_runme.py +++ b/Examples/test-suite/python/python_overload_simple_cast_runme.py @@ -1,16 +1,20 @@ from python_overload_simple_cast import * + class Ai: - def __init__(self,x): + + def __init__(self, x): self.x = x - + def __int__(self): return self.x + class Ad: - def __init__(self,x): + + def __init__(self, x): self.x = x - + def __float__(self): return self.x @@ -26,7 +30,7 @@ except: good = 1 if not good: - raise RuntimeError, "fint(int)" + raise RuntimeError, "fint(int)" if fint(ad) != "fint:int": @@ -40,7 +44,7 @@ if fint(ai) != "fint:int": if fint(5.0) != "fint:int": raise RuntimeError, "fint(int)" - + if fint(3) != "fint:int": raise RuntimeError, "fint(int)" if fint(3.0) != "fint:int": @@ -53,20 +57,19 @@ if fdouble(3) != "fdouble:double": if fdouble(3.0) != "fdouble:double": raise RuntimeError, "fdouble(double)" -if fid(3,3.0) != "fid:intdouble": +if fid(3, 3.0) != "fid:intdouble": raise RuntimeError, "fid:intdouble" -if fid(3.0,3) != "fid:doubleint": +if fid(3.0, 3) != "fid:doubleint": raise RuntimeError, "fid:doubleint" -if fid(ad,ai) != "fid:doubleint": +if fid(ad, ai) != "fid:doubleint": raise RuntimeError, "fid:doubleint" -if fid(ai,ad) != "fid:intdouble": +if fid(ai, ad) != "fid:intdouble": raise RuntimeError, "fid:intdouble" - if foo(3) != "foo:int": raise RuntimeError, "foo(int)" @@ -137,7 +140,7 @@ if s.type != "none": s = Spam(3) if s.type != "int": raise RuntimeError, "Spam(int)" - + s = Spam(3.4) if s.type != "double": raise RuntimeError, "Spam(double)" @@ -160,7 +163,7 @@ if s.type != "void *": # unsigned long long -ullmax = 9223372036854775807 #0xffffffffffffffff +ullmax = 9223372036854775807 # 0xffffffffffffffff ullmaxd = 9007199254740992.0 ullmin = 0 ullmind = 0.0 @@ -174,7 +177,7 @@ if ull(ullmaxd) != ullmaxd: raise RuntimeError, "ull(ullmaxd)" # long long -llmax = 9223372036854775807 #0x7fffffffffffffff +llmax = 9223372036854775807 # 0x7fffffffffffffff llmin = -9223372036854775808 # these are near the largest floats we can still convert into long long llmaxd = 9007199254740992.0 diff --git a/Examples/test-suite/python/python_pybuf_runme3.py b/Examples/test-suite/python/python_pybuf_runme3.py index 152aecdc0..4e57b69e8 100644 --- a/Examples/test-suite/python/python_pybuf_runme3.py +++ b/Examples/test-suite/python/python_pybuf_runme3.py @@ -1,42 +1,41 @@ -#run: +# run: # python python_pybuf_runme3.py benchmark -#for the benchmark, other wise the test case will be run +# for the benchmark, other wise the test case will be run import python_pybuf import sys -if len(sys.argv)>=2 and sys.argv[1]=="benchmark": - #run the benchmark +if len(sys.argv) >= 2 and sys.argv[1] == "benchmark": + # run the benchmark import time - k=1000000 #number of times to excute the functions + k = 1000000 # number of times to excute the functions - t=time.time() + t = time.time() a = bytearray(b'hello world') for i in range(k): - pybuf.title1(a) - print("Time used by bytearray:",time.time()-t) + pybuf.title1(a) + print("Time used by bytearray:", time.time() - t) - t=time.time() + t = time.time() b = 'hello world' for i in range(k): - pybuf.title2(b) - print("Time used by string:",time.time()-t) + pybuf.title2(b) + print("Time used by string:", time.time() - t) else: - #run the test case + # run the test case buf1 = bytearray(10) buf2 = bytearray(50) pybuf.func1(buf1) - assert buf1 == b'a'*10 + assert buf1 == b'a' * 10 pybuf.func2(buf2) assert buf2.startswith(b"Hello world!\x00") count = pybuf.func3(buf2) - assert count==10 #number of alpha and number in 'Hello world!' + assert count == 10 # number of alpha and number in 'Hello world!' length = pybuf.func4(buf2) - assert length==12 + assert length == 12 buf3 = bytearray(b"hello") pybuf.title1(buf3) - assert buf3==b'Hello' - + assert buf3 == b'Hello' diff --git a/Examples/test-suite/python/python_pythoncode_runme.py b/Examples/test-suite/python/python_pythoncode_runme.py new file mode 100644 index 000000000..da238780d --- /dev/null +++ b/Examples/test-suite/python/python_pythoncode_runme.py @@ -0,0 +1,5 @@ +import python_pythoncode + +# No need to actually do anything, this is a regression test for a bug which +# caused an invalid python_pythoncode.py to be generated, so if we can import +# it the bug is still fixed. diff --git a/Examples/test-suite/python/python_richcompare_runme.py b/Examples/test-suite/python/python_richcompare_runme.py index e077989cc..a68da2f98 100644 --- a/Examples/test-suite/python/python_richcompare_runme.py +++ b/Examples/test-suite/python/python_richcompare_runme.py @@ -11,90 +11,96 @@ b2 = python_richcompare.SubClassB(2) b3 = python_richcompare.SubClassB(3) # Check == and != within a single type -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------- -if not (base1 == base1) : +if not (base1 == base1): raise RuntimeError("Object not == to itself") -if not (base1 == python_richcompare.BaseClass(1)) : +if not (base1 == python_richcompare.BaseClass(1)): raise RuntimeError("Object not == to an equivalent object") -if (base1 == base2) : - raise RuntimeError("Comparing non-equivalent objects of the same type, == returned True") +if (base1 == base2): + raise RuntimeError( + "Comparing non-equivalent objects of the same type, == returned True") -if (base1 != base1) : +if (base1 != base1): raise RuntimeError("Object is != itself") -if (base1 != python_richcompare.BaseClass(1)) : +if (base1 != python_richcompare.BaseClass(1)): raise RuntimeError("Object is != an equivalent object") -if not (base1 != base2) : - raise RuntimeError("Comparing non-equivalent objects of the same type, != returned False") +if not (base1 != base2): + raise RuntimeError( + "Comparing non-equivalent objects of the same type, != returned False") # Check redefined operator== in SubClassA -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------- -if (a2 == base2) : +if (a2 == base2): raise RuntimeError("Redefined operator== in SubClassA failed") -if (a2 == b2) : +if (a2 == b2): raise RuntimeError("Redefined operator== in SubClassA failed") -if not (a1 == a2) : +if not (a1 == a2): raise RuntimeError("Redefined operator== in SubClassA failed") # Check up-casting of subclasses -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------- -if (base2 != a2) : - raise RuntimeError("Comparing equivalent base and subclass instances, != returned True") +if (base2 != a2): + raise RuntimeError( + "Comparing equivalent base and subclass instances, != returned True") -if (a2 == base2) : - raise RuntimeError("Comparing non-equivalent base and subclass instances, == returned True") +if (a2 == base2): + raise RuntimeError( + "Comparing non-equivalent base and subclass instances, == returned True") -if (a1 == b1) : - raise RuntimeError("Comparing equivalent instances of different subclasses, == returned True") +if (a1 == b1): + raise RuntimeError( + "Comparing equivalent instances of different subclasses, == returned True") + +if (b1 == a1): + raise RuntimeError( + "Comparing equivalent instances of different subclasses, == returned True") -if (b1 == a1) : - raise RuntimeError("Comparing equivalent instances of different subclasses, == returned True") - # Check inequalities -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------- -if (a2 > b2) : +if (a2 > b2): raise RuntimeError("operator> failed") -if (a2 < b2) : +if (a2 < b2): raise RuntimeError("operator< failed") -if not (a2 >= b2) : +if not (a2 >= b2): raise RuntimeError("operator>= failed") -if not (a2 <= b2) : +if not (a2 <= b2): raise RuntimeError("operator<= failed") # Check inequalities used for ordering -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------- x = sorted([a2, a3, a1]) -if not (x[0] is a1) : +if not (x[0] is a1): raise RuntimeError("Ordering failed") -if not (x[1] is a2) : +if not (x[1] is a2): raise RuntimeError("Ordering failed") -if not (x[2] is a3) : +if not (x[2] is a3): raise RuntimeError("Ordering failed") x = sorted([base2, a3, b1]) -if not (x[0] is b1) : +if not (x[0] is b1): raise RuntimeError("Ordering failed") -if not (x[1] is base2) : +if not (x[1] is base2): raise RuntimeError("Ordering failed") -if not (x[2] is a3) : +if not (x[2] is a3): raise RuntimeError("Ordering failed") diff --git a/Examples/test-suite/python/python_threads_runme.py b/Examples/test-suite/python/python_threads_runme.py index d00e2458f..74cd0552b 100644 --- a/Examples/test-suite/python/python_threads_runme.py +++ b/Examples/test-suite/python/python_threads_runme.py @@ -3,8 +3,9 @@ from python_threads import * action = ActionGroup() count = 1 for child in action.GetActionList(): - if child.val != count: - raise RuntimeError("Expected: " + str(count) + " got: " + str(child.val)) - count = count + 1 + if child.val != count: + raise RuntimeError( + "Expected: " + str(count) + " got: " + str(child.val)) + count = count + 1 # Was seg faulting at the end here diff --git a/Examples/test-suite/python/python_varargs_typemap_runme.py b/Examples/test-suite/python/python_varargs_typemap_runme.py index 65be757c8..f3a70e825 100644 --- a/Examples/test-suite/python/python_varargs_typemap_runme.py +++ b/Examples/test-suite/python/python_varargs_typemap_runme.py @@ -1,7 +1,7 @@ import python_varargs_typemap -if (python_varargs_typemap.testfunc(1, 2.0, "three") != "three") : +if (python_varargs_typemap.testfunc(1, 2.0, "three") != "three"): raise RuntimeError("testfunc failed!") -if (python_varargs_typemap.testfunc(1, 2.0, "three", "four", "five") != "threefourfive") : +if (python_varargs_typemap.testfunc(1, 2.0, "three", "four", "five") != "threefourfive"): raise RuntimeError("testfunc failed! {}") diff --git a/Examples/test-suite/python/refcount_runme.py b/Examples/test-suite/python/refcount_runme.py index ca15e04ac..2cab6a77e 100644 --- a/Examples/test-suite/python/refcount_runme.py +++ b/Examples/test-suite/python/refcount_runme.py @@ -8,16 +8,15 @@ b1 = B(a) b2 = B_create(a) - if a.ref_count() != 3: - raise RuntimeError("Count = %d" % a.ref_count()) + raise RuntimeError("Count = %d" % a.ref_count()) rca = b2.get_rca() b3 = B_create(rca) if a.ref_count() != 5: - raise RuntimeError("Count = %d" % a.ref_count()) + raise RuntimeError("Count = %d" % a.ref_count()) v = vector_A(2) @@ -28,28 +27,28 @@ x = v[0] del v if a.ref_count() != 6: - raise RuntimeError("Count = %d" % a.ref_count()) + raise RuntimeError("Count = %d" % a.ref_count()) # Check %newobject b4 = b2.cloner() if b4.ref_count() != 1: - raise RuntimeError + raise RuntimeError b5 = global_create(a) if b5.ref_count() != 1: - raise RuntimeError + raise RuntimeError b6 = Factory_create(a) if b6.ref_count() != 1: - raise RuntimeError + raise RuntimeError b7 = Factory().create2(a) if b7.ref_count() != 1: - raise RuntimeError + raise RuntimeError if a.ref_count() != 10: - raise RuntimeError("Count = %d" % a.ref_count()) + raise RuntimeError("Count = %d" % a.ref_count()) del b4 del b5 @@ -57,5 +56,4 @@ del b6 del b7 if a.ref_count() != 6: - raise RuntimeError("Count = %d" % a.ref_count()) - + raise RuntimeError("Count = %d" % a.ref_count()) diff --git a/Examples/test-suite/python/reference_global_vars_runme.py b/Examples/test-suite/python/reference_global_vars_runme.py index 98aaec5fe..6c2d181ac 100644 --- a/Examples/test-suite/python/reference_global_vars_runme.py +++ b/Examples/test-suite/python/reference_global_vars_runme.py @@ -71,4 +71,3 @@ if value_double(cvar.var_double) != 10.5: cvar.var_TestClass = createref_TestClass(TestClass(20)) if value_TestClass(cvar.var_TestClass).num != 20: raise RuntimeError - diff --git a/Examples/test-suite/python/rename_pcre_encoder_runme.py b/Examples/test-suite/python/rename_pcre_encoder_runme.py index 419acd1a1..aa60e4b18 100644 --- a/Examples/test-suite/python/rename_pcre_encoder_runme.py +++ b/Examples/test-suite/python/rename_pcre_encoder_runme.py @@ -10,7 +10,7 @@ a = AnotherWidget() a.DoSomething() evt = wxEVTSomeEvent() -t = xUnchangedName() +t = xUnchangedName() if StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42: raise RuntimeError("Unexpected result of renamed function call") diff --git a/Examples/test-suite/python/rename_predicates_runme.py b/Examples/test-suite/python/rename_predicates_runme.py index 2ce097737..2ace8274c 100644 --- a/Examples/test-suite/python/rename_predicates_runme.py +++ b/Examples/test-suite/python/rename_predicates_runme.py @@ -8,22 +8,22 @@ r.MF_extend_function_after() GF_global_function() if r.MV_member_variable != 123: - raise RuntimeError("variable wrong") -r.MV_member_variable = 1234; + raise RuntimeError("variable wrong") +r.MV_member_variable = 1234 if r.MV_member_variable != 1234: - raise RuntimeError("variable wrong") + raise RuntimeError("variable wrong") if cvar.RenamePredicates_MV_static_member_variable != 456: - raise RuntimeError("variable wrong") -cvar.RenamePredicates_MV_static_member_variable = 4567; + raise RuntimeError("variable wrong") +cvar.RenamePredicates_MV_static_member_variable = 4567 if cvar.RenamePredicates_MV_static_member_variable != 4567: - raise RuntimeError("variable wrong") + raise RuntimeError("variable wrong") if cvar.GV_global_variable != 789: - raise RuntimeError("variable wrong") -cvar.GV_global_variable = 7890; + raise RuntimeError("variable wrong") +cvar.GV_global_variable = 7890 if cvar.GV_global_variable != 7890: - raise RuntimeError("variable wrong") + raise RuntimeError("variable wrong") UC_UPPERCASE() LC_lowercase() diff --git a/Examples/test-suite/python/rename_strip_encoder_runme.py b/Examples/test-suite/python/rename_strip_encoder_runme.py index 64be611d6..010c14246 100644 --- a/Examples/test-suite/python/rename_strip_encoder_runme.py +++ b/Examples/test-suite/python/rename_strip_encoder_runme.py @@ -3,4 +3,3 @@ from rename_strip_encoder import * s = SomeWidget() a = AnotherWidget() a.DoSomething() - diff --git a/Examples/test-suite/python/return_const_value_runme.py b/Examples/test-suite/python/return_const_value_runme.py index 932c4822c..947102840 100644 --- a/Examples/test-suite/python/return_const_value_runme.py +++ b/Examples/test-suite/python/return_const_value_runme.py @@ -3,10 +3,10 @@ import sys p = return_const_value.Foo_ptr_getPtr() if (p.getVal() != 17): - print "Runtime test1 faild. p.getVal()=", p.getVal() - sys.exit(1) + print "Runtime test1 faild. p.getVal()=", p.getVal() + sys.exit(1) p = return_const_value.Foo_ptr_getConstPtr() if (p.getVal() != 17): - print "Runtime test2 faild. p.getVal()=", p.getVal() - sys.exit(1) + print "Runtime test2 faild. p.getVal()=", p.getVal() + sys.exit(1) diff --git a/Examples/test-suite/python/smart_pointer_const_overload_runme.py b/Examples/test-suite/python/smart_pointer_const_overload_runme.py index 098e5b4c3..9cec1da9f 100644 --- a/Examples/test-suite/python/smart_pointer_const_overload_runme.py +++ b/Examples/test-suite/python/smart_pointer_const_overload_runme.py @@ -3,115 +3,116 @@ from smart_pointer_const_overload import * CONST_ACCESS = 1 MUTABLE_ACCESS = 2 + def test(b, f): - if f.x != 0: - raise RuntimeError + if f.x != 0: + raise RuntimeError - # Test member variable get - if b.x != 0: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError + # Test member variable get + if b.x != 0: + raise RuntimeError - # Test member variable set - b.x = 1 + if f.access != CONST_ACCESS: + raise RuntimeError - if f.x != 1: - raise RuntimeError - - if f.access != MUTABLE_ACCESS: - raise RuntimeError - - # Test const method - if b.getx() != 1: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError - - # Test mutable method - b.setx(2) + # Test member variable set + b.x = 1 - if f.x != 2: - raise RuntimeError - - if f.access != MUTABLE_ACCESS: - raise RuntimeError - - # Test extended const method - if b.getx2() != 2: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError - - # Test extended mutable method - b.setx2(3) + if f.x != 1: + raise RuntimeError - if f.x != 3: - raise RuntimeError - - if f.access != MUTABLE_ACCESS: - raise RuntimeError - - # Test static method - b.statMethod() + if f.access != MUTABLE_ACCESS: + raise RuntimeError - if f.access != CONST_ACCESS: - raise RuntimeError + # Test const method + if b.getx() != 1: + raise RuntimeError - # Test const member - f.access = MUTABLE_ACCESS - - if b.y != 0: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError - - # Test get through mutable pointer to const member - f.access = MUTABLE_ACCESS - - if get_int(b.yp) != 0: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError + if f.access != CONST_ACCESS: + raise RuntimeError - # Test get through const pointer to mutable member - f.x = 4 - f.access = MUTABLE_ACCESS - - if get_int(b.xp) != 4: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError - - # Test set through const pointer to mutable member - f.access = MUTABLE_ACCESS - set_int(b.xp, 5) - - if f.x != 5: - raise RuntimeError - - if f.access != CONST_ACCESS: - raise RuntimeError + # Test mutable method + b.setx(2) - # Test set pointer to const member - b.yp = new_int(6) - - if f.y != 0: - raise RuntimeError - - if get_int(f.yp) != 6: - raise RuntimeError - - if f.access != MUTABLE_ACCESS: - raise RuntimeError - - delete_int(f.yp); + if f.x != 2: + raise RuntimeError + + if f.access != MUTABLE_ACCESS: + raise RuntimeError + + # Test extended const method + if b.getx2() != 2: + raise RuntimeError + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test extended mutable method + b.setx2(3) + + if f.x != 3: + raise RuntimeError + + if f.access != MUTABLE_ACCESS: + raise RuntimeError + + # Test static method + b.statMethod() + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test const member + f.access = MUTABLE_ACCESS + + if b.y != 0: + raise RuntimeError + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test get through mutable pointer to const member + f.access = MUTABLE_ACCESS + + if get_int(b.yp) != 0: + raise RuntimeError + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test get through const pointer to mutable member + f.x = 4 + f.access = MUTABLE_ACCESS + + if get_int(b.xp) != 4: + raise RuntimeError + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test set through const pointer to mutable member + f.access = MUTABLE_ACCESS + set_int(b.xp, 5) + + if f.x != 5: + raise RuntimeError + + if f.access != CONST_ACCESS: + raise RuntimeError + + # Test set pointer to const member + b.yp = new_int(6) + + if f.y != 0: + raise RuntimeError + + if get_int(f.yp) != 6: + raise RuntimeError + + if f.access != MUTABLE_ACCESS: + raise RuntimeError + + delete_int(f.yp) f = Foo() b = Bar(f) diff --git a/Examples/test-suite/python/smart_pointer_extend_runme.py b/Examples/test-suite/python/smart_pointer_extend_runme.py index 969757b4c..0b2525081 100644 --- a/Examples/test-suite/python/smart_pointer_extend_runme.py +++ b/Examples/test-suite/python/smart_pointer_extend_runme.py @@ -4,7 +4,7 @@ f = Foo() b = Bar(f) if b.extension() != f.extension(): - raise RuntimeError + raise RuntimeError b = CBase() @@ -12,14 +12,13 @@ d = CDerived() p = CPtr() if b.bar() != p.bar(): - raise RuntimeError + raise RuntimeError if d.foo() != p.foo(): - raise RuntimeError + raise RuntimeError if b.hello() != p.hello(): - raise RuntimeError - + raise RuntimeError d = DFoo() @@ -27,8 +26,7 @@ d = DFoo() dp = DPtrFoo(d) if d.SExt(1) != dp.SExt(1): - raise RuntimeError + raise RuntimeError if d.Ext(1) != dp.Ext(1): - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/smart_pointer_member_runme.py b/Examples/test-suite/python/smart_pointer_member_runme.py index 2cf3686fc..ce91da2bd 100644 --- a/Examples/test-suite/python/smart_pointer_member_runme.py +++ b/Examples/test-suite/python/smart_pointer_member_runme.py @@ -1,34 +1,29 @@ from smart_pointer_member import * + def is_new_style_class(cls): - return hasattr(cls, "__class__") + return hasattr(cls, "__class__") f = Foo() f.y = 1 if f.y != 1: - raise RuntimeError + raise RuntimeError b = Bar(f) b.y = 2 if f.y != 2: - print f.y - print b.y - raise RuntimeError - -if b.x != f.x: - raise RuntimeError - -if b.z != f.z: - raise RuntimeError - -if is_new_style_class(Bar): # feature not supported in old style classes - if Foo.z == Bar.z: + print f.y + print b.y raise RuntimeError +if b.x != f.x: + raise RuntimeError +if b.z != f.z: + raise RuntimeError - - - +if is_new_style_class(Bar): # feature not supported in old style classes + if Foo.z == Bar.z: + raise RuntimeError diff --git a/Examples/test-suite/python/smart_pointer_multi_runme.py b/Examples/test-suite/python/smart_pointer_multi_runme.py index c17053055..26c22d449 100644 --- a/Examples/test-suite/python/smart_pointer_multi_runme.py +++ b/Examples/test-suite/python/smart_pointer_multi_runme.py @@ -12,4 +12,3 @@ if s.getx() != 3: g.x = 4 if g.getx() != 4: raise RuntimeError - diff --git a/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py b/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py index ebf4c9b09..3014febcd 100644 --- a/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py +++ b/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py @@ -12,4 +12,3 @@ if s.getx() != 3: g.x = 4 if g.getx() != 4: raise RuntimeError - diff --git a/Examples/test-suite/python/smart_pointer_not_runme.py b/Examples/test-suite/python/smart_pointer_not_runme.py index 4c90b376b..69704c4ef 100644 --- a/Examples/test-suite/python/smart_pointer_not_runme.py +++ b/Examples/test-suite/python/smart_pointer_not_runme.py @@ -13,7 +13,7 @@ except: try: x = s.x - print "Error! s.x" + print "Error! s.x" except: pass @@ -25,13 +25,13 @@ except: try: x = b.getx() - print "Error! b.getx()" + print "Error! b.getx()" except: pass try: x = s.getx() - print "Error! s.getx()" + print "Error! s.getx()" except: pass diff --git a/Examples/test-suite/python/smart_pointer_overload_runme.py b/Examples/test-suite/python/smart_pointer_overload_runme.py index c9fd3a5b0..16f6997fe 100644 --- a/Examples/test-suite/python/smart_pointer_overload_runme.py +++ b/Examples/test-suite/python/smart_pointer_overload_runme.py @@ -17,5 +17,3 @@ if b.test(3.5) != 2: raise RuntimeError if b.test("hello") != 3: raise RuntimeError - - diff --git a/Examples/test-suite/python/smart_pointer_rename_runme.py b/Examples/test-suite/python/smart_pointer_rename_runme.py index c6d22273c..785f69e64 100644 --- a/Examples/test-suite/python/smart_pointer_rename_runme.py +++ b/Examples/test-suite/python/smart_pointer_rename_runme.py @@ -9,5 +9,5 @@ if b.test() != 3: if b.ftest1(1) != 1: raise RuntimeError -if b.ftest2(2,3) != 2: +if b.ftest2(2, 3) != 2: raise RuntimeError diff --git a/Examples/test-suite/python/smart_pointer_templatevariables_runme.py b/Examples/test-suite/python/smart_pointer_templatevariables_runme.py index 367dcf3b2..465551480 100644 --- a/Examples/test-suite/python/smart_pointer_templatevariables_runme.py +++ b/Examples/test-suite/python/smart_pointer_templatevariables_runme.py @@ -3,15 +3,14 @@ from smart_pointer_templatevariables import * d = DiffImContainerPtr_D(create(1234, 5678)) if (d.id != 1234): - raise RuntimeError -#if (d.xyz != 5678): + raise RuntimeError +# if (d.xyz != 5678): # raise RuntimeError d.id = 4321 #d.xyz = 8765 if (d.id != 4321): - raise RuntimeError -#if (d.xyz != 8765): + raise RuntimeError +# if (d.xyz != 8765): # raise RuntimeError - diff --git a/Examples/test-suite/python/sneaky1_runme.py b/Examples/test-suite/python/sneaky1_runme.py index 9c2c32f85..c56f56f9e 100644 --- a/Examples/test-suite/python/sneaky1_runme.py +++ b/Examples/test-suite/python/sneaky1_runme.py @@ -1,5 +1,5 @@ import sneaky1 -x = sneaky1.add(3,4) -y = sneaky1.subtract(3,4) -z = sneaky1.mul(3,4) -w = sneaky1.divide(3,4) +x = sneaky1.add(3, 4) +y = sneaky1.subtract(3, 4) +z = sneaky1.mul(3, 4) +w = sneaky1.divide(3, 4) diff --git a/Examples/test-suite/python/special_variable_macros_runme.py b/Examples/test-suite/python/special_variable_macros_runme.py index eaf9c1858..e487f9a50 100644 --- a/Examples/test-suite/python/special_variable_macros_runme.py +++ b/Examples/test-suite/python/special_variable_macros_runme.py @@ -2,17 +2,16 @@ import special_variable_macros name = special_variable_macros.Name() if special_variable_macros.testFred(name) != "none": - raise "test failed" + raise "test failed" if special_variable_macros.testJack(name) != "$specialname": - raise "test failed" + raise "test failed" if special_variable_macros.testJill(name) != "jilly": - raise "test failed" + raise "test failed" if special_variable_macros.testMary(name) != "SWIGTYPE_p_NameWrap": - raise "test failed" + raise "test failed" if special_variable_macros.testJames(name) != "SWIGTYPE_Name": - raise "test failed" + raise "test failed" if special_variable_macros.testJim(name) != "multiname num": - raise "test failed" + raise "test failed" if special_variable_macros.testJohn(special_variable_macros.PairIntBool(10, False)) != 123: - raise "test failed" - + raise "test failed" diff --git a/Examples/test-suite/python/static_const_member_2_runme.py b/Examples/test-suite/python/static_const_member_2_runme.py index 081726361..01704e39c 100644 --- a/Examples/test-suite/python/static_const_member_2_runme.py +++ b/Examples/test-suite/python/static_const_member_2_runme.py @@ -12,5 +12,5 @@ except: raise RuntimeError -if Foo.BAZ.val != 2*Foo.BAR.val: +if Foo.BAZ.val != 2 * Foo.BAR.val: raise RuntimeError diff --git a/Examples/test-suite/python/std_containers_runme.py b/Examples/test-suite/python/std_containers_runme.py index f90c98405..d4625daa0 100644 --- a/Examples/test-suite/python/std_containers_runme.py +++ b/Examples/test-suite/python/std_containers_runme.py @@ -5,73 +5,72 @@ import std_containers cube = (((1, 2), (3, 4)), ((5, 6), (7, 8))) icube = std_containers.cident(cube) -for i in range(0,len(cube)): - if cube[i] != icube[i]: - raise RuntimeError, "bad cident" +for i in range(0, len(cube)): + if cube[i] != icube[i]: + raise RuntimeError, "bad cident" -p = (1,2) +p = (1, 2) if p != std_containers.pident(p): - raise RuntimeError, "bad pident" + raise RuntimeError, "bad pident" -v = (1,2,3,4,5,6) +v = (1, 2, 3, 4, 5, 6) iv = std_containers.vident(v) -for i in range(0,len(v)): - if v[i] != iv[i]: - raise RuntimeError, "bad vident" - +for i in range(0, len(v)): + if v[i] != iv[i]: + raise RuntimeError, "bad vident" iv = std_containers.videntu(v) -for i in range(0,len(v)): - if v[i] != iv[i]: - raise RuntimeError, "bad videntu" +for i in range(0, len(v)): + if v[i] != iv[i]: + raise RuntimeError, "bad videntu" vu = std_containers.vector_ui(v) if vu[2] != std_containers.videntu(vu)[2]: - raise RuntimeError, "bad videntu" - + raise RuntimeError, "bad videntu" + if v[0:3][1] != vu[0:3][1]: - print v[0:3][1], vu[0:3][1] - raise RuntimeError, "bad getslice" - + print v[0:3][1], vu[0:3][1] + raise RuntimeError, "bad getslice" -m = ((1,2,3),(2,3),(3,4)) + +m = ((1, 2, 3), (2, 3), (3, 4)) im = std_containers.midenti(m) -for i in range(0,len(m)): - for j in range(0,len(m[i])): - if m[i][j] != im[i][j]: - raise RuntimeError, "bad getslice" +for i in range(0, len(m)): + for j in range(0, len(m[i])): + if m[i][j] != im[i][j]: + raise RuntimeError, "bad getslice" -m = ((True,False,True),(True,True),(True,True)) +m = ((True, False, True), (True, True), (True, True)) im = std_containers.midentb(m) -for i in range(0,len(m)): - for j in range(0,len(m[i])): - if m[i][j] != im[i][j]: - raise RuntimeError, "bad getslice" +for i in range(0, len(m)): + for j in range(0, len(m[i])): + if m[i][j] != im[i][j]: + raise RuntimeError, "bad getslice" mi = std_containers.imatrix(m) mc = std_containers.cmatrix(m) if mi[0][1] != mc[0][1]: - raise RuntimeError, "bad matrix" + raise RuntimeError, "bad matrix" -map ={} +map = {} map['hello'] = 1 map['hi'] = 2 map['3'] = 2 imap = std_containers.mapident(map) for k in map: - if map[k] != imap[k]: - raise RuntimeError, "bad map" + if map[k] != imap[k]: + raise RuntimeError, "bad map" -mapc ={} +mapc = {} c1 = std_containers.C() c2 = std_containers.C() mapc[1] = c1.this @@ -80,23 +79,23 @@ mapc[2] = c2 std_containers.mapidentc(mapc) -vi = std_containers.vector_i((2,2,3,4)) +vi = std_containers.vector_i((2, 2, 3, 4)) -v = (1,2) +v = (1, 2) v1 = std_containers.v_inout(vi) vi[1], v1[1] -v1,v2 = ((1,2),(3,4)) -v1,v2 = std_containers.v_inout2(v1,v2) +v1, v2 = ((1, 2), (3, 4)) +v1, v2 = std_containers.v_inout2(v1, v2) a1 = std_containers.A(1) a2 = std_containers.A(2) -p1 = (1,a1) -p2 = (2,a2) -v = (p1,p2) -v2= std_containers.pia_vident(v) +p1 = (1, a1) +p2 = (2, a2) +v = (p1, p2) +v2 = std_containers.pia_vident(v) v2[0][1].a v2[1][1].a @@ -110,10 +109,8 @@ s = std_containers.set_i() s.append(1) s.append(2) s.append(3) -j=1 +j = 1 for i in s: - if i != j: - raise RuntimeError - j = j + 1 - - + if i != j: + raise RuntimeError + j = j + 1 diff --git a/Examples/test-suite/python/struct_initialization_runme.py b/Examples/test-suite/python/struct_initialization_runme.py index fbed6a5e9..524b89630 100644 --- a/Examples/test-suite/python/struct_initialization_runme.py +++ b/Examples/test-suite/python/struct_initialization_runme.py @@ -1,20 +1,19 @@ from struct_initialization import * if cvar.instanceC1.x != 10: - raise RuntimeError + raise RuntimeError if cvar.instanceD1.x != 10: - raise RuntimeError + raise RuntimeError if cvar.instanceD2.x != 20: - raise RuntimeError + raise RuntimeError if cvar.instanceD3.x != 30: - raise RuntimeError + raise RuntimeError if cvar.instanceE1.x != 1: - raise RuntimeError + raise RuntimeError if cvar.instanceF1.x != 1: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/struct_value_runme.py b/Examples/test-suite/python/struct_value_runme.py index 727996f53..aa3ece38c 100644 --- a/Examples/test-suite/python/struct_value_runme.py +++ b/Examples/test-suite/python/struct_value_runme.py @@ -3,7 +3,32 @@ import struct_value b = struct_value.Bar() b.a.x = 3 -if b.a.x != 3: raise RuntimeError +if b.a.x != 3: + raise RuntimeError b.b.x = 3 -if b.b.x != 3: raise RuntimeError +if b.b.x != 3: + raise RuntimeError + + +# Test dynamically added attributes - Github pull request #320 +b.added = 123 + +if b.added != 123: + raise RuntimeError("Wrong attribute value") + +if not b.__dict__.has_key("added"): + raise RuntimeError("Missing added attribute in __dict__") + + +class PyBar(struct_value.Bar): + + def __init__(self): + self.extra = "hi" + struct_value.Bar.__init__(self) + +pybar = PyBar() +if not pybar.__dict__.has_key("extra"): + raise RuntimeError("Missing extra attribute in __dict__") +if pybar.extra != "hi": + raise RuntimeError("Incorrect attribute value for extra") diff --git a/Examples/test-suite/python/swigobject_runme.py b/Examples/test-suite/python/swigobject_runme.py index a906108e3..346b05d40 100644 --- a/Examples/test-suite/python/swigobject_runme.py +++ b/Examples/test-suite/python/swigobject_runme.py @@ -1,5 +1,5 @@ -from swigobject import * +from swigobject import * a = A() @@ -8,11 +8,12 @@ a1 = a_ptr(a) a2 = a_ptr(a) if a1.this != a2.this: - raise RuntimeError - + raise RuntimeError + lthis = long(a.this) -# match pointer value, but deal with leading zeros on 8/16 bit systems and different C++ compilers interpretation of %p +# match pointer value, but deal with leading zeros on 8/16 bit systems and +# different C++ compilers interpretation of %p xstr1 = "%016X" % (lthis,) xstr1 = str.lstrip(xstr1, '0') xstr2 = pointer_str(a) @@ -22,8 +23,8 @@ xstr2 = str.lstrip(xstr2, '0') xstr2 = str.upper(xstr2) if xstr1 != xstr2: - print xstr1, xstr2 - raise RuntimeError + print xstr1, xstr2 + raise RuntimeError s = str(a.this) r = repr(a.this) @@ -31,4 +32,4 @@ r = repr(a.this) v1 = v_ptr(a) v2 = v_ptr(a) if long(v1) != long(v2): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/template_classes_runme.py b/Examples/test-suite/python/template_classes_runme.py new file mode 100644 index 000000000..38b2d7a62 --- /dev/null +++ b/Examples/test-suite/python/template_classes_runme.py @@ -0,0 +1,44 @@ +from template_classes import * + +# This test is just testing incorrect number of arguments/parameters checking + +point = PointInt() + +rectangle = RectangleInt() +rectangle.setPoint(point) +rectangle.getPoint() +RectangleInt.static_noargs() +RectangleInt.static_onearg(1) + +fail = True +try: + rectangle.setPoint() +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") + + +fail = True +try: + rectangle.getPoint(0) +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + RectangleInt.static_noargs(0) +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") + +fail = True +try: + RectangleInt.static_onearg() +except TypeError, e: + fail = False +if fail: + raise RuntimeError("argument count check failed") diff --git a/Examples/test-suite/python/template_default_arg_runme.py b/Examples/test-suite/python/template_default_arg_runme.py index 235a2313a..91b1e0e8c 100644 --- a/Examples/test-suite/python/template_default_arg_runme.py +++ b/Examples/test-suite/python/template_default_arg_runme.py @@ -7,22 +7,20 @@ helloInt.foo(template_default_arg.Hello_int.hi) x = template_default_arg.X_int() if (x.meth(20.0, 200) != 200): - raise RuntimeError, ("X_int test 1 failed") + raise RuntimeError, ("X_int test 1 failed") if (x.meth(20) != 20): - raise RuntimeError, ("X_int test 2 failed") + raise RuntimeError, ("X_int test 2 failed") if (x.meth() != 0): - raise RuntimeError, ("X_int test 3 failed") - + raise RuntimeError, ("X_int test 3 failed") y = template_default_arg.Y_unsigned() if (y.meth(20.0, 200) != 200): - raise RuntimeError, ("Y_unsigned test 1 failed") + raise RuntimeError, ("Y_unsigned test 1 failed") if (y.meth(20) != 20): - raise RuntimeError, ("Y_unsigned test 2 failed") + raise RuntimeError, ("Y_unsigned test 2 failed") if (y.meth() != 0): - raise RuntimeError, ("Y_unsigned test 3 failed") - + raise RuntimeError, ("Y_unsigned test 3 failed") x = template_default_arg.X_longlong() @@ -37,7 +35,8 @@ x = template_default_arg.X_int(20.0, 200) x = template_default_arg.X_hello_unsigned() x = template_default_arg.X_hello_unsigned(20.0) -x = template_default_arg.X_hello_unsigned(20.0, template_default_arg.Hello_int()) +x = template_default_arg.X_hello_unsigned( + 20.0, template_default_arg.Hello_int()) y = template_default_arg.Y_hello_unsigned() @@ -46,7 +45,6 @@ y.meth(template_default_arg.Hello_int()) y.meth() - fz = template_default_arg.Foo_Z_8() x = template_default_arg.X_Foo_Z_8() fzc = x.meth(fz) @@ -56,43 +54,40 @@ fzc = x.meth(fz) # plain function: int ott(Foo) if (template_default_arg.ott(template_default_arg.Foo_int()) != 30): - raise RuntimeError, ("ott test 1 failed") + raise RuntimeError, ("ott test 1 failed") # %template(ott) ott if (template_default_arg.ott() != 10): - raise RuntimeError, ("ott test 2 failed") + raise RuntimeError, ("ott test 2 failed") if (template_default_arg.ott(1) != 10): - raise RuntimeError, ("ott test 3 failed") + raise RuntimeError, ("ott test 3 failed") if (template_default_arg.ott(1, 1) != 10): - raise RuntimeError, ("ott test 4 failed") + raise RuntimeError, ("ott test 4 failed") if (template_default_arg.ott("hi") != 20): - raise RuntimeError, ("ott test 5 failed") + raise RuntimeError, ("ott test 5 failed") if (template_default_arg.ott("hi", 1) != 20): - raise RuntimeError, ("ott test 6 failed") + raise RuntimeError, ("ott test 6 failed") if (template_default_arg.ott("hi", 1, 1) != 20): - raise RuntimeError, ("ott test 7 failed") + raise RuntimeError, ("ott test 7 failed") # %template(ott) ott if (template_default_arg.ottstring(template_default_arg.Hello_int(), "hi") != 40): - raise RuntimeError, ("ott test 8 failed") + raise RuntimeError, ("ott test 8 failed") if (template_default_arg.ottstring(template_default_arg.Hello_int()) != 40): - raise RuntimeError, ("ott test 9 failed") + raise RuntimeError, ("ott test 9 failed") # %template(ott) ott if (template_default_arg.ottint(template_default_arg.Hello_int(), 1) != 50): - raise RuntimeError, ("ott test 10 failed") + raise RuntimeError, ("ott test 10 failed") if (template_default_arg.ottint(template_default_arg.Hello_int()) != 50): - raise RuntimeError, ("ott test 11 failed") + raise RuntimeError, ("ott test 11 failed") # %template(ott) ott if (template_default_arg.ott(template_default_arg.Hello_int(), 1.0) != 60): - raise RuntimeError, ("ott test 12 failed") + raise RuntimeError, ("ott test 12 failed") if (template_default_arg.ott(template_default_arg.Hello_int()) != 60): - raise RuntimeError, ("ott test 13 failed") - - - + raise RuntimeError, ("ott test 13 failed") diff --git a/Examples/test-suite/python/template_inherit_runme.py b/Examples/test-suite/python/template_inherit_runme.py index bb1465a2b..2c47770a5 100644 --- a/Examples/test-suite/python/template_inherit_runme.py +++ b/Examples/test-suite/python/template_inherit_runme.py @@ -50,4 +50,3 @@ if invoke_blah_uint(e) != "Foo": if invoke_blah_uint(f) != "Bar": raise ValueError - diff --git a/Examples/test-suite/python/template_matrix_runme.py b/Examples/test-suite/python/template_matrix_runme.py index 95815a068..208aafb8e 100644 --- a/Examples/test-suite/python/template_matrix_runme.py +++ b/Examples/test-suite/python/template_matrix_runme.py @@ -1,6 +1,4 @@ -from template_matrix import * -passVector([1,2,3]) -passMatrix([[1,2],[1,2,3]]) -passCube([[[1,2],[1,2,3]],[[1,2],[1,2,3]]]) - - +from template_matrix import * +passVector([1, 2, 3]) +passMatrix([[1, 2], [1, 2, 3]]) +passCube([[[1, 2], [1, 2, 3]], [[1, 2], [1, 2, 3]]]) diff --git a/Examples/test-suite/python/template_ns4_runme.py b/Examples/test-suite/python/template_ns4_runme.py index 81107b493..deef019eb 100644 --- a/Examples/test-suite/python/template_ns4_runme.py +++ b/Examples/test-suite/python/template_ns4_runme.py @@ -1,5 +1,5 @@ from template_ns4 import * -d = make_Class_DD(); +d = make_Class_DD() if d.test() != "test": - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/template_ns_runme.py b/Examples/test-suite/python/template_ns_runme.py index 20cc9b99c..888d125c4 100644 --- a/Examples/test-suite/python/template_ns_runme.py +++ b/Examples/test-suite/python/template_ns_runme.py @@ -1,5 +1,5 @@ from template_ns import * -p1 = pairii(2,3) +p1 = pairii(2, 3) p2 = pairii(p1) if p2.first != 2: @@ -7,7 +7,7 @@ if p2.first != 2: if p2.second != 3: raise RuntimeError -p3 = pairdd(3.5,2.5) +p3 = pairdd(3.5, 2.5) p4 = pairdd(p3) if p4.first != 3.5: diff --git a/Examples/test-suite/python/template_opaque_runme.py b/Examples/test-suite/python/template_opaque_runme.py index f3aeb39d1..6f21116ee 100644 --- a/Examples/test-suite/python/template_opaque_runme.py +++ b/Examples/test-suite/python/template_opaque_runme.py @@ -3,4 +3,3 @@ import template_opaque v = template_opaque.OpaqueVectorType(10) template_opaque.FillVector(v) - diff --git a/Examples/test-suite/python/template_ref_type_runme.py b/Examples/test-suite/python/template_ref_type_runme.py index 0b3e4dd26..f4ebc354c 100644 --- a/Examples/test-suite/python/template_ref_type_runme.py +++ b/Examples/test-suite/python/template_ref_type_runme.py @@ -1,5 +1,5 @@ import template_ref_type xr = template_ref_type.XC() -y = template_ref_type.Y() +y = template_ref_type.Y() y.find(xr) diff --git a/Examples/test-suite/python/template_static_runme.py b/Examples/test-suite/python/template_static_runme.py index 9171d93b5..c87a52439 100644 --- a/Examples/test-suite/python/template_static_runme.py +++ b/Examples/test-suite/python/template_static_runme.py @@ -1,3 +1,3 @@ -from template_static import * +from template_static import * Foo_bar_double(1) diff --git a/Examples/test-suite/python/template_tbase_template_runme.py b/Examples/test-suite/python/template_tbase_template_runme.py index d13c5f2c2..b5f2e31f4 100644 --- a/Examples/test-suite/python/template_tbase_template_runme.py +++ b/Examples/test-suite/python/template_tbase_template_runme.py @@ -2,4 +2,4 @@ from template_tbase_template import * a = make_Class_dd() if a.test() != "test": - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/template_type_namespace_runme.py b/Examples/test-suite/python/template_type_namespace_runme.py index 19ea5f5ce..5f00fe5f2 100644 --- a/Examples/test-suite/python/template_type_namespace_runme.py +++ b/Examples/test-suite/python/template_type_namespace_runme.py @@ -1,5 +1,4 @@ from template_type_namespace import * if type(foo()[0]) != type(""): - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/template_typedef_cplx2_runme.py b/Examples/test-suite/python/template_typedef_cplx2_runme.py index 04c599329..3043d4285 100644 --- a/Examples/test-suite/python/template_typedef_cplx2_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx2_runme.py @@ -5,28 +5,28 @@ from template_typedef_cplx2 import * # try: - d = make_Identity_double() - a = d.this + d = make_Identity_double() + a = d.this except: - print d, "is not an instance" - raise RuntimeError + print d, "is not an instance" + raise RuntimeError s = '%s' % d if str.find(s, 'ArithUnaryFunction') == -1: - print d, "is not an ArithUnaryFunction" - raise RuntimeError + print d, "is not an ArithUnaryFunction" + raise RuntimeError try: - e = make_Multiplies_double_double_double_double(d, d) - a = e.this + e = make_Multiplies_double_double_double_double(d, d) + a = e.this except: - print e, "is not an instance" - raise RuntimeError + print e, "is not an instance" + raise RuntimeError s = '%s' % e if str.find(s, 'ArithUnaryFunction') == -1: - print e, "is not an ArithUnaryFunction" - raise RuntimeError + print e, "is not an ArithUnaryFunction" + raise RuntimeError # @@ -34,61 +34,60 @@ if str.find(s, 'ArithUnaryFunction') == -1: # try: - c = make_Identity_complex() - a = c.this + c = make_Identity_complex() + a = c.this except: - print c, "is not an instance" - raise RuntimeError + print c, "is not an instance" + raise RuntimeError s = '%s' % c if str.find(s, 'ArithUnaryFunction') == -1: - print c, "is not an ArithUnaryFunction" - raise RuntimeError + print c, "is not an ArithUnaryFunction" + raise RuntimeError try: - f = make_Multiplies_complex_complex_complex_complex(c, c) - a = f.this + f = make_Multiplies_complex_complex_complex_complex(c, c) + a = f.this except: - print f, "is not an instance" - raise RuntimeError + print f, "is not an instance" + raise RuntimeError s = '%s' % f if str.find(s, 'ArithUnaryFunction') == -1: - print f, "is not an ArithUnaryFunction" - raise RuntimeError + print f, "is not an ArithUnaryFunction" + raise RuntimeError # # Mix case # try: - g = make_Multiplies_double_double_complex_complex(d, c) - a = g.this + g = make_Multiplies_double_double_complex_complex(d, c) + a = g.this except: - print g, "is not an instance" - raise RuntimeError + print g, "is not an instance" + raise RuntimeError s = '%s' % g if str.find(s, 'ArithUnaryFunction') == -1: - print g, "is not an ArithUnaryFunction" - raise RuntimeError + print g, "is not an ArithUnaryFunction" + raise RuntimeError try: - h = make_Multiplies_complex_complex_double_double(c, d) - a = h.this + h = make_Multiplies_complex_complex_double_double(c, d) + a = h.this except: - print h, "is not an instance" - raise RuntimeError + print h, "is not an instance" + raise RuntimeError s = '%s' % h if str.find(s, 'ArithUnaryFunction') == -1: - print h, "is not an ArithUnaryFunction" - raise RuntimeError + print h, "is not an ArithUnaryFunction" + raise RuntimeError try: - a = g.get_value() + a = g.get_value() except: - print g, "has not get_value() method" - raise RuntimeError - + print g, "has not get_value() method" + raise RuntimeError diff --git a/Examples/test-suite/python/template_typedef_cplx3_runme.py b/Examples/test-suite/python/template_typedef_cplx3_runme.py index b8ac1b6ef..ad361426e 100644 --- a/Examples/test-suite/python/template_typedef_cplx3_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx3_runme.py @@ -11,14 +11,14 @@ s.get_base_value() s.get_value() s.get_arith_value() my_func_r(s) -make_Multiplies_double_double_double_double(s,s) +make_Multiplies_double_double_double_double(s, s) z = CSin() z.get_base_value() z.get_value() z.get_arith_value() my_func_c(z) -make_Multiplies_complex_complex_complex_complex(z,z) +make_Multiplies_complex_complex_complex_complex(z, z) # # Here we fail @@ -28,7 +28,3 @@ my_func_r(d) c = make_Identity_complex() my_func_c(c) - - - - diff --git a/Examples/test-suite/python/template_typedef_cplx4_runme.py b/Examples/test-suite/python/template_typedef_cplx4_runme.py index faeca219f..25ac851fb 100644 --- a/Examples/test-suite/python/template_typedef_cplx4_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx4_runme.py @@ -11,14 +11,14 @@ s.get_base_value() s.get_value() s.get_arith_value() my_func_r(s) -make_Multiplies_double_double_double_double(s,s) +make_Multiplies_double_double_double_double(s, s) z = CSin() z.get_base_value() z.get_value() z.get_arith_value() my_func_c(z) -make_Multiplies_complex_complex_complex_complex(z,z) +make_Multiplies_complex_complex_complex_complex(z, z) # # Here we fail @@ -28,7 +28,3 @@ my_func_r(d) c = make_Identity_complex() my_func_c(c) - - - - diff --git a/Examples/test-suite/python/template_typedef_cplx_runme.py b/Examples/test-suite/python/template_typedef_cplx_runme.py index 2cd9c8348..afb97d070 100644 --- a/Examples/test-suite/python/template_typedef_cplx_runme.py +++ b/Examples/test-suite/python/template_typedef_cplx_runme.py @@ -5,28 +5,28 @@ from template_typedef_cplx import * # try: - d = make_Identity_double() - a = d.this + d = make_Identity_double() + a = d.this except: - print d, "is not an instance" - raise RuntimeError + print d, "is not an instance" + raise RuntimeError s = '%s' % d if str.find(s, 'ArithUnaryFunction') == -1: - print d, "is not an ArithUnaryFunction" - raise RuntimeError + print d, "is not an ArithUnaryFunction" + raise RuntimeError try: - e = make_Multiplies_double_double_double_double(d, d) - a = e.this + e = make_Multiplies_double_double_double_double(d, d) + a = e.this except: - print e, "is not an instance" - raise RuntimeError + print e, "is not an instance" + raise RuntimeError s = '%s' % e if str.find(s, 'ArithUnaryFunction') == -1: - print e, "is not an ArithUnaryFunction" - raise RuntimeError + print e, "is not an ArithUnaryFunction" + raise RuntimeError # @@ -34,54 +34,54 @@ if str.find(s, 'ArithUnaryFunction') == -1: # try: - c = make_Identity_complex() - a = c.this + c = make_Identity_complex() + a = c.this except: - print c, "is not an instance" - raise RuntimeError + print c, "is not an instance" + raise RuntimeError s = '%s' % c if str.find(s, 'ArithUnaryFunction') == -1: - print c, "is not an ArithUnaryFunction" - raise RuntimeError + print c, "is not an ArithUnaryFunction" + raise RuntimeError try: - f = make_Multiplies_complex_complex_complex_complex(c, c) - a = f.this + f = make_Multiplies_complex_complex_complex_complex(c, c) + a = f.this except: - print f, "is not an instance" - raise RuntimeError + print f, "is not an instance" + raise RuntimeError s = '%s' % f if str.find(s, 'ArithUnaryFunction') == -1: - print f, "is not an ArithUnaryFunction" - raise RuntimeError + print f, "is not an ArithUnaryFunction" + raise RuntimeError # # Mix case # try: - g = make_Multiplies_double_double_complex_complex(d, c) - a = g.this + g = make_Multiplies_double_double_complex_complex(d, c) + a = g.this except: - print g, "is not an instance" - raise RuntimeError + print g, "is not an instance" + raise RuntimeError s = '%s' % g if str.find(s, 'ArithUnaryFunction') == -1: - print g, "is not an ArithUnaryFunction" - raise RuntimeError + print g, "is not an ArithUnaryFunction" + raise RuntimeError try: - h = make_Multiplies_complex_complex_double_double(c, d) - a = h.this + h = make_Multiplies_complex_complex_double_double(c, d) + a = h.this except: - print h, "is not an instance" - raise RuntimeError + print h, "is not an instance" + raise RuntimeError s = '%s' % h if str.find(s, 'ArithUnaryFunction') == -1: - print h, "is not an ArithUnaryFunction" - raise RuntimeError + print h, "is not an ArithUnaryFunction" + raise RuntimeError diff --git a/Examples/test-suite/python/template_typedef_import_runme.py b/Examples/test-suite/python/template_typedef_import_runme.py index 5c0b0b936..5da489fea 100644 --- a/Examples/test-suite/python/template_typedef_import_runme.py +++ b/Examples/test-suite/python/template_typedef_import_runme.py @@ -11,14 +11,14 @@ s.get_base_value() s.get_value() s.get_arith_value() my_func_r(s) -make_Multiplies_double_double_double_double(s,s) +make_Multiplies_double_double_double_double(s, s) z = CSin() z.get_base_value() z.get_value() z.get_arith_value() my_func_c(z) -make_Multiplies_complex_complex_complex_complex(z,z) +make_Multiplies_complex_complex_complex_complex(z, z) # # Here we fail @@ -28,7 +28,3 @@ my_func_r(d) c = make_Identity_complex() my_func_c(c) - - - - diff --git a/Examples/test-suite/python/template_typedef_runme.py b/Examples/test-suite/python/template_typedef_runme.py index 4b3970593..16695bada 100644 --- a/Examples/test-suite/python/template_typedef_runme.py +++ b/Examples/test-suite/python/template_typedef_runme.py @@ -5,42 +5,42 @@ c = make_Identity_reald() try: - a = d.this - a = c.this + a = d.this + a = c.this except: - raise RuntimeError + raise RuntimeError try: - e = make_Multiplies_float_float_float_float(d, d) - a = e.this + e = make_Multiplies_float_float_float_float(d, d) + a = e.this except: - print e, "is not an instance" - raise RuntimeError + print e, "is not an instance" + raise RuntimeError try: - f = make_Multiplies_reald_reald_reald_reald(c, c) - a = f.this + f = make_Multiplies_reald_reald_reald_reald(c, c) + a = f.this except: - print f, "is not an instance" - raise RuntimeError + print f, "is not an instance" + raise RuntimeError try: - g = make_Multiplies_float_float_reald_reald(d, c) - a = g.this + g = make_Multiplies_float_float_reald_reald(d, c) + a = g.this except: - print g, "is not an instance" - raise RuntimeError + print g, "is not an instance" + raise RuntimeError # the old large format if not SWIG_TypeQuery("vfncs::ArithUnaryFunction::argument_type,vfncs::arith_traits::result_type > *"): - raise RuntimeError + raise RuntimeError # the reduced format if not SWIG_TypeQuery("vfncs::ArithUnaryFunction *"): - raise RuntimeError + raise RuntimeError # this is a bad name if SWIG_TypeQuery("vfncs::ArithUnaryFunction *"): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/template_typemaps_typedef2_runme.py b/Examples/test-suite/python/template_typemaps_typedef2_runme.py index 8a66d27d0..258f44366 100644 --- a/Examples/test-suite/python/template_typemaps_typedef2_runme.py +++ b/Examples/test-suite/python/template_typemaps_typedef2_runme.py @@ -13,8 +13,8 @@ m2 = MultimapAInt() #dummy_pair = m2.make_dummy_pair() #val = m2.typemap_test(dummy_pair) -#print val -#if val != 4321: +# print val +# if val != 4321: # raise RuntimeError, "typemaps not working" if typedef_test1(dummy_pair).val != 1234: @@ -34,4 +34,3 @@ if typedef_test5(dummy_pair).val != 1234: if typedef_test6(dummy_pair).val != 1234: raise RuntimeError, "typedef_test6 not working" - diff --git a/Examples/test-suite/python/template_typemaps_typedef_runme.py b/Examples/test-suite/python/template_typemaps_typedef_runme.py index a4d6fd0a7..1ca3f835c 100644 --- a/Examples/test-suite/python/template_typemaps_typedef_runme.py +++ b/Examples/test-suite/python/template_typemaps_typedef_runme.py @@ -13,8 +13,8 @@ m2 = MultimapAInt() #dummy_pair = m2.make_dummy_pair() #val = m2.typemap_test(dummy_pair) -#print val -#if val != 4321: +# print val +# if val != 4321: # raise RuntimeError, "typemaps not working" if typedef_test1(dummy_pair).val != 1234: @@ -34,4 +34,3 @@ if typedef_test5(dummy_pair).val != 1234: if typedef_test6(dummy_pair).val != 1234: raise RuntimeError, "typedef_test6 not working" - diff --git a/Examples/test-suite/python/threads_exception_runme.py b/Examples/test-suite/python/threads_exception_runme.py index 6fe6947ec..056bd849b 100644 --- a/Examples/test-suite/python/threads_exception_runme.py +++ b/Examples/test-suite/python/threads_exception_runme.py @@ -2,40 +2,39 @@ import threads_exception t = threads_exception.Test() try: - t.unknown() -except RuntimeError,e: - pass + t.unknown() +except RuntimeError, e: + pass try: - t.simple() -except RuntimeError,e: - if e.args[0] != 37: - raise RuntimeError + t.simple() +except RuntimeError, e: + if e.args[0] != 37: + raise RuntimeError try: - t.message() -except RuntimeError,e: - if e.args[0] != "I died.": - raise RuntimeError + t.message() +except RuntimeError, e: + if e.args[0] != "I died.": + raise RuntimeError # This is expected fail with -builtin option # Throwing builtin classes as exceptions not supported if not threads_exception.is_python_builtin(): - try: - t.hosed() - except threads_exception.Exc,e: - code = e.code - if code != 42: - raise RuntimeError, "bad... code: %d" % code - msg = e.msg - if msg != "Hosed": - raise RuntimeError, "bad... msg: '%s' len: %d" % (msg, len(msg)) - -for i in range(1,4): - try: - t.multi(i) - except RuntimeError,e: - pass - except threads_exception.Exc,e: - pass + try: + t.hosed() + except threads_exception.Exc, e: + code = e.code + if code != 42: + raise RuntimeError, "bad... code: %d" % code + msg = e.msg + if msg != "Hosed": + raise RuntimeError, "bad... msg: '%s' len: %d" % (msg, len(msg)) +for i in range(1, 4): + try: + t.multi(i) + except RuntimeError, e: + pass + except threads_exception.Exc, e: + pass diff --git a/Examples/test-suite/python/typedef_class_runme.py b/Examples/test-suite/python/typedef_class_runme.py index 71436b399..6d2f2a5c3 100644 --- a/Examples/test-suite/python/typedef_class_runme.py +++ b/Examples/test-suite/python/typedef_class_runme.py @@ -1,7 +1,7 @@ import typedef_class -a = typedef_class.RealA() -a.a = 3 - -b = typedef_class.B() -b.testA(a) +a = typedef_class.RealA() +a.a = 3 + +b = typedef_class.B() +b.testA(a) diff --git a/Examples/test-suite/python/typedef_scope_runme.py b/Examples/test-suite/python/typedef_scope_runme.py index 37bfc97b1..edd3e9f3a 100644 --- a/Examples/test-suite/python/typedef_scope_runme.py +++ b/Examples/test-suite/python/typedef_scope_runme.py @@ -1,12 +1,10 @@ import typedef_scope b = typedef_scope.Bar() -x = b.test1(42,"hello") +x = b.test1(42, "hello") if x != 42: print "Failed!!" -x = b.test2(42,"hello") +x = b.test2(42, "hello") if x != "hello": print "Failed!!" - - diff --git a/Examples/test-suite/python/typedef_typedef_runme.py b/Examples/test-suite/python/typedef_typedef_runme.py index 1d83065a6..92e85c27e 100644 --- a/Examples/test-suite/python/typedef_typedef_runme.py +++ b/Examples/test-suite/python/typedef_typedef_runme.py @@ -2,4 +2,4 @@ import typedef_typedef b = typedef_typedef.B() if b.getValue(123) != 1234: - raise Exception("Failed") + raise Exception("Failed") diff --git a/Examples/test-suite/python/typemap_arrays_runme.py b/Examples/test-suite/python/typemap_arrays_runme.py index c23222c63..ea0f08d6b 100644 --- a/Examples/test-suite/python/typemap_arrays_runme.py +++ b/Examples/test-suite/python/typemap_arrays_runme.py @@ -2,4 +2,3 @@ from typemap_arrays import * if sumA(None) != 60: raise RuntimeError, "Sum is wrong" - diff --git a/Examples/test-suite/python/typemap_namespace_runme.py b/Examples/test-suite/python/typemap_namespace_runme.py index 581a0f437..b55eb8ba5 100644 --- a/Examples/test-suite/python/typemap_namespace_runme.py +++ b/Examples/test-suite/python/typemap_namespace_runme.py @@ -5,4 +5,3 @@ if test1("hello") != "hello": if test2("hello") != "hello": raise RuntimeError - diff --git a/Examples/test-suite/python/typemap_out_optimal_runme.py b/Examples/test-suite/python/typemap_out_optimal_runme.py index 95556f6bd..c7a34308e 100644 --- a/Examples/test-suite/python/typemap_out_optimal_runme.py +++ b/Examples/test-suite/python/typemap_out_optimal_runme.py @@ -2,4 +2,3 @@ from typemap_out_optimal import * cvar.XX_debug = False x = XX_create() - diff --git a/Examples/test-suite/python/typemap_qualifier_strip_runme.py b/Examples/test-suite/python/typemap_qualifier_strip_runme.py index 5e466cf69..dff94f8b4 100644 --- a/Examples/test-suite/python/typemap_qualifier_strip_runme.py +++ b/Examples/test-suite/python/typemap_qualifier_strip_runme.py @@ -51,4 +51,3 @@ if typemap_qualifier_strip.testD3(val) != 111: if typemap_qualifier_strip.testD4(val) != 111: raise RuntimeError - diff --git a/Examples/test-suite/python/typename_runme.py b/Examples/test-suite/python/typename_runme.py index 10c7bff1b..aac936fde 100644 --- a/Examples/test-suite/python/typename_runme.py +++ b/Examples/test-suite/python/typename_runme.py @@ -4,9 +4,8 @@ f = typename.Foo() b = typename.Bar() x = typename.twoFoo(f) -if not isinstance(x,types.FloatType): - raise RuntimeError,"Wrong return type (FloatType) !" +if not isinstance(x, types.FloatType): + raise RuntimeError, "Wrong return type (FloatType) !" y = typename.twoBar(b) -if not isinstance(y,types.IntType): - raise RuntimeError,"Wrong return type (IntType)!" - +if not isinstance(y, types.IntType): + raise RuntimeError, "Wrong return type (IntType)!" diff --git a/Examples/test-suite/python/types_directive_runme.py b/Examples/test-suite/python/types_directive_runme.py index c28453e84..401e3ae1d 100644 --- a/Examples/test-suite/python/types_directive_runme.py +++ b/Examples/test-suite/python/types_directive_runme.py @@ -1,12 +1,13 @@ from types_directive import * d1 = Time1(2001, 2, 3, 60) -newDate = add(d1, 7) # check that a Time1 instance is accepted where Date is expected +# check that a Time1 instance is accepted where Date is expected +newDate = add(d1, 7) if newDate.day != 10: - raise RuntimeError + raise RuntimeError d2 = Time2(1999, 8, 7, 60) -newDate = add(d2, 7) # check that a Time2 instance is accepted where Date is expected +# check that a Time2 instance is accepted where Date is expected +newDate = add(d2, 7) if newDate.day != 14: - raise RuntimeError - + raise RuntimeError diff --git a/Examples/test-suite/python/unions_runme.py b/Examples/test-suite/python/unions_runme.py index d59e2429e..387a048c8 100644 --- a/Examples/test-suite/python/unions_runme.py +++ b/Examples/test-suite/python/unions_runme.py @@ -1,5 +1,5 @@ -# This is the union runtime testcase. It ensures that values within a +# This is the union runtime testcase. It ensures that values within a # union embedded within a struct can be set and read correctly. import unions @@ -23,12 +23,12 @@ eut.number = 1 eut.uni.small = small Jill1 = eut.uni.small.jill if (Jill1 != 200): - print "Runtime test1 failed. eut.uni.small.jill=" , Jill1 + print "Runtime test1 failed. eut.uni.small.jill=", Jill1 sys.exit(1) Num1 = eut.number if (Num1 != 1): - print "Runtime test2 failed. eut.number=" , Num1 + print "Runtime test2 failed. eut.number=", Num1 sys.exit(1) # Secondly check the BigStruct in EmbeddedUnionTest @@ -36,16 +36,15 @@ eut.number = 2 eut.uni.big = big Jack1 = eut.uni.big.jack if (Jack1 != 300): - print "Runtime test3 failed. eut.uni.big.jack=" , Jack1 + print "Runtime test3 failed. eut.uni.big.jack=", Jack1 sys.exit(1) Jill2 = eut.uni.big.smallstruct.jill if (Jill2 != 200): - print "Runtime test4 failed. eut.uni.big.smallstruct.jill=" , Jill2 + print "Runtime test4 failed. eut.uni.big.smallstruct.jill=", Jill2 sys.exit(1) Num2 = eut.number if (Num2 != 2): - print "Runtime test5 failed. eut.number=" , Num2 + print "Runtime test5 failed. eut.number=", Num2 sys.exit(1) - diff --git a/Examples/test-suite/python/using_composition_runme.py b/Examples/test-suite/python/using_composition_runme.py index 6baa16d13..c4f339095 100644 --- a/Examples/test-suite/python/using_composition_runme.py +++ b/Examples/test-suite/python/using_composition_runme.py @@ -2,33 +2,32 @@ from using_composition import * f = FooBar() if f.blah(3) != 3: - raise RuntimeError,"FooBar::blah(int)" + raise RuntimeError, "FooBar::blah(int)" if f.blah(3.5) != 3.5: - raise RuntimeError,"FooBar::blah(double)" + raise RuntimeError, "FooBar::blah(double)" if f.blah("hello") != "hello": - raise RuntimeError,"FooBar::blah(char *)" + raise RuntimeError, "FooBar::blah(char *)" f = FooBar2() if f.blah(3) != 3: - raise RuntimeError,"FooBar2::blah(int)" + raise RuntimeError, "FooBar2::blah(int)" if f.blah(3.5) != 3.5: - raise RuntimeError,"FooBar2::blah(double)" + raise RuntimeError, "FooBar2::blah(double)" if f.blah("hello") != "hello": - raise RuntimeError,"FooBar2::blah(char *)" + raise RuntimeError, "FooBar2::blah(char *)" f = FooBar3() if f.blah(3) != 3: - raise RuntimeError,"FooBar3::blah(int)" + raise RuntimeError, "FooBar3::blah(int)" if f.blah(3.5) != 3.5: - raise RuntimeError,"FooBar3::blah(double)" + raise RuntimeError, "FooBar3::blah(double)" if f.blah("hello") != "hello": - raise RuntimeError,"FooBar3::blah(char *)" - + raise RuntimeError, "FooBar3::blah(char *)" diff --git a/Examples/test-suite/python/using_extend_runme.py b/Examples/test-suite/python/using_extend_runme.py index 14615a05e..038a1686a 100644 --- a/Examples/test-suite/python/using_extend_runme.py +++ b/Examples/test-suite/python/using_extend_runme.py @@ -2,20 +2,20 @@ from using_extend import * f = FooBar() if f.blah(3) != 3: - raise RuntimeError,"blah(int)" + raise RuntimeError, "blah(int)" if f.blah(3.5) != 3.5: - raise RuntimeError,"blah(double)" + raise RuntimeError, "blah(double)" if f.blah("hello") != "hello": - raise RuntimeError,"blah(char *)" + raise RuntimeError, "blah(char *)" -if f.blah(3,4) != 7: - raise RuntimeError,"blah(int,int)" +if f.blah(3, 4) != 7: + raise RuntimeError, "blah(int,int)" -if f.blah(3.5,7.5) != (3.5+7.5): - raise RuntimeError,"blah(double,double)" +if f.blah(3.5, 7.5) != (3.5 + 7.5): + raise RuntimeError, "blah(double,double)" if f.duh(3) != 3: - raise RuntimeError,"duh(int)" + raise RuntimeError, "duh(int)" diff --git a/Examples/test-suite/python/using_inherit_runme.py b/Examples/test-suite/python/using_inherit_runme.py index b00e66ec3..4fd595968 100644 --- a/Examples/test-suite/python/using_inherit_runme.py +++ b/Examples/test-suite/python/using_inherit_runme.py @@ -2,48 +2,47 @@ from using_inherit import * b = Bar() if b.test(3) != 3: - raise RuntimeError,"Bar::test(int)" + raise RuntimeError, "Bar::test(int)" if b.test(3.5) != 3.5: - raise RuntimeError, "Bar::test(double)" + raise RuntimeError, "Bar::test(double)" b = Bar2() if b.test(3) != 6: - raise RuntimeError,"Bar2::test(int)" + raise RuntimeError, "Bar2::test(int)" if b.test(3.5) != 7.0: - raise RuntimeError, "Bar2::test(double)" + raise RuntimeError, "Bar2::test(double)" b = Bar3() if b.test(3) != 6: - raise RuntimeError,"Bar3::test(int)" + raise RuntimeError, "Bar3::test(int)" if b.test(3.5) != 7.0: - raise RuntimeError, "Bar3::test(double)" + raise RuntimeError, "Bar3::test(double)" b = Bar4() if b.test(3) != 6: - raise RuntimeError,"Bar4::test(int)" + raise RuntimeError, "Bar4::test(int)" if b.test(3.5) != 7.0: - raise RuntimeError, "Bar4::test(double)" + raise RuntimeError, "Bar4::test(double)" b = Fred1() if b.test(3) != 3: - raise RuntimeError,"Fred1::test(int)" + raise RuntimeError, "Fred1::test(int)" if b.test(3.5) != 7.0: - raise RuntimeError, "Fred1::test(double)" + raise RuntimeError, "Fred1::test(double)" b = Fred2() if b.test(3) != 3: - raise RuntimeError,"Fred2::test(int)" + raise RuntimeError, "Fred2::test(int)" if b.test(3.5) != 7.0: - raise RuntimeError, "Fred2::test(double)" - + raise RuntimeError, "Fred2::test(double)" diff --git a/Examples/test-suite/python/varargs_overload_runme.py b/Examples/test-suite/python/varargs_overload_runme.py index a3b2068b5..37958620c 100644 --- a/Examples/test-suite/python/varargs_overload_runme.py +++ b/Examples/test-suite/python/varargs_overload_runme.py @@ -28,4 +28,3 @@ if varargs_overload.vararg_over4(123) != "123": if varargs_overload.vararg_over4("Hello", 123) != "Hello": raise RuntimeError, "Failed" - diff --git a/Examples/test-suite/python/varargs_runme.py b/Examples/test-suite/python/varargs_runme.py index 2c68f4e06..7105ba8d7 100644 --- a/Examples/test-suite/python/varargs_runme.py +++ b/Examples/test-suite/python/varargs_runme.py @@ -11,7 +11,7 @@ if f.test("Hello") != "Hello": raise RuntimeError, "Failed" -if varargs.test_def("Hello",1) != "Hello": +if varargs.test_def("Hello", 1) != "Hello": raise RuntimeError, "Failed" if varargs.test_def("Hello") != "Hello": diff --git a/Examples/test-suite/python/virtual_derivation_runme.py b/Examples/test-suite/python/virtual_derivation_runme.py index 8a6e743af..68546c6eb 100644 --- a/Examples/test-suite/python/virtual_derivation_runme.py +++ b/Examples/test-suite/python/virtual_derivation_runme.py @@ -4,5 +4,4 @@ from virtual_derivation import * # b = B(3) if b.get_a() != b.get_b(): - raise RuntimeError, "something is really wrong" - + raise RuntimeError, "something is really wrong" diff --git a/Examples/test-suite/python/virtual_poly_runme.py b/Examples/test-suite/python/virtual_poly_runme.py index 7e202f9cf..0df6271ef 100644 --- a/Examples/test-suite/python/virtual_poly_runme.py +++ b/Examples/test-suite/python/virtual_poly_runme.py @@ -5,25 +5,25 @@ i = virtual_poly.NInt(2) # # the copy methods return the right polymorphic types -# +# dc = d.copy() ic = i.copy() if d.get() != dc.get(): - raise RuntimeError + raise RuntimeError if i.get() != ic.get(): - raise RuntimeError + raise RuntimeError virtual_poly.incr(ic) if (i.get() + 1) != ic.get(): - raise RuntimeError + raise RuntimeError dr = d.ref_this() if d.get() != dr.get(): - raise RuntimeError + raise RuntimeError # @@ -31,8 +31,8 @@ if d.get() != dr.get(): # ddc = virtual_poly.NDouble_narrow(d.nnumber()) if d.get() != ddc.get(): - raise RuntimeError + raise RuntimeError dic = virtual_poly.NInt_narrow(i.nnumber()) if i.get() != dic.get(): - raise RuntimeError + raise RuntimeError diff --git a/Examples/test-suite/python/voidtest_runme.py b/Examples/test-suite/python/voidtest_runme.py index a7b421d6e..b16cacf00 100644 --- a/Examples/test-suite/python/voidtest_runme.py +++ b/Examples/test-suite/python/voidtest_runme.py @@ -6,10 +6,11 @@ f.memberfunc() voidtest.Foo_staticmemberfunc() + def fvoid(): pass -if f.memberfunc() != fvoid(): +if f.memberfunc() != fvoid(): raise RuntimeError diff --git a/Examples/test-suite/python/wrapmacro_runme.py b/Examples/test-suite/python/wrapmacro_runme.py index 0272afd5d..5e28d6bc9 100644 --- a/Examples/test-suite/python/wrapmacro_runme.py +++ b/Examples/test-suite/python/wrapmacro_runme.py @@ -2,6 +2,6 @@ import wrapmacro a = 2 b = -1 -wrapmacro.maximum(a,b) -wrapmacro.maximum(a/7.0, -b*256) +wrapmacro.maximum(a, b) +wrapmacro.maximum(a / 7.0, -b * 256) wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1) diff --git a/Examples/test-suite/python_pythoncode.i b/Examples/test-suite/python_pythoncode.i new file mode 100644 index 000000000..70474d44c --- /dev/null +++ b/Examples/test-suite/python_pythoncode.i @@ -0,0 +1,31 @@ +%module python_pythoncode + +// github issue#379 - these examples failed with 3.0.5 and earlier (at least as +// far back as 1.3.37): + +struct TYPE { +%pythoncode %{ + def one(): + a = 1 +# Comment XXXX + return a +%} +}; + +%define %bar +%pythoncode %{ + def one(): + a = 1 + # + return a +%} +%enddef + +struct TYPE2 { +%bar +}; + +%{ +struct TYPE { }; +struct TYPE2 { }; +%} diff --git a/Examples/test-suite/python_varargs_typemap.i b/Examples/test-suite/python_varargs_typemap.i index 09deea3b7..c7d8b83ec 100644 --- a/Examples/test-suite/python_varargs_typemap.i +++ b/Examples/test-suite/python_varargs_typemap.i @@ -6,7 +6,7 @@ %typemap(in) (...)(char *vargs[10]) { int i; - int argc; + Py_ssize_t argc; for (i = 0; i < 10; i++) vargs[i] = 0; argc = PyTuple_Size(varargs); if (argc > 10) { diff --git a/Examples/test-suite/ruby/default_constructor_runme.rb b/Examples/test-suite/ruby/default_constructor_runme.rb index 2706f67ca..5cd675879 100644 --- a/Examples/test-suite/ruby/default_constructor_runme.rb +++ b/Examples/test-suite/ruby/default_constructor_runme.rb @@ -143,9 +143,6 @@ end # This should work fine f = F.new -# This should work fine -ff = FFF.new - # This should work fine g = G.new diff --git a/Examples/test-suite/scilab/default_constructor_runme.sci b/Examples/test-suite/scilab/default_constructor_runme.sci index 6c5250bec..26726f1e0 100644 --- a/Examples/test-suite/scilab/default_constructor_runme.sci +++ b/Examples/test-suite/scilab/default_constructor_runme.sci @@ -84,15 +84,6 @@ end F_destroy(f); -ff = new_FFF(); -try - del_ff = delete_FFF; - swigtesterror("delete_FFF created") -catch -end - -F_destroy(ff); - g = new_G(); try diff --git a/Examples/test-suite/template_classes.i b/Examples/test-suite/template_classes.i index ebe13bd9f..d357e418e 100644 --- a/Examples/test-suite/template_classes.i +++ b/Examples/test-suite/template_classes.i @@ -18,6 +18,9 @@ class RectangleTest { public: Point& getPoint() {return point;} void setPoint(Point& value) {point = value;} + + static int static_noargs() { return 0; } + static int static_onearg(int i) { return i; } private: Point point; diff --git a/Examples/test-suite/template_keyword_in_type.i b/Examples/test-suite/template_keyword_in_type.i new file mode 100644 index 000000000..b54b8ad4a --- /dev/null +++ b/Examples/test-suite/template_keyword_in_type.i @@ -0,0 +1,42 @@ +%module template_keyword_in_type + +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) YYY; + +%inline %{ + template struct XXX; + + template struct XXX { + template struct YYY { + typedef TT type; + }; + int xxx(int h) { return h; } + }; + +#if defined(SWIG) || defined(__clang__) + // gcc doesn't parse this (tested with gcc-4.8) + template void testXXX1(::template XXX::template YYY::type xx) {} +#else + template void testXXX1(:: XXX::template YYY::type xx) {} +#endif + template void testXXX2(XXX::YYY::type xx) {} + template void testXXX3(::XXX::template YYY::type) {} +%} + +%inline %{ +typedef double Val; +template struct ListBucket { +}; +namespace Alloc { + template struct rebind { + typedef int other; + }; +} + +template void other1(typename Alloc::template rebind >::other) {} +#if !defined(__SUNPRO_CC) +template void other2(typename Alloc::template rebind< ::template ListBucket >::other) {} +#else +template void other2(typename Alloc::template rebind< :: ListBucket >::other) {} +#endif +template void other3(Alloc::template rebind) {} +%} diff --git a/Examples/test-suite/testdir/go_subdir_import/go_subdir_import_c.i b/Examples/test-suite/testdir/go_subdir_import/go_subdir_import_c.i new file mode 100644 index 000000000..dff269c3f --- /dev/null +++ b/Examples/test-suite/testdir/go_subdir_import/go_subdir_import_c.i @@ -0,0 +1,12 @@ +/* File : go_subdir_import_c.i */ +%module go_subdir_import_c + +%inline %{ +class ObjC { + public: + virtual int getInt() const { + return 18; + } +}; +%} + diff --git a/Lib/csharp/csharp.swg b/Lib/csharp/csharp.swg index 94a0771ba..f7b7927ba 100644 --- a/Lib/csharp/csharp.swg +++ b/Lib/csharp/csharp.swg @@ -203,7 +203,7 @@ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { %typemap(directorin) int "$input = $1;" %typemap(directorin) unsigned int "$input = $1;" %typemap(directorin) long "$input = $1;" -%typemap(directorin) unsigned long "$input = $1;" +%typemap(directorin) unsigned long "$input = (unsigned long)$1;" %typemap(directorin) long long "$input = $1;" %typemap(directorin) unsigned long long "$input = $1;" %typemap(directorin) float "$input = $1;" diff --git a/Lib/director_common.swg b/Lib/director_common.swg new file mode 100644 index 000000000..9ce93c7e7 --- /dev/null +++ b/Lib/director_common.swg @@ -0,0 +1,15 @@ +/* ----------------------------------------------------------------------------- + * director_common.swg + * + * This file contains support for director classes which is common between + * languages. + * ----------------------------------------------------------------------------- */ + +/* + Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the + 'Swig' namespace. This could be useful for multi-modules projects. +*/ +#ifdef SWIG_DIRECTOR_STATIC +/* Force anonymous (static) namespace */ +#define Swig +#endif diff --git a/Lib/go/go.swg b/Lib/go/go.swg index d38623b4a..35f914c5b 100644 --- a/Lib/go/go.swg +++ b/Lib/go/go.swg @@ -533,7 +533,7 @@ %typemap(directorin) enum SWIGTYPE & (intgo e) %{ e = (intgo)$1; - $input = &e; + $input = ($1_ltype)&e; %} %typemap(godirectorin) enum SWIGTYPE & "" diff --git a/Lib/go/goruntime.swg b/Lib/go/goruntime.swg index 19ccf5ae9..031a7f6f0 100644 --- a/Lib/go/goruntime.swg +++ b/Lib/go/goruntime.swg @@ -19,21 +19,45 @@ static void Swig_free(void* p) { %} +#if SWIGGO_CGO +%insert(cgo_comment_typedefs) %{ +#include +%} +#endif + #if SWIGGO_INTGO_SIZE == 32 %insert(runtime) %{ typedef int intgo; typedef unsigned int uintgo; %} +#if SWIGGO_CGO +%insert(cgo_comment_typedefs) %{ +typedef int intgo; +typedef unsigned int uintgo; +%} +#endif #elif SWIGGO_INTGO_SIZE == 64 %insert(runtime) %{ typedef long long intgo; typedef unsigned long long uintgo; %} +#if SWIGGO_CGO +%insert(cgo_comment_typedefs) %{ +typedef long long intgo; +typedef unsigned long long uintgo; +%} +#endif #else %insert(runtime) %{ typedef ptrdiff_t intgo; typedef size_t uintgo; %} +#if SWIGGO_CGO +%insert(cgo_comment_typedefs) %{ +typedef ptrdiff_t intgo; +typedef size_t uintgo; +%} +#endif #endif %insert(runtime) %{ @@ -43,6 +67,17 @@ typedef struct { void* array; intgo len; intgo cap; } _goslice_; %} +#ifdef SWIGGO_CGO + +%insert(cgo_comment_typedefs) %{ + +typedef struct { char *p; intgo n; } _gostring_; +typedef struct { void* array; intgo len; intgo cap; } _goslice_; + +%} + +#endif + #ifndef SWIGGO_GCCGO /* Boilerplate for C/C++ code when using 6g/8g. This code is compiled with gcc. */ @@ -78,6 +113,22 @@ static char *_swig_topofstack() { } } +static void _swig_gopanic(const char *p) { + struct { + const char *p; + } a; + a.p = p; + crosscall2(_cgo_panic, &a, (int) sizeof a); +} + +%} + +#if !SWIGGO_CGO + +/* This is here for backward compatibility, but it will not work + with Go 1.5 or later. Do not use it in new code. */ +%insert(runtime) %{ + static void *_swig_goallocate(size_t len) { struct { size_t len; @@ -88,16 +139,12 @@ static void *_swig_goallocate(size_t len) { return a.ret; } -static void _swig_gopanic(const char *p) { - struct { - const char *p; - } a; - a.p = p; - crosscall2(_cgo_panic, &a, (int) sizeof a); -} - %} +#endif + +#if !SWIGGO_CGO + /* Boilerplate for C code when using 6g/8g. This code is compiled with 6c/8c. */ %insert(gc_header) %{ @@ -111,6 +158,8 @@ void *·_cgo_runtime_cgocall = &cgocall; %} +#endif + #else /* Boilerplate for C/C++ code when using gccgo. */ @@ -122,6 +171,17 @@ extern "C" { #endif extern void *_cgo_allocate(size_t); extern void _cgo_panic(const char *); +#ifdef __cplusplus +} +#endif + +#define _swig_goallocate _cgo_allocate +#define _swig_gopanic _cgo_panic +%} + +#if !SWIGGO_CGO + +%insert(runtime) %{ /* Implementations of SwigCgocall and friends for different versions of gccgo. The Go code will call these functions using C names with @@ -130,6 +190,10 @@ extern void _cgo_panic(const char *); version. We assume that the version of gcc used to compile this file is the same as the version of gccgo. */ +#ifdef __cplusplus +extern "C" { +#endif + #define SWIG_GCC_VERSION \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) @@ -184,15 +248,18 @@ void SwigCgocallBackDone() { } #endif -#define _swig_goallocate _cgo_allocate -#define _swig_gopanic _cgo_panic - %} #endif +#endif + +#if !SWIGGO_CGO + %insert(runtime) %{ +/* This is here for backward compatibility, but it will not work + with Go 1.5 or later. Do not use it in new code. */ static _gostring_ _swig_makegostring(const char *p, size_t l) { _gostring_ ret; ret.p = (char*)_swig_goallocate(l + 1); @@ -201,6 +268,12 @@ static _gostring_ _swig_makegostring(const char *p, size_t l) { return ret; } +%} + +#endif + +%insert(runtime) %{ + #define SWIG_contract_assert(expr, msg) \ if (!(expr)) { _swig_gopanic(msg); } else %} @@ -209,9 +282,11 @@ static _gostring_ _swig_makegostring(const char *p, size_t l) { %go_import("unsafe", _ "runtime/cgo") +#if !SWIGGO_CGO %insert(go_header) %{ var _cgo_runtime_cgocall func(unsafe.Pointer, uintptr) %} +#endif #else @@ -317,3 +392,58 @@ static void swig_acquire_pointer(Swig_memory** pmem, Type* ptr) { (*pmem)->swig_acquire_pointer(ptr); } %} + +/* For directors we need C++ to track a Go pointer. Since we can't + pass a Go pointer into C++, we use a map to track the pointers on + the Go side. */ + +%go_import("sync") + +%insert(go_header) %{ +type _ sync.Mutex +%} + +%insert(go_director) %{ + +var swigDirectorTrack struct { + sync.Mutex + m map[int]interface{} + c int +} + +func swigDirectorAdd(v interface{}) int { + swigDirectorTrack.Lock() + defer swigDirectorTrack.Unlock() + if swigDirectorTrack.m == nil { + swigDirectorTrack.m = make(map[int]interface{}) + } + swigDirectorTrack.c++ + ret := swigDirectorTrack.c + swigDirectorTrack.m[ret] = v + return ret +} + +func swigDirectorLookup(c int) interface{} { + swigDirectorTrack.Lock() + defer swigDirectorTrack.Unlock() + ret := swigDirectorTrack.m[c] + if ret == nil { + panic("C++ director pointer not found (possible use-after-free)") + } + return ret +} + +func swigDirectorDelete(c int) { + swigDirectorTrack.Lock() + defer swigDirectorTrack.Unlock() + if swigDirectorTrack.m[c] == nil { + if c > swigDirectorTrack.c { + panic("C++ director pointer invalid (possible memory corruption") + } else { + panic("C++ director pointer not found (possible use-after-free)") + } + } + delete(swigDirectorTrack.m, c) +} + +%} diff --git a/Lib/java/director.swg b/Lib/java/director.swg index 031cdf2a9..355e62d67 100644 --- a/Lib/java/director.swg +++ b/Lib/java/director.swg @@ -209,6 +209,20 @@ namespace Swig { } }; + // Zero initialized bool array + template class BoolArray { + bool array_[N]; + public: + BoolArray() { + memset(array_, 0, sizeof(array_)); + } + bool& operator[](size_t n) { + return array_[n]; + } + bool operator[](size_t n) const { + return array_[n]; + } + }; // Utility classes and functions for exception handling. @@ -355,7 +369,7 @@ namespace Swig { static char *copystr(const char *srcmsg) { char *target = 0; if (srcmsg) { - int msglen = strlen(srcmsg) + 1; + size_t msglen = strlen(srcmsg) + 1; target = new char[msglen]; strncpy(target, srcmsg, msglen); } @@ -367,7 +381,7 @@ namespace Swig { }; // Helper method to determine if a Java throwable matches a particular Java class type - bool ExceptionMatches(JNIEnv *jenv, jthrowable throwable, const char *classname) { + SWIGINTERN bool ExceptionMatches(JNIEnv *jenv, jthrowable throwable, const char *classname) { bool matches = false; if (throwable && jenv && classname) { diff --git a/Lib/java/java.swg b/Lib/java/java.swg index e7e041d13..22a4884ef 100644 --- a/Lib/java/java.swg +++ b/Lib/java/java.swg @@ -1341,12 +1341,14 @@ SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE) if ($input) JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *)$1, 0); } %typemap(directorin, descriptor="[B") (char *STRING, size_t LENGTH) { - jbyteArray jb = (jenv)->NewByteArray($2); - (jenv)->SetByteArrayRegion(jb, 0, $2, (jbyte *)$1); + jbyteArray jb = (jenv)->NewByteArray((jsize)$2); + (jenv)->SetByteArrayRegion(jb, 0, (jsize)$2, (jbyte *)$1); $input = jb; } %typemap(directorargout) (char *STRING, size_t LENGTH) -%{(jenv)->GetByteArrayRegion($input, 0, $2, (jbyte *)$1); %} +%{(jenv)->GetByteArrayRegion($input, 0, (jsize)$2, (jbyte *)$1); +(jenv)->DeleteLocalRef($input);%} +%typemap(javadirectorin, descriptor="[B") (char *STRING, size_t LENGTH) "$jniinput" %apply (char *STRING, size_t LENGTH) { (char *STRING, int LENGTH) } /* java keywords */ diff --git a/Lib/java/various.i b/Lib/java/various.i index bfcf346d3..e8042b763 100644 --- a/Lib/java/various.i +++ b/Lib/java/various.i @@ -65,7 +65,7 @@ %typemap(out) char **STRING_ARRAY { if ($1) { int i; - int len=0; + jsize len=0; jstring temp_string; const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String"); diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index b37059cca..dc4d37a48 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -101,7 +101,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #define SWIG_fail goto fail #define SWIGV8_OVERLOAD false -static void SWIG_V8_Raise(const char *msg) { +SWIGINTERN void SWIG_V8_Raise(const char *msg) { SWIGV8_THROW_EXCEPTION(v8::Exception::Error(SWIGV8_STRING_NEW(msg))); } @@ -126,7 +126,7 @@ public: } }; // this is used in usually -static V8ErrorHandler SWIGV8_ErrorHandler; +SWIGRUNTIME V8ErrorHandler SWIGV8_ErrorHandler; // instances of this are used in overloaded functions class OverloadErrorHandler: public V8ErrorHandler { @@ -198,9 +198,9 @@ public: #endif }; -static v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; +SWIGRUNTIME v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; -static int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void **ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void **ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE(); if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; @@ -234,22 +234,22 @@ static int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void **ptr, #if (SWIG_V8_VERSION < 0x031710) -static void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { +SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); #elif (SWIG_V8_VERSION < 0x031900) -static void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Value > object, void *parameter) { +SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast(parameter); #elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -static void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { +SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { #else -static void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackData &data) { +SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackData &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif delete proxy; } -static int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) { +SWIGRUNTIME int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) { if(!valRef->IsObject()) { return SWIG_TypeError; } @@ -273,7 +273,7 @@ static int SWIG_V8_GetInstancePtr(v8::Handle valRef, void **ptr) { return SWIG_OK; } -static void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, swig_type_info *info, int flags) { +SWIGRUNTIME void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, swig_type_info *info, int flags) { SWIGV8_Proxy *cdata = new SWIGV8_Proxy(); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; @@ -330,7 +330,7 @@ static void SWIGV8_SetPrivateData(v8::Handle obj, void *ptr, swig_ty } -static int SWIG_V8_ConvertPtr(v8::Handle valRef, void **ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_V8_ConvertPtr(v8::Handle valRef, void **ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE(); /* special case: JavaScript null => C NULL pointer */ @@ -345,7 +345,7 @@ static int SWIG_V8_ConvertPtr(v8::Handle valRef, void **ptr, swig_typ return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } -static v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { +SWIGRUNTIME v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { SWIGV8_HANDLESCOPE_ESC(); v8::Handle class_templ; @@ -393,7 +393,7 @@ static v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *in #define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) -static SwigV8ReturnValue _SWIGV8_wrap_equals(const SwigV8Arguments &args) { +SWIGRUNTIME SwigV8ReturnValue _SWIGV8_wrap_equals(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); v8::Handle jsresult; @@ -423,7 +423,7 @@ fail: SWIGV8_RETURN(SWIGV8_UNDEFINED()); } -static SwigV8ReturnValue _wrap_getCPtr(const SwigV8Arguments &args) { +SWIGRUNTIME SwigV8ReturnValue _wrap_getCPtr(const SwigV8Arguments &args) { SWIGV8_HANDLESCOPE(); v8::Handle jsresult; @@ -512,15 +512,15 @@ int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swi } #if (SWIG_V8_VERSION < 0x031710) -static void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) { +SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) { SwigV8PackedData *cdata = static_cast(parameter); #elif (SWIG_V8_VERSION < 0x031900) -static void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent object, void *parameter) { +SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent object, void *parameter) { SwigV8PackedData *cdata = static_cast(parameter); #elif (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) -static void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent *object, SwigV8PackedData *cdata) { +SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent *object, SwigV8PackedData *cdata) { #else -static void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackData &data) { +SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackData &data) { v8::Local object = data.GetValue(); SwigV8PackedData *cdata = data.GetParameter(); #endif diff --git a/Lib/lua/lua.swg b/Lib/lua/lua.swg index 892d15798..9c21d0812 100644 --- a/Lib/lua/lua.swg +++ b/Lib/lua/lua.swg @@ -185,7 +185,7 @@ use %include instead // char is changed to a string %typemap(throws) char -%{lua_pushfstring(L,"%c",$1);SWIG_fail;%} +%{lua_pushlstring(L,&$1,1);SWIG_fail;%} /* Throwing object is a serious problem: diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index d9124887d..721fac22b 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1831,7 +1831,7 @@ SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { switch(constants[i].type) { case SWIG_LUA_INT: lua_pushstring(L,constants[i].name); - lua_pushnumber(L,(lua_Number)constants[i].lvalue); + lua_pushinteger(L,(lua_Number)constants[i].lvalue); lua_rawset(L,-3); break; case SWIG_LUA_FLOAT: @@ -1841,7 +1841,10 @@ SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { break; case SWIG_LUA_CHAR: lua_pushstring(L,constants[i].name); - lua_pushfstring(L,"%c",(char)constants[i].lvalue); + { + char c = constants[i].lvalue; + lua_pushlstring(L,&c,1); + } lua_rawset(L,-3); break; case SWIG_LUA_STRING: diff --git a/Lib/lua/luatypemaps.swg b/Lib/lua/luatypemaps.swg index c86b40d74..5d98e6107 100644 --- a/Lib/lua/luatypemaps.swg +++ b/Lib/lua/luatypemaps.swg @@ -122,14 +122,14 @@ SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { %{$1 = (lua_tostring(L, $input))[0];%} %typemap(out) char -%{ lua_pushfstring(L,"%c",$1); SWIG_arg++;%} +%{ lua_pushlstring(L, &$1, 1); SWIG_arg++;%} // by const ref %typemap(in,checkfn="SWIG_lua_isnilstring",fragment="SWIG_lua_isnilstring") const char& (char temp) %{temp = (lua_tostring(L, $input))[0]; $1=&temp;%} %typemap(out) const char& -%{ lua_pushfstring(L,"%c",*$1); SWIG_arg++;%} +%{ lua_pushlstring(L, $1, 1); SWIG_arg++;%} // pointers and references // under SWIG rules, it is ok, to have a pass in a lua nil, diff --git a/Lib/ocaml/director.swg b/Lib/ocaml/director.swg index fea0cada6..158cbfeec 100644 --- a/Lib/ocaml/director.swg +++ b/Lib/ocaml/director.swg @@ -72,7 +72,7 @@ namespace Swig { mutable bool swig_disown_flag; public: - /* wrap a ocaml object, optionally taking ownership */ + /* wrap a ocaml object. */ Director(CAML_VALUE self) : swig_self(self), swig_disown_flag(false) { register_global_root(&swig_self); } diff --git a/Lib/ocaml/ocamldec.swg b/Lib/ocaml/ocamldec.swg index e6b8939fb..96e1cd2ce 100644 --- a/Lib/ocaml/ocamldec.swg +++ b/Lib/ocaml/ocamldec.swg @@ -130,7 +130,7 @@ CAMLextern int64 Int64_val(caml_value_t v); SWIGSTATIC CAML_VALUE caml_array_new( int n ); SWIGSTATIC void caml_array_set( CAML_VALUE arr, int n, CAML_VALUE item ); SWIGSTATIC CAML_VALUE caml_array_nth( CAML_VALUE arr, int n ); - SWIGSTATIC int caml_array_length( CAML_VALUE arr ); + SWIGSTATIC int caml_array_len( CAML_VALUE arr ); SWIGSTATIC CAML_VALUE caml_val_char( char c ); SWIGSTATIC CAML_VALUE caml_val_uchar( unsigned char c ); @@ -165,5 +165,3 @@ CAMLextern int64 Int64_val(caml_value_t v); #ifdef __cplusplus } #endif - -/* mzschemedec.swg ends here */ diff --git a/Lib/octave/director.swg b/Lib/octave/director.swg index c399a6a89..e80877ef6 100644 --- a/Lib/octave/director.swg +++ b/Lib/octave/director.swg @@ -1,7 +1,7 @@ /* ----------------------------------------------------------------------------- * director.swg * - * This file contains support for director classes so that D proxy + * This file contains support for director classes so that Octave proxy * methods can be called from C++. * ----------------------------------------------------------------------------- */ diff --git a/Lib/octave/octcontainer.swg b/Lib/octave/octcontainer.swg index 723256ca0..0211b33c6 100644 --- a/Lib/octave/octcontainer.swg +++ b/Lib/octave/octcontainer.swg @@ -12,6 +12,7 @@ * ----------------------------------------------------------------------------- */ %{ +#include #include %} diff --git a/Lib/octave/octrun.swg b/Lib/octave/octrun.swg index b5c3e5d86..ddfd48939 100644 --- a/Lib/octave/octrun.swg +++ b/Lib/octave/octrun.swg @@ -868,6 +868,17 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } #if defined (HAVE_HDF5) +# if SWIG_OCTAVE_PREREQ(4,0,0) + virtual bool + save_hdf5 (octave_hdf5_id loc_id, const char *name, bool save_as_floats) { + return true; + } + + virtual bool + load_hdf5 (octave_hdf5_id loc_id, const char *name, bool have_h5giterate_bug) { + return true; + } +# else virtual bool save_hdf5 (hid_t loc_id, const char *name, bool save_as_floats) { return true; @@ -877,6 +888,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); load_hdf5 (hid_t loc_id, const char *name, bool have_h5giterate_bug) { return true; } +# endif #endif virtual octave_value convert_to_str(bool pad = false, bool force = false, char type = '"') const { @@ -969,7 +981,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return octave_value(); } +#if SWIG_OCTAVE_PREREQ(4,0,0) + void print(std::ostream &os, bool pr_as_read_syntax = false) { +#else void print(std::ostream &os, bool pr_as_read_syntax = false) const { +#endif if (is_string()) { os << string_value(); return; @@ -1089,6 +1105,15 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); { return ptr->load_binary(is, swap, fmt); } #if defined (HAVE_HDF5) +# if SWIG_OCTAVE_PREREQ(4,0,0) + virtual bool + save_hdf5 (octave_hdf5_id loc_id, const char *name, bool save_as_floats) + { return ptr->save_hdf5(loc_id, name, save_as_floats); } + + virtual bool + load_hdf5 (octave_hdf5_id loc_id, const char *name, bool have_h5giterate_bug) + { return ptr->load_hdf5(loc_id, name, have_h5giterate_bug); } +# else virtual bool save_hdf5 (hid_t loc_id, const char *name, bool save_as_floats) { return ptr->save_hdf5(loc_id, name, save_as_floats); } @@ -1096,6 +1121,7 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); virtual bool load_hdf5 (hid_t loc_id, const char *name, bool have_h5giterate_bug) { return ptr->load_hdf5(loc_id, name, have_h5giterate_bug); } +# endif #endif virtual octave_value convert_to_str(bool pad = false, bool force = false, char type = '"') const @@ -1104,14 +1130,22 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); virtual octave_value convert_to_str_internal(bool pad, bool force, char type) const { return ptr->convert_to_str_internal(pad, force, type); } +#if SWIG_OCTAVE_PREREQ(4,0,0) + void print(std::ostream &os, bool pr_as_read_syntax = false) +#else void print(std::ostream &os, bool pr_as_read_syntax = false) const +#endif { return ptr->print(os, pr_as_read_syntax); } private: +#if !SWIG_OCTAVE_PREREQ(4,0,0) DECLARE_OCTAVE_ALLOCATOR; +#endif DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA; }; +#if !SWIG_OCTAVE_PREREQ(4,0,0) DEFINE_OCTAVE_ALLOCATOR(octave_swig_ref); +#endif DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_swig_ref, "swig_ref", "swig_ref"); class octave_swig_packed:public octave_base_value { @@ -1143,7 +1177,11 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); return true; } +#if SWIG_OCTAVE_PREREQ(4,0,0) + void print(std::ostream &os, bool pr_as_read_syntax = false) { +#else void print(std::ostream &os, bool pr_as_read_syntax = false) const { +#endif indent(os); os << "swig packed type: name = " << (type ? type->name : std::string()) << ", len = " << buf.size(); newline(os); } @@ -1167,6 +1205,17 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); } #if defined (HAVE_HDF5) +# if SWIG_OCTAVE_PREREQ(4,0,0) + virtual bool + save_hdf5 (octave_hdf5_id loc_id, const char *name, bool save_as_floats) { + return true; + } + + virtual bool + load_hdf5 (octave_hdf5_id loc_id, const char *name, bool have_h5giterate_bug) { + return true; + } +# else virtual bool save_hdf5 (hid_t loc_id, const char *name, bool save_as_floats) { return true; @@ -1176,13 +1225,18 @@ SWIGRUNTIME void swig_acquire_ownership_obj(void *vptr, int own); load_hdf5 (hid_t loc_id, const char *name, bool have_h5giterate_bug) { return true; } +# endif #endif private: +#if !SWIG_OCTAVE_PREREQ(4,0,0) DECLARE_OCTAVE_ALLOCATOR; +#endif DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA; }; +#if !SWIG_OCTAVE_PREREQ(4,0,0) DEFINE_OCTAVE_ALLOCATOR(octave_swig_packed); +#endif DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_swig_packed, "swig_packed", "swig_packed"); SWIGRUNTIME octave_value_list octave_set_immutable(const octave_value_list &args, int nargout) { diff --git a/Lib/perl5/director.swg b/Lib/perl5/director.swg index 714a87877..f0a6614fc 100644 --- a/Lib/perl5/director.swg +++ b/Lib/perl5/director.swg @@ -227,13 +227,12 @@ namespace Swig { } public: - /* wrap a Perl object, optionally taking ownership */ + /* wrap a Perl object. */ Director(SV *pkg) : swig_disown_flag(false) { STRLEN len; char *str = SvPV(pkg, len); swig_class = std::string(str, len); swig_self = newRV_inc((SV *)newHV()); - swig_incref(); } /* discard our reference at destruction */ diff --git a/Lib/perl5/noembed.h b/Lib/perl5/noembed.h index 936d50ba6..4e30f1117 100644 --- a/Lib/perl5/noembed.h +++ b/Lib/perl5/noembed.h @@ -103,6 +103,9 @@ #ifdef stat #undef stat #endif +#ifdef seed + #undef seed +#endif #ifdef bool /* Leave if macro is from C99 stdbool.h */ diff --git a/Lib/php/director.swg b/Lib/php/director.swg index b28df607c..d9dccdf6f 100644 --- a/Lib/php/director.swg +++ b/Lib/php/director.swg @@ -15,15 +15,6 @@ #include #include -/* - Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the - 'Swig' namespace. This could be useful for multi-modules projects. -*/ -#ifdef SWIG_DIRECTOR_STATIC -/* Force anonymous (static) namespace */ -#define Swig -#endif - namespace Swig { /* memory handler */ diff --git a/Lib/python/builtin.swg b/Lib/python/builtin.swg index 28c557a21..1d892375c 100644 --- a/Lib/python/builtin.swg +++ b/Lib/python/builtin.swg @@ -9,6 +9,7 @@ SWIGINTERN void \ wrapper##_closure(PyObject *a) { \ SwigPyObject *sobj; \ sobj = (SwigPyObject *)a; \ + Py_XDECREF(sobj->dict); \ if (sobj->own) { \ PyObject *o = wrapper(a, NULL); \ Py_XDECREF(o); \ diff --git a/Lib/python/director.swg b/Lib/python/director.swg index 90c58c107..4bdc94dc2 100644 --- a/Lib/python/director.swg +++ b/Lib/python/director.swg @@ -40,16 +40,6 @@ #endif -/* - Use -DSWIG_DIRECTOR_STATIC if you prefer to avoid the use of the - 'Swig' namespace. This could be useful for multi-modules projects. -*/ -#ifdef SWIG_DIRECTOR_STATIC -/* Force anonymous (static) namespace */ -#define Swig -#endif - - /* Use -DSWIG_DIRECTOR_NORTTI if you prefer to avoid the use of the native C++ RTTI and dynamic_cast<>. But be aware that directors @@ -338,9 +328,8 @@ namespace Swig { } public: - /* wrap a python object, optionally taking ownership */ + /* wrap a python object. */ Director(PyObject *self) : swig_self(self), swig_disown_flag(false) { - swig_incref(); } /* discard our reference at destruction */ diff --git a/Lib/python/pyabc.i b/Lib/python/pyabc.i index 3da06b5a9..12ce65985 100644 --- a/Lib/python/pyabc.i +++ b/Lib/python/pyabc.i @@ -1,7 +1,7 @@ %define %pythonabc(Type, Abc) %feature("python:abc", #Abc) Type; %enddef -%pythoncode {import collections}; +%pythoncode %{import collections%} %pythonabc(std::vector, collections.MutableSequence); %pythonabc(std::list, collections.MutableSequence); %pythonabc(std::map, collections.MutableMapping); diff --git a/Lib/python/pycontainer.swg b/Lib/python/pycontainer.swg index e5543cd6b..7168862f5 100644 --- a/Lib/python/pycontainer.swg +++ b/Lib/python/pycontainer.swg @@ -710,8 +710,8 @@ namespace swig #if defined(SWIGPYTHON_BUILTIN) %feature("python:slot", "tp_iter", functype="getiterfunc") iterator; #else - %pythoncode {def __iter__(self): - return self.iterator()} + %pythoncode %{def __iter__(self): + return self.iterator()%} #endif } diff --git a/Lib/python/pyinit.swg b/Lib/python/pyinit.swg index 47d3d9700..e71c72b27 100644 --- a/Lib/python/pyinit.swg +++ b/Lib/python/pyinit.swg @@ -275,7 +275,9 @@ SWIG_Python_FixMethods(PyMethodDef *methods, size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; - if (c && (c = strstr(c, "swig_ptr: "))) { + if (!c) continue; + c = strstr(c, "swig_ptr: "); + if (c) { int j; swig_const_info *ci = 0; const char *name = c + 10; diff --git a/Lib/python/pyiterators.swg b/Lib/python/pyiterators.swg index 110c431fe..8fbb31226 100644 --- a/Lib/python/pyiterators.swg +++ b/Lib/python/pyiterators.swg @@ -344,8 +344,8 @@ namespace swig %feature("python:slot", "tp_iternext", functype="iternextfunc") SwigPyIterator::__next__; #else %extend SwigPyIterator { - %pythoncode {def __iter__(self): - return self} + %pythoncode %{def __iter__(self): + return self%} } #endif diff --git a/Lib/python/pyrun.swg b/Lib/python/pyrun.swg index a713486d1..5eedca483 100644 --- a/Lib/python/pyrun.swg +++ b/Lib/python/pyrun.swg @@ -381,6 +381,23 @@ typedef struct { #endif } SwigPyObject; + +#ifdef SWIGPYTHON_BUILTIN + +SWIGRUNTIME PyObject * +SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + + if (!sobj->dict) + sobj->dict = PyDict_New(); + + Py_INCREF(sobj->dict); + return sobj->dict; +} + +#endif + SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { @@ -651,7 +668,7 @@ swigobject_methods[] = { static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"acquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, @@ -1420,18 +1437,21 @@ SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int f newobj = (SwigPyObject *) newobj->next; newobj->next = next_self; newobj = (SwigPyObject *)next_self; +#ifdef SWIGPYTHON_BUILTIN + newobj->dict = 0; +#endif } } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); +#ifdef SWIGPYTHON_BUILTIN + newobj->dict = 0; +#endif } if (newobj) { newobj->ptr = ptr; newobj->ty = type; newobj->own = own; newobj->next = 0; -#ifdef SWIGPYTHON_BUILTIN - newobj->dict = 0; -#endif return (PyObject*) newobj; } return SWIG_Py_Void(); diff --git a/Lib/python/std_map.i b/Lib/python/std_map.i index 58902bca4..454e821a5 100644 --- a/Lib/python/std_map.i +++ b/Lib/python/std_map.i @@ -176,14 +176,14 @@ #else %extend { - %pythoncode {def __iter__(self): - return self.key_iterator()} - %pythoncode {def iterkeys(self): - return self.key_iterator()} - %pythoncode {def itervalues(self): - return self.value_iterator()} - %pythoncode {def iteritems(self): - return self.iterator()} + %pythoncode %{def __iter__(self): + return self.key_iterator()%} + %pythoncode %{def iterkeys(self): + return self.key_iterator()%} + %pythoncode %{def itervalues(self): + return self.value_iterator()%} + %pythoncode %{def iteritems(self): + return self.iterator()%} } #endif diff --git a/Lib/python/std_pair.i b/Lib/python/std_pair.i index 73d47e198..5694e7e09 100644 --- a/Lib/python/std_pair.i +++ b/Lib/python/std_pair.i @@ -176,7 +176,7 @@ SwigPython_std_pair_setitem (PyObject *a, Py_ssize_t b, PyObject *c) %define %swig_pair_methods(pair...) #if !defined(SWIGPYTHON_BUILTIN) %extend { -%pythoncode {def __len__(self): +%pythoncode %{def __len__(self): return 2 def __repr__(self): return str((self.first, self.second)) @@ -189,7 +189,7 @@ def __setitem__(self, index, val): if not (index % 2): self.first = val else: - self.second = val} + self.second = val%} } #endif %enddef diff --git a/Lib/python/std_unordered_map.i b/Lib/python/std_unordered_map.i index 737468234..e58a4e927 100644 --- a/Lib/python/std_unordered_map.i +++ b/Lib/python/std_unordered_map.i @@ -231,14 +231,14 @@ return swig::make_output_value_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF); } - %pythoncode {def __iter__(self): - return self.key_iterator()} - %pythoncode {def iterkeys(self): - return self.key_iterator()} - %pythoncode {def itervalues(self): - return self.value_iterator()} - %pythoncode {def iteritems(self): - return self.iterator()} + %pythoncode %{def __iter__(self): + return self.key_iterator()%} + %pythoncode %{def iterkeys(self): + return self.key_iterator()%} + %pythoncode %{def itervalues(self): + return self.value_iterator()%} + %pythoncode %{def iteritems(self): + return self.iterator()%} } %enddef diff --git a/Lib/r/r.swg b/Lib/r/r.swg index 126611d61..a6014965e 100644 --- a/Lib/r/r.swg +++ b/Lib/r/r.swg @@ -264,8 +264,8 @@ x setAs('ExternalReference', 'character', function(from) {if (!is.null(from$"__str__")) from$"__str__"()}) -setMethod('print', 'ExternalReference', -function(x) {print(as(x, "character"))}) +suppressWarnings(setMethod('print', 'ExternalReference', +function(x) {print(as(x, "character"))})) %} diff --git a/Lib/r/rkw.swg b/Lib/r/rkw.swg index 2c181faa0..074d7dfd9 100644 --- a/Lib/r/rkw.swg +++ b/Lib/r/rkw.swg @@ -3,6 +3,7 @@ */ #define RKW(x) %keywordwarn("'" `x` "' is a R keyword, renaming to '_" `x`"'", rename="_%s") `x` +#define RSWIGKW(x) %keywordwarn("'" `x` "' is a SWIG R reserved parameter name, renaming to '_" `x`"'", rename="_%s") `x` /* Warnings for R reserved words taken from @@ -29,4 +30,7 @@ RKW(NA_real_); RKW(NA_complex_); RKW(NA_character_); +RSWIGKW(self); + #undef RKW +#undef RSWIGKW diff --git a/Lib/r/srun.swg b/Lib/r/srun.swg index 71a508d49..2045ab94e 100644 --- a/Lib/r/srun.swg +++ b/Lib/r/srun.swg @@ -62,7 +62,7 @@ function(className, ..., append = TRUE) if(!isGeneric("copyToC")) setGeneric("copyToC", - function(value, obj = RSWIG_createNewRef(class(value))) + function(value, obj = SWIG_createNewRef(class(value))) standardGeneric("copyToC" )) @@ -147,4 +147,4 @@ function(fun, userData = NULL) } -####################################################################### \ No newline at end of file +####################################################################### diff --git a/Lib/ruby/director.swg b/Lib/ruby/director.swg index c2c4150e6..395dccc17 100644 --- a/Lib/ruby/director.swg +++ b/Lib/ruby/director.swg @@ -278,7 +278,7 @@ namespace Swig { mutable bool swig_disown_flag; public: - /* wrap a Ruby object, optionally taking ownership */ + /* wrap a Ruby object. */ Director(VALUE self) : swig_self(self), swig_disown_flag(false) { } diff --git a/Lib/scilab/scichar.swg b/Lib/scilab/scichar.swg index 509a40c18..5edbf5b76 100644 --- a/Lib/scilab/scichar.swg +++ b/Lib/scilab/scichar.swg @@ -14,12 +14,9 @@ SWIGINTERN int SWIG_SciString_AsChar(void *pvApiCtx, int iVar, char *pcValue, char *fname) { SciErr sciErr; - int iType = 0; - int iRows = 0; - int iCols = 0; int *piAddrVar = NULL; - char *pstStrings = NULL; - int piLength = 0; + char *pstValue = NULL; + int iRet; sciErr = getVarAddressFromPosition(pvApiCtx, iVar, &piAddrVar); if (sciErr.iErr) { @@ -27,30 +24,22 @@ SWIG_SciString_AsChar(void *pvApiCtx, int iVar, char *pcValue, char *fname) { return SWIG_ERROR; } - sciErr = getVarType(pvApiCtx, piAddrVar, &iType); - if (sciErr.iErr) { - printError(&sciErr, 0); - return SWIG_ERROR; + if (isStringType(pvApiCtx, piAddrVar) == 0) + { + Scierror(SCILAB_API_ARGUMENT_ERROR, _("%s: Wrong type for input argument #%d: A single string expected.\n"), fname, iVar); + return SWIG_TypeError; } - if (iType != sci_strings) { - Scierror(SCILAB_API_ARGUMENT_ERROR, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname, iVar); + + iRet = getAllocatedSingleString(pvApiCtx, piAddrVar, &pstValue); + if (iRet) { return SWIG_ERROR; } - pstStrings = (char *)malloc(sizeof(char)); - sciErr = getMatrixOfString(pvApiCtx, piAddrVar, &iRows, &iCols, &piLength, (char **)&pstStrings); - if (sciErr.iErr) { - printError(&sciErr, 0); - return SWIG_ERROR; + if (pcValue != NULL) { + *pcValue = pstValue[0]; } - if (iRows * iCols != 1) { - Scierror(SCILAB_API_ARGUMENT_ERROR, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname, iVar); - return SWIG_ERROR; - } - *pcValue = pstStrings[0]; - - free(pstStrings); + freeAllocatedSingleString(pstValue); return SWIG_OK; } } @@ -103,8 +92,7 @@ SWIG_SciString_AsCharPtr(void *pvApiCtx, int iVar, char *pcValue, int iLength, c strncpy(pcValue, pcTmpValue, iLength); } - free(pcTmpValue); - + freeAllocatedSingleString(pcTmpValue); return SWIG_OK; } } @@ -117,8 +105,10 @@ SWIGINTERN int SWIG_SciString_AsCharPtrAndSize(void *pvApiCtx, int iVar, char **pcValue, size_t *piLength, int *alloc, char *fname) { SciErr sciErr; int *piAddrVar = NULL; - int iRet; - char *pstStrings = NULL; + char *pstString = NULL; + int iRows = 0; + int iCols = 0; + int iLen = 0; sciErr = getVarAddressFromPosition(pvApiCtx, iVar, &piAddrVar); if (sciErr.iErr) { @@ -126,14 +116,31 @@ SWIG_SciString_AsCharPtrAndSize(void *pvApiCtx, int iVar, char **pcValue, size_t return SWIG_ERROR; } - iRet = getAllocatedSingleString(pvApiCtx, piAddrVar, &pstStrings); - if (iRet) { - return SWIG_ERROR; + if (isScalar(pvApiCtx, piAddrVar) == 0 || isStringType(pvApiCtx, piAddrVar) == 0) + { + Scierror(SCILAB_API_ARGUMENT_ERROR, _("%s: Wrong type for input argument #%d: A single string expected.\n"), fname, iVar); + return SWIG_TypeError; + } + + sciErr = getMatrixOfString(pvApiCtx, piAddrVar, &iRows, &iCols, &iLen, NULL); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return SWIG_ERROR; + } + + pstString = %new_array(iLen + 1, char); + + sciErr = getMatrixOfString(pvApiCtx, piAddrVar, &iRows, &iCols, &iLen, &pstString); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return SWIG_ERROR; } // TODO: return SWIG_ERROR if pcValue NULL (now returning SWIG_ERROR fails some typechecks) if (pcValue) { - *pcValue = pstStrings; + *pcValue = pstString; } if (alloc != NULL) { @@ -141,7 +148,7 @@ SWIG_SciString_AsCharPtrAndSize(void *pvApiCtx, int iVar, char **pcValue, size_t } if (piLength != NULL) { - *piLength = strlen(*pcValue); + *piLength = strlen(pstString); } return SWIG_OK; diff --git a/Lib/scilab/scirun.swg b/Lib/scilab/scirun.swg index 081012fe9..71641e074 100644 --- a/Lib/scilab/scirun.swg +++ b/Lib/scilab/scirun.swg @@ -66,11 +66,13 @@ static void SWIG_Scilab_SetApiContext(void *apiCtx) { #if SWIG_SCILAB_VERSION >= 540 #define SWIG_CheckInputArgument(pvApiCtx, minInputArgument, maxInputArgument) CheckInputArgument(pvApiCtx, minInputArgument, maxInputArgument) +#define SWIG_CheckInputArgumentAtLeast(pvApiCtx, minInputArgument) CheckInputArgumentAtLeast(pvApiCtx, minInputArgument) #define SWIG_CheckOutputArgument(pvApiCtx, minOutputArgument, maxOutputArgument) CheckOutputArgument(pvApiCtx, minOutputArgument, maxOutputArgument) #define SWIG_NbInputArgument(pvApiCtx) nbInputArgument(pvApiCtx) #define SWIG_AssignOutputArgument(pvApiCtx, outputArgumentPos, argumentPos) AssignOutputVariable(pvApiCtx, outputArgumentPos) = argumentPos #else #define SWIG_CheckInputArgument(pvApiCtx, minInputArgument, maxInputArgument) CheckRhs(minInputArgument, maxInputArgument) +#define SWIG_CheckInputArgumentAtLeast(pvApiCtx, minInputArgument) CheckRhs(minInputArgument, 256) #define SWIG_CheckOutputArgument(pvApiCtx, minOutputArgument, maxOutputArgument) CheckLhs(minOutputArgument, maxOutputArgument) #define SWIG_NbInputArgument(pvApiCtx) Rhs #define SWIG_AssignOutputArgument(pvApiCtx, outputArgumentPos, argumentPos) LhsVar(outputArgumentPos) = argumentPos @@ -148,7 +150,8 @@ SWIGRUNTIME int SWIG_Scilab_ConvertPacked(void *pvApiCtx, int iVar, void *ptr, int sz, swig_type_info *ty, char *fname) { swig_cast_info *tc; int *piAddrVar = NULL; - char *pstStrings = NULL; + char *pstString = NULL; + char *pstStringPtr = NULL; SciErr sciErr; sciErr = getVarAddressFromPosition(pvApiCtx, iVar, &piAddrVar); @@ -157,27 +160,33 @@ SWIG_Scilab_ConvertPacked(void *pvApiCtx, int iVar, void *ptr, int sz, swig_type return SWIG_ERROR; } - if (getAllocatedSingleString(pvApiCtx, piAddrVar, &pstStrings)) { + if (getAllocatedSingleString(pvApiCtx, piAddrVar, &pstString)) { return SWIG_ERROR; } /* Pointer values must start with leading underscore */ - if (*pstStrings != '_') { + if (*pstString != '_') { + freeAllocatedSingleString(pstString); return SWIG_ERROR; } - pstStrings++; - pstStrings = (char*)SWIG_UnpackData(pstStrings, ptr, sz); + pstStringPtr = pstString; + pstStringPtr++; + pstStringPtr = (char*)SWIG_UnpackData(pstStringPtr, ptr, sz); if (ty) { - if (!pstStrings) { + if (!pstStringPtr) { + freeAllocatedSingleString(pstString); return SWIG_ERROR; } - tc = SWIG_TypeCheck(pstStrings, ty); + tc = SWIG_TypeCheck(pstStringPtr, ty); if (!tc) { + freeAllocatedSingleString(pstString); return SWIG_ERROR; } } + + freeAllocatedSingleString(pstString); return SWIG_OK; } diff --git a/Lib/swiglabels.swg b/Lib/swiglabels.swg index baa21a756..e73e63a57 100644 --- a/Lib/swiglabels.swg +++ b/Lib/swiglabels.swg @@ -110,3 +110,12 @@ #if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) # define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 #endif + +/* Intel's compiler complains if a variable which was never initialised is + * cast to void, which is a common idiom which we use to indicate that we + * are aware a variable isn't used. So we just silence that warning. + * See: https://github.com/swig/swig/issues/192 for more discussion. + */ +#ifdef __INTEL_COMPILER +# pragma warning disable 592 +#endif diff --git a/Makefile.in b/Makefile.in index 964c48a07..e8e08a994 100644 --- a/Makefile.in +++ b/Makefile.in @@ -409,7 +409,7 @@ clean-ccache: # DISTCLEAN - clean what configure built ##################################################################### -DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log libtool preinst-swig +DISTCLEAN-DEAD = config.status config.log config.cache swig.spec Makefile mkmf.log preinst-swig distclean-helper: distclean-test-suite distclean-examples distclean-tools distclean-dead @@ -570,8 +570,9 @@ dd = @PACKAGE_NAME@-@PACKAGE_VERSION@ srpm = @PACKAGE_NAME@-@PACKAGE_VERSION@ dist: - @echo "not implemented - use Tools/mkdist.py instead." - false + @echo "'make dist' not implemented - use Tools/mkdist.py instead - e.g.:" + @echo "Tools/mkdist.py @VERSION@ master" + @false srcrpm: rm -fr $(srpm) $(srpm).src.rpm diff --git a/README b/README index 5c85e6c3a..a02c56ea9 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.6 (in progress) +Version: 3.0.7 (in progress) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, diff --git a/RELEASENOTES b/RELEASENOTES index ff1c99821..bb1d82bb9 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,11 @@ and CHANGES files. Release Notes ============= +SWIG-3.0.6 summary: +- Stability and regression fixes. +- Fixed parsing of C++ corner cases. +- Language improvements and bug fixes for C#, Go, Java, Lua, Python, R. + SWIG-3.0.5 summary: - Added support for Scilab. - Important Python regression fix when wrapping C++ default arguments. @@ -358,7 +363,7 @@ SWIG-1.3.22 summary: exceptions into target language exceptions. - Improved enum support, mapping to built-in Java 1.5 enums and C# enums or the typesafe enum pattern for these two languages. -- Python - much better STL suppport and support for std::wstring, +- Python - much better STL support and support for std::wstring, wchar_t and FILE *. - Initial support for Modula3 and Allegro CL. - 64 bit TCL support. diff --git a/Source/CParse/cscanner.c b/Source/CParse/cscanner.c index 7dd63924b..a987c4fd2 100644 --- a/Source/CParse/cscanner.c +++ b/Source/CParse/cscanner.c @@ -632,7 +632,10 @@ int yylex(void) { */ - nexttok = Scanner_token(scan); + do { + nexttok = Scanner_token(scan); + } while (nexttok == SWIG_TOKEN_ENDLINE || nexttok == SWIG_TOKEN_COMMENT); + if (Scanner_isoperator(nexttok)) { /* One of the standard C/C++ symbolic operators */ Append(s,Scanner_text(scan)); @@ -703,6 +706,8 @@ int yylex(void) { Append(s," "); } Append(s,Scanner_text(scan)); + } else if (nexttok == SWIG_TOKEN_ENDLINE) { + } else if (nexttok == SWIG_TOKEN_COMMENT) { } else { Append(s,Scanner_text(scan)); needspace = 0; @@ -739,7 +744,7 @@ int yylex(void) { Setfile(cs,cparse_file); Scanner_push(scan,cs); Delete(cs); - return COPERATOR; + return CONVERSIONOPERATOR; } } if (termtoken) @@ -908,7 +913,7 @@ int yylex(void) { return (WARN); /* Note down the apparently unknown directive for error reporting. */ - cparse_unknown_directive = Swig_copy_string(yytext); + cparse_unknown_directive = NewString(yytext); } /* Have an unknown identifier, as a last step, we'll do a typedef lookup on it. */ diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 44af84923..c6e15bc32 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -27,7 +27,6 @@ to work, see Byacc man page: http://invisible-island.net/byacc/manpage/yacc.html #include "preprocessor.h" #include - /* We do this for portability */ #undef alloca #define alloca malloc @@ -52,7 +51,7 @@ static String *Classprefix = 0; static String *Namespaceprefix = 0; static int inclass = 0; static Node *currentOuterClass = 0; /* for nested classes */ -static char *last_cpptype = 0; +static const char *last_cpptype = 0; static int inherit_list = 0; static Parm *template_parameters = 0; static int extendmode = 0; @@ -466,6 +465,10 @@ static void add_symbols(Node *n) { if ((Cmp(Getattr(n,"storage"),"virtual") == 0) && (Cmp(Getattr(n,"value"),"0") == 0)) { only_csymbol = 0; } + if (Cmp(nodeType(n),"destructor") == 0) { + /* Needed for "unref" feature */ + only_csymbol = 0; + } } } else { Setattr(n,"access", "public"); @@ -794,14 +797,14 @@ static String *make_class_name(String *name) { /* Use typedef name as class name */ -static void add_typedef_name(Node *n, Node *decl, String *oldName, Symtab *cscope, String *scpname) { +static void add_typedef_name(Node *n, Node *declnode, String *oldName, Symtab *cscope, String *scpname) { String *class_rename = 0; - SwigType *decltype = Getattr(decl, "decl"); - if (!decltype || !Len(decltype)) { + SwigType *decl = Getattr(declnode, "decl"); + if (!decl || !Len(decl)) { String *cname; String *tdscopename; String *class_scope = Swig_symbol_qualifiedscopename(cscope); - String *name = Getattr(decl, "name"); + String *name = Getattr(declnode, "name"); cname = Copy(name); Setattr(n, "tdname", cname); tdscopename = class_scope ? NewStringf("%s::%s", class_scope, name) : Copy(name); @@ -812,7 +815,7 @@ static void add_typedef_name(Node *n, Node *decl, String *oldName, Symtab *cscop if (!Equal(scpname, tdscopename) && !Getattr(classes_typedefs, tdscopename)) { Setattr(classes_typedefs, tdscopename, n); } - Setattr(n, "decl", decltype); + Setattr(n, "decl", decl); Delete(class_scope); Delete(cname); Delete(tdscopename); @@ -835,7 +838,7 @@ static String *remove_block(Node *kw, const String *inputcode) { String *name = Getattr(kw,"name"); if (name && (Cmp(name,"noblock") == 0)) { char *cstr = Char(inputcode); - size_t len = Len(inputcode); + int len = Len(inputcode); if (len && cstr[0] == '{') { --len; ++cstr; if (len && cstr[len - 1] == '}') { --len; } @@ -1072,7 +1075,6 @@ static void update_nested_classes(Node *n) static Node *nested_forward_declaration(const char *storage, const char *kind, String *sname, String *name, Node *cpp_opt_declarators) { Node *nn = 0; - int warned = 0; if (sname) { /* Add forward declaration of the nested type */ @@ -1116,13 +1118,12 @@ static Node *nested_forward_declaration(const char *storage, const char *kind, S if (!currentOuterClass || !GetFlag(currentOuterClass, "nested")) { if (nn && Equal(nodeType(nn), "classforward")) { Node *n = nn; - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); - SWIG_WARN_NODE_END(n); - warned = 1; - } - - if (!warned) { + if (!GetFlag(n, "feature:ignore")) { + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(WARN_PARSE_NAMED_NESTED_CLASS, cparse_file, cparse_line,"Nested %s not currently supported (%s ignored)\n", kind, sname ? sname : name); + SWIG_WARN_NODE_END(n); + } + } else { Swig_warning(WARN_PARSE_UNNAMED_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", kind); } } @@ -1243,7 +1244,6 @@ static void default_arguments(Node *n) { Node *function = n; if (function) { - ParmList *varargs = Getattr(function,"feature:varargs"); if (varargs) { /* Handles the %varargs directive by looking for "feature:varargs" and @@ -1393,7 +1393,7 @@ static void mark_nodes_as_extend(Node *n) { %} %union { - char *id; + const char *id; List *bases; struct Define { String *val; @@ -1468,7 +1468,7 @@ static void mark_nodes_as_extend(Node *n) { %token NONID DSTAR DCNOT %token TEMPLATE %token OPERATOR -%token COPERATOR +%token CONVERSIONOPERATOR %token PARSETYPE PARSEPARM PARSEPARMS %token DOXYGENSTRING %token DOXYGENPOSTSTRING @@ -1513,7 +1513,7 @@ static void mark_nodes_as_extend(Node *n) { /* Misc */ %type identifier; %type initializer cpp_const exception_specification; -%type storage_class; +%type storage_class extern_string; %type parms ptail rawparms varargs_parms ; %type templateparameters templateparameterstail; %type

    parm valparm rawvalparms valparms valptail ; @@ -1527,7 +1527,7 @@ static void mark_nodes_as_extend(Node *n) { %type definetype def_args etype default_delete deleted_definition explicit_default; %type expr exprnum exprcompound valexpr; %type ename ; -%type template_decl; +%type less_valparms_greater; %type type_qualifier ; %type type_qualifier_raw; %type idstring idstringopt; @@ -1535,11 +1535,11 @@ static void mark_nodes_as_extend(Node *n) { %type pragma_arg; %type includetype; %type pointer primitive_type; -%type declarator direct_declarator notso_direct_declarator parameter_declarator typemap_parameter_declarator; +%type declarator direct_declarator notso_direct_declarator parameter_declarator plain_declarator; %type abstract_declarator direct_abstract_declarator ctor_end; %type typemap_type; -%type idcolon idcolontail idcolonnt idcolontailnt idtemplate stringbrace stringbracesemi; -%type string stringnum wstring; +%type idcolon idcolontail idcolonnt idcolontailnt idtemplate idtemplatetemplate stringbrace stringbracesemi; +%type string stringnum wstring; %type template_parms; %type cpp_end cpp_vend; %type rename_namewarn; @@ -1648,10 +1648,11 @@ declaration : swig_directive { $$ = $1; } This is nearly impossible to parse normally. We just let the first part generate a syntax error and then resynchronize on the - COPERATOR token---discarding the rest of the definition. Ugh. + CONVERSIONOPERATOR token---discarding the rest of the definition. Ugh. */ - | error COPERATOR { + + | error CONVERSIONOPERATOR { $$ = 0; skip_decl(); } @@ -1856,7 +1857,7 @@ echo_directive : ECHO HBLOCK { } | ECHO string { char temp[64]; - String *s = NewString($2); + String *s = $2; Replace(s,"$file",cparse_file, DOH_REPLACE_ANY); sprintf(temp,"%d", cparse_line); Replace(s,"$line",temp,DOH_REPLACE_ANY); @@ -1961,7 +1962,7 @@ fragment_directive: FRAGMENT LPAREN fname COMMA kwargs RPAREN HBLOCK { include_directive: includetype options string BEGINFILE { $1.filename = Copy(cparse_file); $1.line = cparse_line; - scanner_set_location(NewString($3),1); + scanner_set_location($3,1); if ($2) { String *maininput = Getattr($2, "maininput"); if (maininput) @@ -2216,7 +2217,7 @@ pragma_directive : PRAGMA pragma_lang identifier EQUAL pragma_arg { } ; -pragma_arg : string { $$ = NewString($1); } +pragma_arg : string { $$ = $1; } | HBLOCK { $$ = $1; } ; @@ -2368,7 +2369,7 @@ feature_directive : FEATURE LPAREN idstring RPAREN declarator cpp_const stringbr scanner_clear_rename(); } | FEATURE LPAREN idstring COMMA stringnum RPAREN declarator cpp_const SEMI { - String *val = Len($5) ? NewString($5) : 0; + String *val = Len($5) ? $5 : 0; new_feature($3, val, 0, $7.id, $7.type, $7.parms, $8.qualifier); $$ = 0; scanner_clear_rename(); @@ -2380,7 +2381,7 @@ feature_directive : FEATURE LPAREN idstring RPAREN declarator cpp_const stringbr scanner_clear_rename(); } | FEATURE LPAREN idstring COMMA stringnum featattr RPAREN declarator cpp_const SEMI { - String *val = Len($5) ? NewString($5) : 0; + String *val = Len($5) ? $5 : 0; new_feature($3, val, $6, $8.id, $8.type, $8.parms, $9.qualifier); $$ = 0; scanner_clear_rename(); @@ -2394,7 +2395,7 @@ feature_directive : FEATURE LPAREN idstring RPAREN declarator cpp_const stringbr scanner_clear_rename(); } | FEATURE LPAREN idstring COMMA stringnum RPAREN SEMI { - String *val = Len($5) ? NewString($5) : 0; + String *val = Len($5) ? $5 : 0; new_feature($3, val, 0, 0, 0, 0, 0); $$ = 0; scanner_clear_rename(); @@ -2406,7 +2407,7 @@ feature_directive : FEATURE LPAREN idstring RPAREN declarator cpp_const stringbr scanner_clear_rename(); } | FEATURE LPAREN idstring COMMA stringnum featattr RPAREN SEMI { - String *val = Len($5) ? NewString($5) : 0; + String *val = Len($5) ? $5 : 0; new_feature($3, val, $6, 0, 0, 0, 0); $$ = 0; scanner_clear_rename(); @@ -2581,7 +2582,7 @@ tm_tail : COMMA typemap_parm tm_tail { | empty { $$ = 0;} ; -typemap_parm : type typemap_parameter_declarator { +typemap_parm : type plain_declarator { Parm *parm; SwigType_push($1,$2.type); $$ = new_node("typemapitem"); @@ -2783,7 +2784,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va String *symname = Swig_name_make(templnode,0,$3,0,0); */ - String *symname = $3; + String *symname = NewString($3); Swig_cparse_template_expand(templnode,symname,temparms,tscope); Setattr(templnode,"sym:name",symname); } else { @@ -2918,7 +2919,6 @@ warn_directive : WARN string { } ; - /* ====================================================================== * C Parsing * ====================================================================== */ @@ -2966,10 +2966,11 @@ c_declaration : c_decl { Swig_warning(WARN_CPP11_LAMBDA, cparse_file, cparse_line, "Lambda expressions and closures are not fully supported yet.\n"); SWIG_WARN_NODE_END($$); } - | USING idcolon EQUAL { - skip_decl(); + | USING idcolon EQUAL type plain_declarator SEMI { $$ = new_node("using"); Setattr($$,"name",$2); + SwigType_push($4,$5.type); + Setattr($$,"uname",$4); add_symbols($$); SWIG_WARN_NODE_BEGIN($$); Swig_warning(WARN_CPP11_ALIAS_DECLARATION, cparse_file, cparse_line, "The 'using' keyword in type aliasing is not fully supported yet.\n"); @@ -2977,15 +2978,17 @@ c_declaration : c_decl { $$ = 0; /* TODO - ignored for now */ } - | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL identifier { - skip_decl(); + | TEMPLATE LESSTHAN template_parms GREATERTHAN USING idcolon EQUAL type plain_declarator SEMI { $$ = new_node("using"); - Setattr($$,"uname",$8); Setattr($$,"name",$6); + SwigType_push($8,$9.type); + Setattr($$,"uname",$8); add_symbols($$); SWIG_WARN_NODE_BEGIN($$); Swig_warning(WARN_CPP11_ALIAS_TEMPLATE, cparse_file, cparse_line, "The 'using' keyword in template aliasing is not fully supported yet.\n"); SWIG_WARN_NODE_END($$); + + $$ = 0; /* TODO - ignored for now */ } ; @@ -3186,7 +3189,9 @@ initializer : def_args { cpp_alternate_rettype : primitive_type { $$ = $1; } | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } +/* | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } +*/ | TYPE_RAW { $$ = $1; } | idcolon { $$ = $1; } | decltype { $$ = $1; } @@ -4617,7 +4622,7 @@ cpp_destructor_decl : NOT idtemplate LPAREN parms RPAREN cpp_end { /* C++ type conversion operator */ -cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAREN cpp_vend { +cpp_conversion_operator : storage_class CONVERSIONOPERATOR type pointer LPAREN parms RPAREN cpp_vend { $$ = new_node("cdecl"); Setattr($$,"type",$3); Setattr($$,"name",$2); @@ -4632,7 +4637,7 @@ cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAR Setattr($$,"conversion_operator","1"); add_symbols($$); } - | storage_class COPERATOR type AND LPAREN parms RPAREN cpp_vend { + | storage_class CONVERSIONOPERATOR type AND LPAREN parms RPAREN cpp_vend { SwigType *decl; $$ = new_node("cdecl"); Setattr($$,"type",$3); @@ -4649,7 +4654,7 @@ cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAR Setattr($$,"conversion_operator","1"); add_symbols($$); } - | storage_class COPERATOR type LAND LPAREN parms RPAREN cpp_vend { + | storage_class CONVERSIONOPERATOR type LAND LPAREN parms RPAREN cpp_vend { SwigType *decl; $$ = new_node("cdecl"); Setattr($$,"type",$3); @@ -4667,7 +4672,7 @@ cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAR add_symbols($$); } - | storage_class COPERATOR type pointer AND LPAREN parms RPAREN cpp_vend { + | storage_class CONVERSIONOPERATOR type pointer AND LPAREN parms RPAREN cpp_vend { SwigType *decl; $$ = new_node("cdecl"); Setattr($$,"type",$3); @@ -4686,7 +4691,7 @@ cpp_conversion_operator : storage_class COPERATOR type pointer LPAREN parms RPAR add_symbols($$); } - | storage_class COPERATOR type LPAREN parms RPAREN cpp_vend { + | storage_class CONVERSIONOPERATOR type LPAREN parms RPAREN cpp_vend { String *t = NewStringEmpty(); $$ = new_node("cdecl"); Setattr($$,"type",$3); @@ -4823,7 +4828,9 @@ anon_bitfield_type : primitive_type { $$ = $1; } | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } +/* | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } +*/ | TYPE_RAW { $$ = $1; } | idcolon { @@ -4834,28 +4841,22 @@ anon_bitfield_type : primitive_type { $$ = $1; /* ====================================================================== * PRIMITIVES * ====================================================================== */ - -storage_class : EXTERN { $$ = "extern"; } - | EXTERN string { - if (strcmp($2,"C") == 0) { +extern_string : EXTERN string { + if (Strcmp($2,"C") == 0) { $$ = "externc"; - } else if (strcmp($2,"C++") == 0) { + } else if (Strcmp($2,"C++") == 0) { $$ = "extern"; } else { Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); $$ = 0; } } - | EXTERN string THREAD_LOCAL { - if (strcmp($2,"C") == 0) { - $$ = "externc thread_local"; - } else if (strcmp($2,"C++") == 0) { - $$ = "extern thread_local"; - } else { - Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", $2); - $$ = 0; - } - } + ; + +storage_class : EXTERN { $$ = "extern"; } + | extern_string { $$ = $1; } + | extern_string THREAD_LOCAL { $$ = "thread_local"; } + | extern_string TYPEDEF { $$ = "typedef"; } | STATIC { $$ = "static"; } | TYPEDEF { $$ = "typedef"; } | VIRTUAL { $$ = "virtual"; } @@ -4920,6 +4921,7 @@ parm : rawtype parameter_declarator { Setattr($$,"value",$2.defarg); } } + | TEMPLATE LESSTHAN cpptype GREATERTHAN cpptype idcolon def_args { $$ = NewParmWithoutFileLineInfo(NewStringf("template %s %s", $5,$6), 0); previousNode = currentNode; @@ -5084,7 +5086,7 @@ parameter_declarator : declarator def_args { } ; -typemap_parameter_declarator : declarator { +plain_declarator : declarator { $$ = $1; if (SwigType_isfunction($1.type)) { Delete(SwigType_pop_function($1.type)); @@ -5794,7 +5796,9 @@ type_right : primitive_type { $$ = $1; } | TYPE_BOOL { $$ = $1; } | TYPE_VOID { $$ = $1; } +/* | TYPE_TYPEDEF template_decl { $$ = NewStringf("%s%s",$1,$2); } +*/ | c_enum_key idcolon { $$ = NewStringf("enum %s", $2); } | TYPE_RAW { $$ = $1; } @@ -5977,17 +5981,6 @@ definetype : { /* scanner_check_typedef(); */ } expr { | default_delete { $$ = $1; } -/* - | string { - $$.val = NewString($1); - $$.rawval = NewStringf("\"%(escape)s\"",$$.val); - $$.type = T_STRING; - $$.bitfield = 0; - $$.throws = 0; - $$.throwf = 0; - $$.nexcept = 0; - } -*/ ; default_delete : deleted_definition { @@ -6123,7 +6116,7 @@ expr : valexpr { $$ = $1; } valexpr : exprnum { $$ = $1; } | string { - $$.val = NewString($1); + $$.val = $1; $$.type = T_STRING; } | SIZEOF LPAREN type parameter_declarator RPAREN { @@ -6138,7 +6131,7 @@ valexpr : exprnum { $$ = $1; } } | exprcompound { $$ = $1; } | wstring { - $$.val = NewString($1); + $$.val = $1; $$.rawval = NewStringf("L\"%s\"", $$.val); $$.type = T_WSTRING; } @@ -6633,14 +6626,13 @@ mem_initializer : idcolon LPAREN { } ; -template_decl : LESSTHAN valparms GREATERTHAN { +less_valparms_greater : LESSTHAN valparms GREATERTHAN { String *s = NewStringEmpty(); SwigType_add_template(s,$2); $$ = Char(s); scanner_last_id(1); - } - | empty { $$ = (char*)""; } - ; + } + ; /* Identifiers including the C++11 identifiers with special meaning */ identifier : ID { $$ = $1; } @@ -6649,8 +6641,8 @@ identifier : ID { $$ = $1; } ; idstring : identifier { $$ = $1; } - | default_delete { $$ = $1.val; } - | string { $$ = $1; } + | default_delete { $$ = Char($1.val); } + | string { $$ = Char($1); } ; idstringopt : idstring { $$ = $1; } @@ -6662,35 +6654,38 @@ idcolon : idtemplate idcolontail { if (!$$) $$ = NewStringf("%s%s", $1,$2); Delete($2); } - | NONID DCOLON idtemplate idcolontail { + | NONID DCOLON idtemplatetemplate idcolontail { $$ = NewStringf("::%s%s",$3,$4); Delete($4); } | idtemplate { $$ = NewString($1); } - | NONID DCOLON idtemplate { + | NONID DCOLON idtemplatetemplate { $$ = NewStringf("::%s",$3); } | OPERATOR { - $$ = NewString($1); + $$ = NewStringf("%s", $1); + } + | OPERATOR less_valparms_greater { + $$ = NewStringf("%s%s", $1, $2); } | NONID DCOLON OPERATOR { $$ = NewStringf("::%s",$3); } ; -idcolontail : DCOLON idtemplate idcolontail { +idcolontail : DCOLON idtemplatetemplate idcolontail { $$ = NewStringf("::%s%s",$2,$3); Delete($3); } - | DCOLON idtemplate { + | DCOLON idtemplatetemplate { $$ = NewStringf("::%s",$2); } | DCOLON OPERATOR { $$ = NewStringf("::%s",$2); } -/* | DCOLON COPERATOR { +/* | DCOLON CONVERSIONOPERATOR { $$ = NewString($2); } */ @@ -6700,12 +6695,20 @@ idcolontail : DCOLON idtemplate idcolontail { ; -idtemplate : identifier template_decl { - $$ = NewStringf("%s%s",$1,$2); - /* if (Len($2)) { - scanner_last_id(1); - } */ - } +idtemplate : identifier { + $$ = NewStringf("%s", $1); + } + | identifier less_valparms_greater { + $$ = NewStringf("%s%s", $1, $2); + } + ; + +idtemplatetemplate : idtemplate { + $$ = $1; + } + | TEMPLATE identifier less_valparms_greater { + $$ = NewStringf("%s%s", $2, $3); + } ; /* Identifier, but no templates */ @@ -6749,30 +6752,24 @@ idcolontailnt : DCOLON identifier idcolontailnt { /* Concatenated strings */ string : string STRING { - $$ = (char *) malloc(strlen($1)+strlen($2)+1); - strcpy($$,$1); - strcat($$,$2); + $$ = NewStringf("%s%s", $1, $2); } - | STRING { $$ = $1;} + | STRING { $$ = NewString($1);} ; /* Concatenated wide strings: L"str1" L"str2" */ wstring : wstring WSTRING { - $$ = (char *) malloc(strlen($1)+strlen($2)+1); - strcpy($$,$1); - strcat($$,$2); + $$ = NewStringf("%s%s", $1, $2); } /* Concatenated wide string and normal string literal: L"str1" "str2" */ /*not all the compilers support this concatenation mode, so perhaps better to postpone it*/ /*| wstring STRING { here $2 comes unescaped, we have to escape it back first via NewStringf("%(escape)s)" - $$ = (char *) malloc(strlen($1)+strlen($2)+1); - strcpy($$,$1); - strcat($$,$2); + $$ = NewStringf("%s%s", $1, $2); }*/ - | WSTRING { $$ = $1;} + | WSTRING { $$ = NewString($1);} ; stringbrace : string { - $$ = NewString($1); + $$ = $1; } | LBRACE { skip_balanced('{','}'); @@ -6888,3 +6885,4 @@ ParmList *Swig_cparse_parms(String *s, Node *file_line_node) { /* Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */ return top; } + diff --git a/Source/CParse/templ.c b/Source/CParse/templ.c index fe8fc2800..e575073a4 100644 --- a/Source/CParse/templ.c +++ b/Source/CParse/templ.c @@ -97,6 +97,15 @@ static int cparse_template_expand(Node *n, String *tname, String *rname, String Append(cpatchlist, Getattr(n, "sym:name")); } } + if (checkAttribute(n, "storage", "friend")) { + String *symname = Getattr(n, "sym:name"); + if (symname) { + String *stripped_name = SwigType_templateprefix(symname); + Setattr(n, "sym:name", stripped_name); + Delete(stripped_name); + } + Append(typelist, Getattr(n, "name")); + } add_parms(Getattr(n, "parms"), cpatchlist, typelist); add_parms(Getattr(n, "throws"), cpatchlist, typelist); @@ -228,7 +237,7 @@ String *partial_arg(String *s, String *p) { if (!c) { return Copy(s); } - prefix = NewStringWithSize(cp, c - cp); + prefix = NewStringWithSize(cp, (int)(c - cp)); newarg = Copy(s); Replace(newarg, prefix, "", DOH_REPLACE_ANY | DOH_REPLACE_FIRST); Delete(prefix); diff --git a/Source/DOH/base.c b/Source/DOH/base.c index 4034e5626..12351dd09 100644 --- a/Source/DOH/base.c +++ b/Source/DOH/base.c @@ -146,7 +146,7 @@ int DohLen(const DOH *obj) { } return 0; } else { - return strlen((char *) obj); + return (int)strlen((char *) obj); } } @@ -636,7 +636,7 @@ int DohRead(DOH *obj, void *buffer, int length) { return -1; } /* Hmmm. Not a file. Maybe it's a real FILE */ - return fread(buffer, 1, length, (FILE *) b); + return (int)fread(buffer, 1, length, (FILE *) b); } /* ----------------------------------------------------------------------------- @@ -654,7 +654,7 @@ int DohWrite(DOH *obj, const void *buffer, int length) { return -1; } /* Hmmm. Not a file. Maybe it's a real FILE */ - return fwrite(buffer, 1, length, (FILE *) b); + return (int)fwrite(buffer, 1, length, (FILE *) b); } /* ----------------------------------------------------------------------------- diff --git a/Source/DOH/file.c b/Source/DOH/file.c index 7409ebbfb..5c56771d0 100644 --- a/Source/DOH/file.c +++ b/Source/DOH/file.c @@ -52,7 +52,7 @@ static int File_read(DOH *fo, void *buffer, int len) { DohFile *f = (DohFile *) ObjData(fo); if (f->filep) { - return fread(buffer, 1, len, f->filep); + return (int)fread(buffer, 1, len, f->filep); } else if (f->fd) { #ifdef DOH_INTFILE return read(f->fd, buffer, len); diff --git a/Source/DOH/fio.c b/Source/DOH/fio.c index 7055ffc85..77419008c 100644 --- a/Source/DOH/fio.c +++ b/Source/DOH/fio.c @@ -304,9 +304,9 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { } if (strlen(encoder)) { enc = encode(encoder, Sval); - maxwidth = maxwidth + strlen(newformat) + Len(enc); + maxwidth = maxwidth + (int)strlen(newformat) + Len(enc); } else { - maxwidth = maxwidth + strlen(newformat) + Len(Sval); + maxwidth = maxwidth + (int)strlen(newformat) + Len(Sval); } *(fmt++) = 's'; *fmt = 0; @@ -320,7 +320,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { } else { nbytes += sprintf(stemp, newformat, Data(Sval)); } - if (Writen(so, stemp, strlen(stemp)) < 0) + if (Writen(so, stemp, (int)strlen(stemp)) < 0) return -1; if ((DOH *) Sval != doh) { Delete(Sval); @@ -346,7 +346,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { } else { enc = 0; } - maxwidth = maxwidth + strlen(newformat) + strlen((char *) doh); + maxwidth = maxwidth + (int)strlen(newformat) + (int)strlen((char *) doh); *(fmt++) = 's'; *fmt = 0; if ((maxwidth + 1) < OBUFLEN) { @@ -355,7 +355,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { stemp = (char *) DohMalloc(maxwidth + 1); } nbytes += sprintf(stemp, newformat, doh); - if (Writen(so, stemp, strlen(stemp)) < 0) + if (Writen(so, stemp, (int)strlen(stemp)) < 0) return -1; if (stemp != obuffer) { DohFree(stemp); @@ -366,7 +366,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { } else { *(fmt++) = *p; *fmt = 0; - maxwidth = maxwidth + strlen(newformat) + 64; + maxwidth = maxwidth + (int)strlen(newformat) + 64; /* Only allocate a buffer if it is too big to fit. Shouldn't have to do this very often */ @@ -401,7 +401,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { default: break; } - if (Writen(so, stemp, strlen(stemp)) < 0) + if (Writen(so, stemp, (int)strlen(stemp)) < 0) return -1; if (stemp != obuffer) DohFree(stemp); @@ -414,7 +414,7 @@ int DohvPrintf(DOH *so, const char *format, va_list ap) { if (state) { int r; *fmt = 0; - r = Writen(so, fmt, strlen(fmt)); + r = Writen(so, fmt, (int)strlen(fmt)); if (r < 0) return -1; nbytes += r; @@ -455,7 +455,7 @@ int DohPrintv(DOHFile * f, ...) { if (DohCheck(obj)) { ret += DohDump(obj, f); } else { - ret += DohWrite(f, obj, strlen((char *) obj)); + ret += DohWrite(f, obj, (int)strlen((char *) obj)); } } va_end(ap); diff --git a/Source/DOH/string.c b/Source/DOH/string.c index cfc6c70f6..490198dfa 100644 --- a/Source/DOH/string.c +++ b/Source/DOH/string.c @@ -687,7 +687,7 @@ static int replace_simple(String *str, char *token, char *rep, int flags, int co return 0; base = str->str; - tokenlen = strlen(token); + tokenlen = (int)strlen(token); s = (*match) (base, base, token, tokenlen); if (!s) @@ -724,7 +724,7 @@ static int replace_simple(String *str, char *token, char *rep, int flags, int co } first = s; - replen = strlen(rep); + replen = (int)strlen(rep); delta = (replen - tokenlen); diff --git a/Source/Include/swigwarn.h b/Source/Include/swigwarn.h index 9c9ecb652..a9acbb2cd 100644 --- a/Source/Include/swigwarn.h +++ b/Source/Include/swigwarn.h @@ -236,13 +236,17 @@ /* please leave 720-739 free for Scilab */ -#define WARN_DOXYGEN_UNKNOWN_COMMAND 740 -#define WARN_DOXYGEN_UNEXPECTED_END_OF_COMMENT 741 -#define WARN_DOXYGEN_COMMAND_EXPECTED 742 -#define WARN_DOXYGEN_UNTERMINATED_STRING 743 -#define WARN_DOXYGEN_COMMAND_ERROR 744 +#define WARN_PYTHON_INDENT_MISMATCH 740 -/* please leave 740-749 free for Doxygen */ +/* please leave 740-759 free for Python */ + +#define WARN_DOXYGEN_UNKNOWN_COMMAND 760 +#define WARN_DOXYGEN_UNEXPECTED_END_OF_COMMENT 761 +#define WARN_DOXYGEN_COMMAND_EXPECTED 762 +#define WARN_DOXYGEN_UNTERMINATED_STRING 763 +#define WARN_DOXYGEN_COMMAND_ERROR 764 + +/* please leave 760-779 free for Doxygen */ #define WARN_RUBY_WRONG_NAME 801 #define WARN_RUBY_MULTIPLE_INHERITANCE 802 diff --git a/Source/Modules/allegrocl.cxx b/Source/Modules/allegrocl.cxx index c7d9ff21b..4b2f325ba 100644 --- a/Source/Modules/allegrocl.cxx +++ b/Source/Modules/allegrocl.cxx @@ -1794,12 +1794,12 @@ static List *Swig_overload_rank(Node *n, bool script_lang_wrapping) { String *t2 = Getattr(p2, "tmap:typecheck:precedence"); if ((!t1) && (!nodes[i].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n), - "Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[i].n), SwigType_str(Getattr(p1, "type"), 0)); nodes[i].error = 1; } else if ((!t2) && (!nodes[j].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n), - "Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[j].n), SwigType_str(Getattr(p2, "type"), 0)); nodes[j].error = 1; } diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index dc3820766..f79373d18 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -941,6 +941,8 @@ Allocate(): Setattr(inclass, "allocate:default_destructor", "1"); } else if (cplus_mode == PROTECTED) { Setattr(inclass, "allocate:default_base_destructor", "1"); + } else if (cplus_mode == PRIVATE) { + Setattr(inclass, "allocate:private_destructor", "1"); } } else { Setattr(inclass, "allocate:has_destructor", "1"); diff --git a/Source/Modules/cffi.cxx b/Source/Modules/cffi.cxx index a1be00100..8f718e653 100644 --- a/Source/Modules/cffi.cxx +++ b/Source/Modules/cffi.cxx @@ -831,7 +831,12 @@ void CFFI::emit_struct_union(Node *n, bool un = false) { if (slot_name && (Strcmp(slot_name, "t") == 0 || Strcmp(slot_name, "T") == 0)) slot_name = NewStringf("t_var"); - Printf(f_cl, "\n\t(%s %s)", slot_name, typespec); + if (SwigType_isarray(childType) && SwigType_array_ndim(childType) == 1) { + String *dim = SwigType_array_getdim(childType, 0); + Printf(f_cl, "\n\t(%s %s :count %s)", slot_name, typespec, dim); + Delete(dim); + } else + Printf(f_cl, "\n\t(%s %s)", slot_name, typespec); Delete(node); Delete(childType); diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 3b1e03560..9193cd34b 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -34,6 +34,7 @@ class CSHARP:public Language { File *f_init; File *f_directors; File *f_directors_h; + File *f_single_out; List *filenames_list; bool proxy_flag; // Flag for generating proxy classes @@ -78,6 +79,7 @@ class CSHARP:public Language { String *director_method_types; // Director method types String *director_connect_parms; // Director delegates parameter list for director connect call String *destructor_call; //C++ destructor call if any + String *output_file; // File name for single file mode. If set all generated code will be written to this file // Director method stuff: List *dmethods_seq; @@ -108,6 +110,7 @@ public: f_init(NULL), f_directors(NULL), f_directors_h(NULL), + f_single_out(NULL), filenames_list(NULL), proxy_flag(true), native_function_flag(false), @@ -150,6 +153,7 @@ public: director_method_types(NULL), director_connect_parms(NULL), destructor_call(NULL), + output_file(NULL), dmethods_seq(NULL), dmethods_table(NULL), n_dmethods(0), @@ -244,6 +248,16 @@ public: } else if (strcmp(argv[i], "-oldvarnames") == 0) { Swig_mark_arg(i); old_variable_names = true; + } else if (strcmp(argv[i], "-outfile") == 0) { + if (argv[i + 1]) { + output_file = NewString(""); + Printf(output_file, argv[i + 1]); + Swig_mark_arg(i); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } } else if (strcmp(argv[i], "-help") == 0) { Printf(stdout, "%s\n", usage); } @@ -418,22 +432,12 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } // Generate the intermediary class { - String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), imclass_name); - File *f_im = NewFile(filen, "w", SWIG_output_files()); - if (!f_im) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the intermediary class file - emitBanner(f_im); + File *f_im = getOutputFile(SWIG_output_directory(), imclass_name); addOpenNamespace(0, f_im); @@ -461,23 +465,14 @@ public: Printf(f_im, "}\n"); addCloseNamespace(0, f_im); - Delete(f_im); + if (f_im != f_single_out) + Delete(f_im); + f_im = NULL; } // Generate the C# module class { - String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), module_class_name); - File *f_module = NewFile(filen, "w", SWIG_output_files()); - if (!f_module) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the module class file - emitBanner(f_module); + File *f_module = getOutputFile(SWIG_output_directory(), module_class_name); addOpenNamespace(0, f_module); @@ -513,7 +508,9 @@ public: Printf(f_module, "}\n"); addCloseNamespace(0, f_module); - Delete(f_module); + if (f_module != f_single_out) + Delete(f_module); + f_module = NULL; } if (upcasts_code) @@ -612,6 +609,12 @@ public: f_directors_h = NULL; } + if (f_single_out) { + Dump(f_single_out, f_begin); + Delete(f_single_out); + f_single_out = NULL; + } + Dump(f_wrappers, f_begin); Wrapper_pretty_print(f_init, f_begin); Delete(f_header); @@ -634,6 +637,50 @@ public: Printf(f, "//------------------------------------------------------------------------------\n\n"); } + /* ----------------------------------------------------------------------------- + * getOutputFile() + * + * Prepares a File object by creating the file in the file system and + * writing the banner for auto-generated files to it (emitBanner). + * If '-outfile' is provided (single file mode) the supplied parameters will + * be ignored and the returned file will always be: + * / + * Otherwise the file will be: + *

    /.cs + * ----------------------------------------------------------------------------- */ + + File *getOutputFile(const String *dir, const String *name) { + if (output_file) { + if (!f_single_out) { + String *filen = NewStringf("%s%s", SWIG_output_directory(), output_file); + f_single_out = NewFile(filen, "w", SWIG_output_files()); + if (!f_single_out) { + FileErrorDisplay(filen); + SWIG_exit(EXIT_FAILURE); + } + Append(filenames_list, Copy(filen)); + Delete(filen); + filen = NULL; + + emitBanner(f_single_out); + } + return f_single_out; + } else { + String *filen = NewStringf("%s%s.cs", dir, name); + File *f = NewFile(filen, "w", SWIG_output_files()); + if (!f) { + FileErrorDisplay(f); + SWIG_exit(EXIT_FAILURE); + } + Append(filenames_list, Copy(filen)); + Delete(filen); + filen = NULL; + + emitBanner(f); + return f; + } + } + /*----------------------------------------------------------------------- * Add new director upcall signature *----------------------------------------------------------------------*/ @@ -1085,7 +1132,7 @@ public: scope = NewString(""); if (nspace) Printf(scope, "%s", nspace); - if (Node* cls = getCurrentClass()) { + if (Node *cls = getCurrentClass()) { if (Node *outer = Getattr(cls, "nested:outer")) { String *outerClassesPrefix = Copy(Getattr(outer, "sym:name")); for (outer = Getattr(outer, "nested:outer"); outer != 0; outer = Getattr(outer, "nested:outer")) { @@ -1197,18 +1244,7 @@ public: } else { // Global enums are defined in their own file String *output_directory = outputDirectory(nspace); - String *filen = NewStringf("%s%s.cs", output_directory, symname); - File *f_enum = NewFile(filen, "w", SWIG_output_files()); - if (!f_enum) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the enum file - emitBanner(f_enum); + File *f_enum = getOutputFile(output_directory, symname); addOpenNamespace(nspace, f_enum); @@ -1216,7 +1252,9 @@ public: "\n", enum_code, "\n", NIL); addCloseNamespace(nspace, f_enum); - Delete(f_enum); + if (f_enum != f_single_out) + Delete(f_enum); + f_enum = NULL; Delete(output_directory); } } else { @@ -1641,7 +1679,7 @@ public: String *proxyclassname = Getattr(n, "classtypeobj"); String *baseclassname = Getattr(base.item, "name"); Swig_warning(WARN_CSHARP_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), - "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); + "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in C#.\n", SwigType_namestr(proxyclassname), SwigType_namestr(baseclassname)); base = Next(base); } } @@ -1916,21 +1954,9 @@ public: } } - // Each outer proxy class goes into a separate file if (!has_outerclass) { String *output_directory = outputDirectory(nspace); - String *filen = NewStringf("%s%s.cs", output_directory, proxy_class_name); - f_proxy = NewFile(filen, "w", SWIG_output_files()); - if (!f_proxy) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the proxy class file - emitBanner(f_proxy); + f_proxy = getOutputFile(output_directory, proxy_class_name); addOpenNamespace(nspace, f_proxy); } @@ -1990,7 +2016,8 @@ public: if (!has_outerclass) { Printf(f_proxy, "}\n"); addCloseNamespace(nspace, f_proxy); - Delete(f_proxy); + if (f_proxy != f_single_out) + Delete(f_proxy); f_proxy = NULL; } else { for (int i = 0; i < nesting_depth; ++i) @@ -2003,7 +2030,7 @@ public: good place to put this code, since Abstract Base Classes (ABCs) can and should have downcasts, making the constructorHandler() a bad place (because ABCs don't get to have constructors emitted.) */ - if (GetFlag(n, "feature:javadowncast")) { + if (GetFlag(n, "feature:csdowncast")) { String *downcast_method = Swig_name_member(getNSpace(), proxy_class_name, "SWIGDowncast"); String *wname = Swig_name_wrapper(downcast_method); @@ -3215,18 +3242,7 @@ public: Setline(n, line_number); String *swigtype = NewString(""); - String *filen = NewStringf("%s%s.cs", SWIG_output_directory(), classname); - File *f_swigtype = NewFile(filen, "w", SWIG_output_files()); - if (!f_swigtype) { - FileErrorDisplay(filen); - SWIG_exit(EXIT_FAILURE); - } - Append(filenames_list, Copy(filen)); - Delete(filen); - filen = NULL; - - // Start writing out the type wrapper class file - emitBanner(f_swigtype); + File *f_swigtype = getOutputFile(SWIG_output_directory(), classname); addOpenNamespace(0, f_swigtype); @@ -3261,8 +3277,9 @@ public: Printv(f_swigtype, swigtype, NIL); addCloseNamespace(0, f_swigtype); - - Delete(f_swigtype); + if (f_swigtype != f_single_out) + Delete(f_swigtype); + f_swigtype = NULL; Delete(swigtype); Delete(n); } @@ -3358,7 +3375,7 @@ public: /* ----------------------------------------------------------------------------- * outputDirectory() * - * Return the directory to use for generating Java classes/enums and create the + * Return the directory to use for generating C# classes/enums and create the * subdirectory (does not create if language specific outdir does not exist). * ----------------------------------------------------------------------------- */ @@ -3498,7 +3515,7 @@ public: * classDirectorMethod() * * Emit a virtual director method to pass a method call on to the - * underlying Java object. + * underlying C# object. * * --------------------------------------------------------------- */ @@ -3659,7 +3676,7 @@ public: if (!ignored_method) Printf(w->code, "} else {\n"); - /* Go through argument list, convert from native to Java */ + /* Go through argument list, convert from native to C# */ for (i = 0, p = l; p; ++i) { /* Is this superfluous? */ while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { @@ -4284,4 +4301,5 @@ C# Options (available with -csharp)\n\ -noproxy - Generate the low-level functional interface instead\n\ of proxy classes\n\ -oldvarnames - Old intermediary method names for variable wrappers\n\ + -outfile - Write all C# into a single located in the output directory\n\ \n"; diff --git a/Source/Modules/d.cxx b/Source/Modules/d.cxx index 8546372ea..8b0bdded1 100644 --- a/Source/Modules/d.cxx +++ b/Source/Modules/d.cxx @@ -508,6 +508,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (before %header section). + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } diff --git a/Source/Modules/go.cxx b/Source/Modules/go.cxx index 9a3960ce0..6b9ba760d 100644 --- a/Source/Modules/go.cxx +++ b/Source/Modules/go.cxx @@ -115,6 +115,8 @@ class GO:public Language { String *package; // SWIG module name. String *module; + // Flag for generating cgo input files. + bool cgo_flag; // Flag for generating gccgo output. bool gccgo_flag; // Prefix to use with gccgo. @@ -146,9 +148,12 @@ class GO:public Language { File *f_go_runtime; File *f_go_header; File *f_go_wrappers; + File *f_go_directors; File *f_gc_runtime; File *f_gc_header; File *f_gc_wrappers; + File *f_cgo_comment; + File *f_cgo_comment_typedefs; // True if we imported a module. bool saw_import; @@ -194,6 +199,7 @@ class GO:public Language { public: GO():package(NULL), module(NULL), + cgo_flag(false), gccgo_flag(false), go_prefix(NULL), prefix_option(NULL), @@ -214,9 +220,12 @@ public: f_go_runtime(NULL), f_go_header(NULL), f_go_wrappers(NULL), + f_go_directors(NULL), f_gc_runtime(NULL), f_gc_header(NULL), f_gc_wrappers(NULL), + f_cgo_comment(NULL), + f_cgo_comment_typedefs(NULL), saw_import(false), imported_package(NULL), interfaces(NULL), @@ -229,7 +238,8 @@ public: undefined_enum_types(NULL), undefined_types(NULL), defined_types(NULL), - go_imports(NULL) { + go_imports(NULL), + unique_id(NULL) { director_multiple_inheritance = 1; director_language = 1; director_prot_ctor_code = NewString("_swig_gopanic(\"accessing abstract class or protected constructor\");"); @@ -256,6 +266,9 @@ private: } else { Swig_arg_error(); } + } else if (strcmp(argv[i], "-cgo") == 0) { + Swig_mark_arg(i); + cgo_flag = true; } else if (strcmp(argv[i], "-gccgo") == 0) { Swig_mark_arg(i); gccgo_flag = true; @@ -325,6 +338,10 @@ private: // Add preprocessor symbol to parser. Preprocessor_define("SWIGGO 1", 0); + if (cgo_flag) { + Preprocessor_define("SWIGGO_CGO 1", 0); + } + if (gccgo_flag) { Preprocessor_define("SWIGGO_GCCGO 1", 0); } @@ -413,7 +430,7 @@ private: } if (!pkgpath_option) { Append(go_prefix, "."); - Append(go_prefix, package); + Append(go_prefix, getModuleName(package)); } } @@ -444,7 +461,7 @@ private: Delete(swig_input_content); fclose(swig_input); unique_id = NewString(""); - Printf(unique_id, "_%s_%08x%08x", package, hash.hi, hash.lo); + Printf(unique_id, "_%s_%08x%08x", getModuleName(package), hash.hi, hash.lo); // Open files. @@ -472,7 +489,7 @@ private: SWIG_exit(EXIT_FAILURE); } - if (!gccgo_flag) { + if (!gccgo_flag && !cgo_flag) { f_gc_begin = NewFile(gc_filename, "w", SWIG_output_files()); if (!f_gc_begin) { FileErrorDisplay(gc_filename); @@ -489,11 +506,16 @@ private: f_go_runtime = NewString(""); f_go_header = NewString(""); f_go_wrappers = NewString(""); - if (!gccgo_flag) { + f_go_directors = NewString(""); + if (!gccgo_flag && !cgo_flag) { f_gc_runtime = NewString(""); f_gc_header = NewString(""); f_gc_wrappers = NewString(""); } + if (cgo_flag) { + f_cgo_comment = NewString(""); + f_cgo_comment_typedefs = NewString(""); + } Swig_register_filebyname("begin", f_c_begin); Swig_register_filebyname("runtime", f_c_runtime); @@ -507,12 +529,17 @@ private: Swig_register_filebyname("go_runtime", f_go_runtime); Swig_register_filebyname("go_header", f_go_header); Swig_register_filebyname("go_wrapper", f_go_wrappers); - if (!gccgo_flag) { + Swig_register_filebyname("go_director", f_go_directors); + if (!gccgo_flag && !cgo_flag) { Swig_register_filebyname("gc_begin", f_gc_begin); Swig_register_filebyname("gc_runtime", f_gc_runtime); Swig_register_filebyname("gc_header", f_gc_header); Swig_register_filebyname("gc_wrapper", f_gc_wrappers); } + if (cgo_flag) { + Swig_register_filebyname("cgo_comment", f_cgo_comment); + Swig_register_filebyname("cgo_comment_typedefs", f_cgo_comment_typedefs); + } Swig_banner(f_c_begin); if (CPlusPlus) { @@ -545,18 +572,28 @@ private: Swig_banner(f_go_begin); Printf(f_go_begin, "\n// source: %s\n", swig_filename); - if (!gccgo_flag && soname) { + if (!gccgo_flag && !cgo_flag && soname) { Swig_banner(f_gc_begin); Printf(f_gc_begin, "\n/* source: %s */\n\n", swig_filename); Printf(f_gc_begin, "\n/* This file should be compiled with 6c/8c. */\n"); Printf(f_gc_begin, "#pragma dynimport _ _ \"%s\"\n", soname); } + if (cgo_flag) { + Printv(f_cgo_comment_typedefs, "/*\n", NULL); + + // The cgo program defines the intgo type after our function + // definitions, but we want those definitions to be able to use + // intgo also. + Printv(f_cgo_comment_typedefs, "#define intgo swig_intgo\n", NULL); + Printv(f_cgo_comment_typedefs, "typedef void *swig_voidp;\n", NULL); + } + // Output module initialization code. - Printf(f_go_begin, "\npackage %s\n\n", package); + Printf(f_go_begin, "\npackage %s\n\n", getModuleName(package)); - if (gccgo_flag) { + if (gccgo_flag && !cgo_flag) { Printf(f_go_runtime, "func SwigCgocall()\n"); Printf(f_go_runtime, "func SwigCgocallDone()\n"); Printf(f_go_runtime, "func SwigCgocallBack()\n"); @@ -628,14 +665,29 @@ private: // End the extern "C". Printv(f_c_wrappers, "#ifdef __cplusplus\n", "}\n", "#endif\n\n", NULL); + if (cgo_flag) { + // End the cgo comment. + Printv(f_cgo_comment, "#undef intgo\n", NULL); + Printv(f_cgo_comment, "*/\n", NULL); + Printv(f_cgo_comment, "import \"C\"\n", NULL); + Printv(f_cgo_comment, "\n", NULL); + } + Dump(f_c_runtime, f_c_begin); Dump(f_c_wrappers, f_c_begin); Dump(f_c_init, f_c_begin); + if (cgo_flag) { + Dump(f_cgo_comment_typedefs, f_go_begin); + Dump(f_cgo_comment, f_go_begin); + } Dump(f_go_imports, f_go_begin); Dump(f_go_header, f_go_begin); Dump(f_go_runtime, f_go_begin); Dump(f_go_wrappers, f_go_begin); - if (!gccgo_flag) { + if (directorsEnabled()) { + Dump(f_go_directors, f_go_begin); + } + if (!gccgo_flag && !cgo_flag) { Dump(f_gc_header, f_gc_begin); Dump(f_gc_runtime, f_gc_begin); Dump(f_gc_wrappers, f_gc_begin); @@ -649,15 +701,20 @@ private: Delete(f_go_runtime); Delete(f_go_header); Delete(f_go_wrappers); - if (!gccgo_flag) { + Delete(f_go_directors); + if (!gccgo_flag && !cgo_flag) { Delete(f_gc_runtime); Delete(f_gc_header); Delete(f_gc_wrappers); } + if (cgo_flag) { + Delete(f_cgo_comment); + Delete(f_cgo_comment_typedefs); + } Delete(f_c_begin); Delete(f_go_begin); - if (!gccgo_flag) { + if (!gccgo_flag && !cgo_flag) { Delete(f_gc_begin); } @@ -937,24 +994,33 @@ private: assert(result); - int r = goFunctionWrapper(n, name, go_name, overname, wname, base, parms, result, is_static); - if (r != SWIG_OK) { - return r; - } + int ret = SWIG_OK; - if (!gccgo_flag) { - r = gcFunctionWrapper(wname); + if (cgo_flag) { + int r = makeCgoWrappers(n, go_name, overname, wname, base, parms, result, is_static); if (r != SWIG_OK) { - return r; - } - r = gccFunctionWrapper(n, base, wname, parms, result); - if (r != SWIG_OK) { - return r; + ret = r; } } else { - r = gccgoFunctionWrapper(n, base, wname, parms, result); + int r = goFunctionWrapper(n, name, go_name, overname, wname, base, parms, result, is_static); if (r != SWIG_OK) { - return r; + ret = r; + } + + if (!gccgo_flag) { + r = gcFunctionWrapper(wname); + if (r != SWIG_OK) { + ret = r; + } + r = gccFunctionWrapper(n, base, wname, parms, result); + if (r != SWIG_OK) { + ret = r; + } + } else { + r = gccgoFunctionWrapper(n, base, wname, parms, result); + if (r != SWIG_OK) { + ret = r; + } } } @@ -962,6 +1028,556 @@ private: Setattr(class_methods, Getattr(n, "name"), NewString("")); } + return ret; + } + + /* ---------------------------------------------------------------------- + * struct cgoWrapperInfo + * + * Information needed by the CGO wrapper functions. + * ---------------------------------------------------------------------- */ + + struct cgoWrapperInfo { + // The function we are generating code for. + Node *n; + // The name of the Go function. + String *go_name; + // The overload string for an overloaded function. + String *overname; + // The name of the C wrapper function. + String *wname; + // The base classes. + List *base; + // The parameters. + ParmList *parms; + // The result type. + SwigType *result; + // Whether this is a static function, not a class method. + bool is_static; + // The Go receiver type. + String *receiver; + // Whether this is a class constructor. + bool is_constructor; + // Whether this is a class destructor. + bool is_destructor; + }; + + /* ---------------------------------------------------------------------- + * makeCgoWrappers() + * + * Write out the wrappers for a function when producing cgo input + * files. + * ---------------------------------------------------------------------- */ + + int makeCgoWrappers(Node *n, String *go_name, String *overname, String *wname, List *base, ParmList *parms, SwigType *result, bool is_static) { + Swig_save("makeCgoWrappers", n, "emit:cgotype", "emit:cgotypestruct", NULL); + + cgoWrapperInfo info; + + info.n = n; + info.go_name = go_name; + info.overname = overname; + info.wname = wname; + info.base = base; + info.parms = parms; + info.result = result; + info.is_static = is_static; + + info.receiver = class_receiver; + if (is_static) { + info.receiver = NULL; + } + + String *nodetype = Getattr(n, "nodeType"); + info.is_constructor = Cmp(nodetype, "constructor") == 0; + info.is_destructor = Cmp(nodetype, "destructor") == 0; + if (info.is_constructor || info.is_destructor) { + assert(class_receiver); + assert(!base); + info.receiver = NULL; + } + + int ret = SWIG_OK; + + int r = cgoGoWrapper(&info); + if (r != SWIG_OK) { + ret = r; + } + + r = cgoCommentWrapper(&info); + if (r != SWIG_OK) { + ret = r; + } + + r = cgoGccWrapper(&info); + if (r != SWIG_OK) { + ret = r; + } + + Swig_restore(n); + + return ret; + } + + /* ---------------------------------------------------------------------- + * cgoGoWrapper() + * + * Write out Go code to call a cgo function. This code will go into + * the generated Go output file. + * ---------------------------------------------------------------------- */ + int cgoGoWrapper(const cgoWrapperInfo *info) { + + Wrapper *dummy = initGoTypemaps(info->parms); + + bool add_to_interface = interfaces && !info->is_constructor && !info->is_destructor && !info->is_static && !info->overname && checkFunctionVisibility(info->n, NULL); + + Printv(f_go_wrappers, "func ", NULL); + + Parm *p = info->parms; + int pi = 0; + + // Add the receiver first if this is a method. + if (info->receiver) { + Printv(f_go_wrappers, "(", NULL); + if (info->base && info->receiver) { + Printv(f_go_wrappers, "_swig_base", NULL); + } else { + Printv(f_go_wrappers, Getattr(p, "lname"), NULL); + p = nextParm(p); + ++pi; + } + Printv(f_go_wrappers, " ", info->receiver, ") ", NULL); + } + + Printv(f_go_wrappers, info->go_name, NULL); + if (info->overname) { + Printv(f_go_wrappers, info->overname, NULL); + } + Printv(f_go_wrappers, "(", NULL); + + // If we are doing methods, add this method to the interface. + if (add_to_interface) { + Printv(interfaces, "\t", info->go_name, "(", NULL); + } + + // Write out the parameters to both the function definition and + // the interface. + + String *parm_print = NewString(""); + + int parm_count = emit_num_arguments(info->parms); + int required_count = emit_num_required(info->parms); + int args = 0; + + for (; pi < parm_count; ++pi) { + p = getParm(p); + if (pi == 0 && info->is_destructor) { + String *cl = exportedName(class_name); + Printv(parm_print, Getattr(p, "lname"), " ", cl, NULL); + Delete(cl); + ++args; + } else { + if (args > 0) { + Printv(parm_print, ", ", NULL); + } + ++args; + if (pi >= required_count) { + Printv(parm_print, "_swig_args ...interface{}", NULL); + break; + } + Printv(parm_print, Getattr(p, "lname"), " ", NULL); + String *tm = goType(p, Getattr(p, "type")); + Printv(parm_print, tm, NULL); + Delete(tm); + } + p = nextParm(p); + } + + Printv(parm_print, ")", NULL); + + // Write out the result type. + if (info->is_constructor) { + String *cl = exportedName(class_name); + Printv(parm_print, " (_swig_ret ", cl, ")", NULL); + Delete(cl); + } else { + if (SwigType_type(info->result) != T_VOID) { + String *tm = goType(info->n, info->result); + Printv(parm_print, " (_swig_ret ", tm, ")", NULL); + Delete(tm); + } + } + + Printv(f_go_wrappers, parm_print, NULL); + if (add_to_interface) { + Printv(interfaces, parm_print, "\n", NULL); + } + + // Write out the function body. + + Printv(f_go_wrappers, " {\n", NULL); + + if (parm_count > required_count) { + Parm *p = info->parms; + int i; + for (i = 0; i < required_count; ++i) { + p = getParm(p); + p = nextParm(p); + } + for (; i < parm_count; ++i) { + p = getParm(p); + String *tm = goType(p, Getattr(p, "type")); + Printv(f_go_wrappers, "\tvar ", Getattr(p, "lname"), " ", tm, "\n", NULL); + Printf(f_go_wrappers, "\tif len(_swig_args) > %d {\n", i - required_count); + Printf(f_go_wrappers, "\t\t%s = _swig_args[%d].(%s)\n", Getattr(p, "lname"), i - required_count, tm); + Printv(f_go_wrappers, "\t}\n", NULL); + Delete(tm); + p = nextParm(p); + } + } + + String *call = NewString("\t"); + + String *ret_type = NULL; + bool memcpy_ret = false; + String *wt = NULL; + if (SwigType_type(info->result) != T_VOID) { + if (info->is_constructor) { + ret_type = exportedName(class_name); + } else { + ret_type = goImType(info->n, info->result); + } + Printv(f_go_wrappers, "\tvar swig_r ", ret_type, "\n", NULL); + + bool c_struct_type; + Delete(cgoTypeForGoValue(info->n, info->result, &c_struct_type)); + if (c_struct_type) { + memcpy_ret = true; + } + + if (memcpy_ret) { + Printv(call, "swig_r_p := ", NULL); + } else { + Printv(call, "swig_r = (", ret_type, ")(", NULL); + } + + if (info->is_constructor || goTypeIsInterface(info->n, info->result)) { + if (info->is_constructor) { + wt = Copy(class_receiver); + } else { + wt = goWrapperType(info->n, info->result, true); + } + Printv(call, wt, "(", NULL); + } + } + + Printv(call, "C.", info->wname, "(", NULL); + + args = 0; + + if (parm_count > required_count) { + Printv(call, "C.swig_intgo(len(_swig_args))", NULL); + ++args; + } + + if (info->base && info->receiver) { + if (args > 0) { + Printv(call, ", ", NULL); + } + ++args; + Printv(call, "C.uintptr_t(_swig_base)", NULL); + } + + p = info->parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + if (args > 0) { + Printv(call, ", ", NULL); + } + ++args; + + SwigType *pt = Getattr(p, "type"); + String *ln = Getattr(p, "lname"); + + String *ivar = NewStringf("_swig_i_%d", i); + + String *goin = goGetattr(p, "tmap:goin"); + if (goin == NULL) { + Printv(f_go_wrappers, "\t", ivar, " := ", ln, NULL); + if ((i == 0 && info->is_destructor) || ((i > 0 || !info->receiver || info->base || info->is_constructor) && goTypeIsInterface(p, pt))) { + Printv(f_go_wrappers, ".Swigcptr()", NULL); + } + Printv(f_go_wrappers, "\n", NULL); + Setattr(p, "emit:goinput", ln); + } else { + String *itm = goImType(p, pt); + Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, "\n", NULL); + goin = Copy(goin); + Replaceall(goin, "$input", ln); + Replaceall(goin, "$result", ivar); + Printv(f_go_wrappers, goin, "\n", NULL); + Delete(goin); + Setattr(p, "emit:goinput", ivar); + } + + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, pt, &c_struct_type); + if (c_struct_type) { + Printv(call, "*(*C.", ct, ")(unsafe.Pointer(&", ivar, "))", NULL); + } else { + Printv(call, "C.", ct, "(", ivar, ")", NULL); + } + Delete(ct); + + p = nextParm(p); + } + + Printv(f_go_wrappers, call, ")", NULL); + Delete(call); + + if (wt) { + // Close the type conversion to the wrapper type. + Printv(f_go_wrappers, ")", NULL); + } + if (SwigType_type(info->result) != T_VOID && !memcpy_ret) { + // Close the type conversion of the return value. + Printv(f_go_wrappers, ")", NULL); + } + + Printv(f_go_wrappers, "\n", NULL); + + if (memcpy_ret) { + Printv(f_go_wrappers, "\tswig_r = *(*", ret_type, ")(unsafe.Pointer(&swig_r_p))\n", NULL); + } + if (ret_type) { + Delete(ret_type); + } + + goargout(info->parms); + + if (SwigType_type(info->result) != T_VOID) { + String *goout = goTypemapLookup("goout", info->n, "swig_r"); + if (goout == NULL) { + Printv(f_go_wrappers, "\treturn swig_r\n", NULL); + } else { + String *tm = goType(info->n, info->result); + Printv(f_go_wrappers, "\tvar swig_r_1 ", tm, "\n", NULL); + goout = Copy(goout); + Replaceall(goout, "$input", "swig_r"); + Replaceall(goout, "$result", "swig_r_1"); + Printv(f_go_wrappers, goout, "\n", NULL); + Printv(f_go_wrappers, "\treturn swig_r_1\n", NULL); + } + } + + Printv(f_go_wrappers, "}\n\n", NULL); + + DelWrapper(dummy); + + return SWIG_OK; + } + + /* ---------------------------------------------------------------------- + * cgoCommentWrapper() + * + * Write out a cgo function to call a C/C++ function. This code + * will go into the cgo comment in the generated Go output file. + * ---------------------------------------------------------------------- */ + int cgoCommentWrapper(const cgoWrapperInfo *info) { + String *ret_type; + if (SwigType_type(info->result) == T_VOID) { + ret_type = NewString("void"); + } else { + bool c_struct_type; + ret_type = cgoTypeForGoValue(info->n, info->result, &c_struct_type); + } + + Printv(f_cgo_comment, "extern ", ret_type, " ", info->wname, "(", NULL); + + Delete(ret_type); + + int parm_count = emit_num_arguments(info->parms); + int required_count = emit_num_required(info->parms); + int args = 0; + + if (parm_count > required_count) { + Printv(f_cgo_comment, "intgo _swig_args", NULL); + ++args; + } + + if (info->base && info->receiver) { + if (args > 0) { + Printv(f_cgo_comment, ", ", NULL); + } + ++args; + Printv(f_cgo_comment, "uintptr_t _swig_base", NULL); + } + + Parm *p = info->parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + if (args > 0) { + Printv(f_cgo_comment, ", ", NULL); + } + ++args; + + SwigType *pt = Getattr(p, "type"); + String *ln = Getattr(p, "lname"); + + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, pt, &c_struct_type); + Printv(f_cgo_comment, ct, " ", ln, NULL); + Delete(ct); + + p = nextParm(p); + } + + if (args == 0) { + Printv(f_cgo_comment, "void", NULL); + } + + Printv(f_cgo_comment, ");\n", NULL); + + return SWIG_OK; + } + + /* ---------------------------------------------------------------------- + * cgoGccWrapper() + * + * Write out code to the C/C++ wrapper file. This code will be + * called by the code generated by cgoCommentWrapper. + * ---------------------------------------------------------------------- */ + int cgoGccWrapper(const cgoWrapperInfo *info) { + Wrapper *f = NewWrapper(); + + Swig_save("cgoGccWrapper", info->n, "parms", NULL); + + ParmList *parms = info->parms; + + Parm *base_parm = NULL; + if (info->base && !isStatic(info->n)) { + SwigType *base_type = Copy(getClassType()); + SwigType_add_pointer(base_type); + base_parm = NewParm(base_type, NewString("arg1"), info->n); + set_nextSibling(base_parm, parms); + parms = base_parm; + } + + emit_parameter_variables(parms, f); + emit_attach_parmmaps(parms, f); + int parm_count = emit_num_arguments(parms); + int required_count = emit_num_required(parms); + + emit_return_variable(info->n, info->result, f); + + // Start the function definition. + + String *fnname = NewString(""); + Printv(fnname, info->wname, "(", NULL); + + int args = 0; + + if (parm_count > required_count) { + Printv(fnname, "intgo _swig_optargc", NULL); + ++args; + } + + Parm *p = parms; + for (int i = 0; i < parm_count; ++i) { + if (args > 0) { + Printv(fnname, ", ", NULL); + } + ++args; + + p = getParm(p); + + SwigType *pt = Copy(Getattr(p, "type")); + if (SwigType_isarray(pt)) { + SwigType_del_array(pt); + SwigType_add_pointer(pt); + } + String *pn = NewStringf("_swig_go_%d", i); + String *ct = gcCTypeForGoValue(p, pt, pn); + Printv(fnname, ct, NULL); + Delete(ct); + Delete(pn); + Delete(pt); + + p = nextParm(p); + } + + Printv(fnname, ")", NULL); + + if (SwigType_type(info->result) == T_VOID) { + Printv(f->def, "void ", fnname, NULL); + } else { + String *ct = gcCTypeForGoValue(info->n, info->result, fnname); + Printv(f->def, ct, NULL); + Delete(ct); + + String *ln = NewString("_swig_go_result"); + ct = gcCTypeForGoValue(info->n, info->result, ln); + Wrapper_add_local(f, "_swig_go_result", ct); + Delete(ct); + Delete(ln); + } + + Delete(fnname); + + Printv(f->def, " {\n", NULL); + + // Apply the in typemaps. + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + String *tm = Getattr(p, "tmap:in"); + if (!tm) { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "unable to use type %s as a function argument\n", SwigType_str(Getattr(p, "type"), 0)); + } else { + tm = Copy(tm); + String *pn = NewStringf("_swig_go_%d", i); + Replaceall(tm, "$input", pn); + if (i < required_count) { + Printv(f->code, "\t", tm, "\n", NULL); + } else { + Printf(f->code, "\tif (_swig_optargc > %d) {\n", i - required_count); + Printv(f->code, "\t\t", tm, "\n", NULL); + Printv(f->code, "\t}\n", NULL); + } + Delete(tm); + Setattr(p, "emit:input", pn); + } + p = nextParm(p); + } + + Printv(f->code, "\n", NULL); + + // Do the real work of the function. + + checkConstraints(parms, f); + + emitGoAction(info->n, info->base, parms, info->result, f); + + argout(parms, f); + + cleanupFunction(info->n, f, parms); + + if (SwigType_type(info->result) != T_VOID) { + Printv(f->code, "\treturn _swig_go_result;\n", NULL); + } + + Printv(f->code, "}\n", NULL); + + Wrapper_print(f, f_c_wrappers); + + Swig_restore(info->n); + + DelWrapper(f); + if (base_parm) { + Delete(base_parm); + } + return SWIG_OK; } @@ -977,23 +1593,9 @@ private: * ---------------------------------------------------------------------- */ int goFunctionWrapper(Node *n, String *name, String *go_name, String *overname, String *wname, List *base, ParmList *parms, SwigType *result, bool is_static) { - Wrapper *dummy = NewWrapper(); - emit_attach_parmmaps(parms, dummy); + Wrapper *dummy = initGoTypemaps(parms); - Parm *p = parms; int parm_count = emit_num_arguments(parms); - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - Swig_cparm_name(p, i); - p = nextParm(p); - } - - Swig_typemap_attach_parms("default", parms, dummy); - Swig_typemap_attach_parms("gotype", parms, dummy); - Swig_typemap_attach_parms("goin", parms, dummy); - Swig_typemap_attach_parms("goargout", parms, dummy); - Swig_typemap_attach_parms("imtype", parms, dummy); - int required_count = emit_num_required(parms); String *receiver = class_receiver; @@ -1024,7 +1626,7 @@ private: // See whether any of the function parameters are represented by // interface values. When calling the C++ code, we need to convert // back to a uintptr. - p = parms; + Parm *p = parms; for (int i = 0; i < parm_count; ++i) { p = getParm(p); String *ty = Getattr(p, "type"); @@ -1314,11 +1916,11 @@ private: String *ivar = NewString(""); Printf(ivar, "_swig_i_%d", i); String *itm = goImType(p, pt); - Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, NULL); + Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, "\n", NULL); goin = Copy(goin); Replaceall(goin, "$input", ln); Replaceall(goin, "$result", ivar); - Printv(f_go_wrappers, goin, NULL); + Printv(f_go_wrappers, goin, "\n", NULL); Delete(goin); Printv(call, ivar, NULL); Setattr(p, "emit:goinput", ivar); @@ -1343,7 +1945,7 @@ private: Printv(f_go_wrappers, call, NULL); Delete(call); - goargout(parms, parm_count); + goargout(parms); if (need_return_var) { if (goout == NULL) { @@ -1383,6 +1985,34 @@ private: return SWIG_OK; } + /* ---------------------------------------------------------------------- + * initGoTypemaps() + * + * Initialize the typenames for a Go wrapper, returning a dummy + * Wrapper*. Also set consistent names for the parameters. + * ---------------------------------------------------------------------- */ + + Wrapper* initGoTypemaps(ParmList *parms) { + Wrapper *dummy = NewWrapper(); + emit_attach_parmmaps(parms, dummy); + + Parm *p = parms; + int parm_count = emit_num_arguments(parms); + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + Swig_cparm_name(p, i); + p = nextParm(p); + } + + Swig_typemap_attach_parms("default", parms, dummy); + Swig_typemap_attach_parms("gotype", parms, dummy); + Swig_typemap_attach_parms("goin", parms, dummy); + Swig_typemap_attach_parms("goargout", parms, dummy); + Swig_typemap_attach_parms("imtype", parms, dummy); + + return dummy; + } + /* ---------------------------------------------------------------------- * argName() * @@ -1405,7 +2035,7 @@ private: * needs to explicitly escape. This is true if the parameter has a * non-empty argout or freearg typemap, because in those cases the * Go argument might be or contain a pointer. We need to ensure - * that that pointer does not oint into the stack, which means that + * that that pointer does not point into the stack, which means that * it needs to escape. * ---------------------------------------------------------------------- */ bool paramNeedsEscape(Parm *p) { @@ -1763,7 +2393,7 @@ private: * ----------------------------------------------------------------------- */ void emitGoAction(Node *n, List *base, ParmList *parms, SwigType *result, Wrapper *f) { - if (!gccgo_flag && SwigType_type(result) != T_VOID) { + if (!gccgo_flag && !cgo_flag && SwigType_type(result) != T_VOID) { Wrapper_add_local(f, "swig_stktop", "char *swig_stktop"); Printv(f->code, "\tswig_stktop = _swig_topofstack();\n", NULL); } @@ -1776,7 +2406,7 @@ private: actioncode = NewString(""); String *current = NewString(""); - if (!gccgo_flag) { + if (!gccgo_flag && !cgo_flag) { Printv(current, "swig_a->", NULL); } Printv(current, Getattr(parms, "lname"), NULL); @@ -1813,7 +2443,7 @@ private: Delete(tm); } - if (!gccgo_flag && SwigType_type(result) != T_VOID) { + if (!gccgo_flag && !cgo_flag && SwigType_type(result) != T_VOID) { // If the function called back into the Go code, the stack might // have been copied. We need to adjust swig_a accordingly here. // This is what cgo does. @@ -1857,22 +2487,43 @@ private: * property with the name to use to refer to that parameter. * ----------------------------------------------------------------------- */ - void goargout(ParmList *parms, int parm_count) { + void goargout(ParmList *parms) { Parm *p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - String *tm = goGetattr(p, "tmap:goargout"); + while (p) { + String *tm = Getattr(p, "tmap:goargout"); if (!tm) { p = nextSibling(p); } else { tm = Copy(tm); Replaceall(tm, "$result", "swig_r"); Replaceall(tm, "$input", Getattr(p, "emit:goinput")); - Printv(f_go_wrappers, tm, NULL); + Printv(f_go_wrappers, tm, "\n", NULL); Delete(tm); p = Getattr(p, "tmap:goargout:next"); } } + + // When using cgo, if we need to memcpy a parameter to pass it to + // the C code, the compiler may think that the parameter is not + // live during the function call. If the garbage collector runs + // while the C/C++ function is running, the parameter may be + // freed. Force the compiler to see the parameter as live across + // the C/C++ function. + if (cgo_flag) { + int parm_count = emit_num_arguments(parms); + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + bool c_struct_type; + Delete(cgoTypeForGoValue(p, Getattr(p, "type"), &c_struct_type)); + if (c_struct_type) { + Printv(f_go_wrappers, "\tif Swig_escape_always_false {\n", NULL); + Printv(f_go_wrappers, "\t\tSwig_escape_val = ", Getattr(p, "emit:goinput"), "\n", NULL); + Printv(f_go_wrappers, "\t}\n", NULL); + } + p = nextParm(p); + } + } } /* ----------------------------------------------------------------------- @@ -1978,7 +2629,7 @@ private: // exponentiation. Treat anything else as too complicated to // handle as a Go constant. char *p = Char(value); - int len = strlen(p); + int len = (int)strlen(p); bool need_copy = false; while (len > 0) { char c = p[len - 1]; @@ -2058,7 +2709,7 @@ private: Printv(f_go_wrappers, "type ", name, " int\n", NULL); } else { String *nw = NewString(""); - Printv(nw, imported_package, ".", name, NULL); + Printv(nw, getModuleName(imported_package), ".", name, NULL); Setattr(n, "go:enumname", nw); } } @@ -2509,15 +3160,26 @@ private: Setattr(var, "type", var_type); SwigType *vt = Copy(var_type); - if (SwigType_isclass(vt)) { - SwigType_add_pointer(vt); - } int flags = Extend | SmartPointer | use_naturalvar_mode(var); if (isNonVirtualProtectedAccess(var)) { flags |= CWRAP_ALL_PROTECTED_ACCESS; } + // Copied from Swig_wrapped_member_var_type. + if (SwigType_isclass(vt)) { + if (flags & CWRAP_NATURAL_VAR) { + if (CPlusPlus) { + if (!SwigType_isconst(vt)) { + SwigType_add_qualifier(vt, "const"); + } + SwigType_add_reference(vt); + } + } else { + SwigType_add_pointer(vt); + } + } + String *mname = Swig_name_member(getNSpace(), Getattr(var_class, "sym:name"), var_name); if (is_assignable(var)) { @@ -2888,6 +3550,11 @@ private: } } + String *fn_with_over_name = Copy(fn_name); + if (overname) { + Append(fn_with_over_name, overname); + } + String *wname = Swig_name_wrapper(fn_name); if (overname) { @@ -2903,6 +3570,8 @@ private: DelWrapper(dummy); Swig_typemap_attach_parms("gotype", parms, NULL); + Swig_typemap_attach_parms("goin", parms, NULL); + Swig_typemap_attach_parms("goargout", parms, NULL); Swig_typemap_attach_parms("imtype", parms, NULL); int parm_count = emit_num_arguments(parms); @@ -2914,8 +3583,7 @@ private: Append(func_with_over_name, overname); } - SwigType *first_type = NewString("void"); - SwigType_add_pointer(first_type); + SwigType *first_type = NewString("int"); Parm *first_parm = NewParm(first_type, "swig_p", n); set_nextSibling(first_parm, parms); Setattr(first_parm, "lname", "p"); @@ -2928,47 +3596,58 @@ private: } if (!is_ignored) { - // Declare the C++ wrapper. + if (cgo_flag) { + Printv(f_cgo_comment, "extern uintptr_t ", wname, "(int", NULL); - if (!gccgo_flag) { - Printv(f_go_wrappers, "var ", wname, " unsafe.Pointer\n\n", NULL); + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, Getattr(p, "type"), &c_struct_type); + Printv(f_cgo_comment, ", ", ct, " ", Getattr(p, "lname"), NULL); + p = nextParm(p); + } + Printv(f_cgo_comment, ");\n", NULL); } else { - Printv(f_go_wrappers, "//extern ", go_prefix, "_", wname, "\n", NULL); + // Declare the C++ wrapper. + + if (!gccgo_flag) { + Printv(f_go_wrappers, "var ", wname, " unsafe.Pointer\n\n", NULL); + } else { + Printv(f_go_wrappers, "//extern ", go_prefix, "_", wname, "\n", NULL); + } + + Printv(f_go_wrappers, "func ", fn_with_over_name, "(_swig_director int", NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + String *tm = goWrapperType(p, Getattr(p, "type"), false); + Printv(f_go_wrappers, ", _ ", tm, NULL); + Delete(tm); + p = nextParm(p); + } + + Printv(f_go_wrappers, ") (_swig_ret ", go_type_name, ")", NULL); + + if (!gccgo_flag) { + Printv(f_go_wrappers, " {\n", NULL); + Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&_swig_director))\n", NULL); + Printv(f_go_wrappers, "\t_cgo_runtime_cgocall(", wname, ", _swig_p)\n", NULL); + Printv(f_go_wrappers, "\treturn\n", NULL); + Printv(f_go_wrappers, "}", NULL); + } + + Printv(f_go_wrappers, "\n\n", NULL); } - Printv(f_go_wrappers, "func ", fn_name, NULL); - if (overname) { - Printv(f_go_wrappers, overname, NULL); - } - Printv(f_go_wrappers, "(_swig_director *", director_struct_name, NULL); - - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - String *tm = goType(p, Getattr(p, "type")); - Printv(f_go_wrappers, ", _ ", tm, NULL); - Delete(tm); - p = nextParm(p); - } - - Printv(f_go_wrappers, ") (_swig_ret ", go_type_name, ")", NULL); - - if (!gccgo_flag) { - Printv(f_go_wrappers, " {\n", NULL); - Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&_swig_director))\n", NULL); - Printv(f_go_wrappers, "\t_cgo_runtime_cgocall(", wname, ", _swig_p)\n", NULL); - Printv(f_go_wrappers, "\treturn\n", NULL); - Printv(f_go_wrappers, "}", NULL); - } - - Printv(f_go_wrappers, "\n\n", NULL); + // Write out the Go function that calls the wrapper. Printv(f_go_wrappers, "func ", func_with_over_name, "(v interface{}", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { p = getParm(p); - // Set the lname parameter. Printv(f_go_wrappers, ", ", Getattr(p, "lname"), " ", NULL); String *tm = goType(p, Getattr(p, "type")); Printv(f_go_wrappers, tm, NULL); @@ -2980,25 +3659,73 @@ private: Printv(f_go_wrappers, "\tp := &", director_struct_name, "{0, v}\n", NULL); - if (gccgo_flag) { + if (gccgo_flag && !cgo_flag) { Printv(f_go_wrappers, "\tdefer SwigCgocallDone()\n", NULL); Printv(f_go_wrappers, "\tSwigCgocall()\n", NULL); } - Printv(f_go_wrappers, "\tp.", class_receiver, " = ", fn_name, NULL); - if (overname) { - Printv(f_go_wrappers, overname, NULL); + String *call = NewString(""); + + Printv(call, "\tp.", class_receiver, " = ", NULL); + if (cgo_flag) { + Printv(call, go_type_name, "(C.", wname, "(C.int(swigDirectorAdd(p))", NULL); + } else { + Printv(call, fn_with_over_name, "(swigDirectorAdd(p)", NULL); } - Printv(f_go_wrappers, "(p", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { + Printv(call, ", ", NULL); + p = getParm(p); - Printv(f_go_wrappers, ", ", Getattr(p, "lname"), NULL); + String *pt = Getattr(p, "type"); + String *ln = Getattr(p, "lname"); + + String *ivar = NewStringf("_swig_i_%d", i); + + String *goin = goGetattr(p, "tmap:goin"); + if (goin == NULL) { + Printv(f_go_wrappers, "\t", ivar, " := ", ln, NULL); + if (goTypeIsInterface(p, pt)) { + Printv(f_go_wrappers, ".Swigcptr()", NULL); + } + Printv(f_go_wrappers, "\n", NULL); + } else { + String *itm = goImType(p, pt); + Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, "\n", NULL); + goin = Copy(goin); + Replaceall(goin, "$input", ln); + Replaceall(goin, "$result", ivar); + Printv(f_go_wrappers, goin, "\n", NULL); + Delete(goin); + } + + Setattr(p, "emit:goinput", ivar); + + if (cgo_flag) { + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, pt, &c_struct_type); + if (c_struct_type) { + Printv(call, "*(*C.", ct, ")(unsafe.Pointer(&", ivar, "))", NULL); + } else { + Printv(call, "C.", ct, "(", ivar, ")", NULL); + } + Delete(ct); + } else { + Printv(call, ivar, NULL); + } p = nextParm(p); } - Printv(f_go_wrappers, ")\n", NULL); + Printv(call, ")", NULL); + if (cgo_flag) { + Printv(call, ")", NULL); + } + + Printv(f_go_wrappers, call, "\n", NULL); + + goargout(parms); + Printv(f_go_wrappers, "\treturn p\n", NULL); Printv(f_go_wrappers, "}\n\n", NULL); @@ -3031,7 +3758,26 @@ private: Printv(action, ");", NULL); Setattr(n, "wrap:action", action); - if (!gccgo_flag) { + if (cgo_flag) { + cgoWrapperInfo info; + + info.n = n; + info.go_name = func_name; + info.overname = overname; + info.wname = wname; + info.base = NULL; + info.parms = first_parm; + info.result = result; + info.is_static = false; + info.receiver = NULL; + info.is_constructor = true; + info.is_destructor = false; + + int r = cgoGccWrapper(&info); + if (r != SWIG_OK) { + return r; + } + } else if (!gccgo_flag) { int r = gcFunctionWrapper(wname); if (r != SWIG_OK) { return r; @@ -3094,6 +3840,7 @@ private: Delete(go_type_name); Delete(director_struct_name); Delete(fn_name); + Delete(fn_with_over_name); Delete(func_name); Delete(func_with_over_name); Delete(wname); @@ -3176,16 +3923,14 @@ private: Printv(director_sig, "\n", NULL); Printv(director_sig, "{\n", NULL); - if (!is_ignored) { - makeDirectorDestructorWrapper(go_name, director_sig); - - Printv(f_c_directors, " delete swig_mem;\n", NULL); - - Printv(f_go_wrappers, "func ", go_name, "(p *", director_struct_name, ") {\n", NULL); - Printv(f_go_wrappers, "\tp.", class_receiver, " = 0\n", NULL); - Printv(f_go_wrappers, "}\n\n", NULL); + if (is_ignored) { + Printv(f_c_directors, director_sig, NULL); + } else { + makeDirectorDestructorWrapper(go_name, director_struct_name, director_sig); } + Printv(f_c_directors, " delete swig_mem;\n", NULL); + Printv(f_c_directors, "}\n\n", NULL); Delete(director_sig); @@ -3204,20 +3949,34 @@ private: * unfinished. * ------------------------------------------------------------ */ - void makeDirectorDestructorWrapper(String *go_name, String *director_sig) { + void makeDirectorDestructorWrapper(String *go_name, String *director_struct_name, String *director_sig) { + if (cgo_flag) { + makeCgoDirectorDestructorWrapper(go_name, director_struct_name, director_sig); + return; + } + + Printv(f_go_wrappers, "func ", go_name, "(c int) {\n", NULL); + if (gccgo_flag) { + Printv(f_go_wrappers, "\tSwigCgocallBack()\n", NULL); + Printv(f_go_wrappers, "\tdefer SwigCgocallBackDone()\n", NULL); + } + Printv(f_go_wrappers, "\tswigDirectorLookup(c).(*", director_struct_name, ").", class_receiver, " = 0\n", NULL); + Printv(f_go_wrappers, "\tswigDirectorDelete(c)\n", NULL); + Printv(f_go_wrappers, "}\n\n", NULL); + String *wname = NewString("_swiggo_wrap_DeleteDirector_"); Append(wname, class_name); if (!gccgo_flag) { Printv(f_c_directors, "extern \"C\" void ", wname, "(void*, int);\n", NULL); } else { - Printv(f_c_directors, "extern \"C\" void ", wname, "(void*) __asm__(\"", go_prefix, ".", go_name, "\");\n", NULL); + Printv(f_c_directors, "extern \"C\" void ", wname, "(intgo) __asm__(\"", go_prefix, ".", go_name, "\");\n", NULL); } Printv(f_c_directors, director_sig, NULL); if (!gccgo_flag) { - Printv(f_c_directors, " struct { void *p; } a;\n", NULL); + Printv(f_c_directors, " struct { intgo p; } a;\n", NULL); Printv(f_c_directors, " a.p = go_val;\n", NULL); Printv(f_c_directors, " crosscall2(", wname, ", &a, (int) sizeof a);\n", NULL); @@ -3237,6 +3996,28 @@ private: Delete(wname); } + /* ------------------------------------------------------------ + * makeCgoDirectorDestructorWrapper + * + * When using cgo, emit the function wrapper for the destructor of a + * director class. + * ------------------------------------------------------------ */ + + void makeCgoDirectorDestructorWrapper(String *go_name, String *director_struct_name, String *director_sig) { + String *wname = Copy(go_name); + Append(wname, unique_id); + + Printv(f_go_wrappers, "//export ", wname, "\n", NULL); + Printv(f_go_wrappers, "func ", wname, "(c int) {\n", NULL); + Printv(f_go_wrappers, "\tswigDirectorLookup(c).(*", director_struct_name, ").", class_receiver, " = 0\n", NULL); + Printv(f_go_wrappers, "\tswigDirectorDelete(c)\n", NULL); + Printv(f_go_wrappers, "}\n\n", NULL); + + Printv(f_c_directors, "extern \"C\" void ", wname, "(intgo);\n", NULL); + Printv(f_c_directors, director_sig, NULL); + Printv(f_c_directors, " ", wname, "(go_val);\n", NULL); + } + /* ------------------------------------------------------------ * classDirectorMethod * @@ -3392,6 +4173,9 @@ private: if (overname) { Append(callback_name, overname); } + if (cgo_flag) { + Append(callback_name, unique_id); + } String *upcall_name = Copy(director_struct_name); Append(upcall_name, "_upcall_"); @@ -3450,43 +4234,68 @@ private: Printv(f_go_wrappers, "}\n\n", NULL); if (!GetFlag(n, "abstract")) { - // Declare the upcall function, which calls the method on the - // parent class. + if (cgo_flag) { + Printv(f_cgo_comment, "extern ", NULL); - if (!gccgo_flag) { - Printv(f_go_wrappers, "var ", upcall_wname, " unsafe.Pointer\n\n", NULL); + if (SwigType_type(result) == T_VOID) { + Printv(f_cgo_comment, "void", NULL); + } else { + bool c_struct_type; + String *ret_type = cgoTypeForGoValue(n, result, &c_struct_type); + Printv(f_cgo_comment, ret_type, NULL); + Delete(ret_type); + } + + Printv(f_cgo_comment, " ", upcall_wname, "(uintptr_t", NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, Getattr(p, "type"), &c_struct_type); + Printv(f_cgo_comment, ", ", ct, " ", Getattr(p, "lname"), NULL); + p = nextParm(p); + } + Printv(f_cgo_comment, ");\n", NULL); } else { - Printv(f_go_wrappers, "//extern ", go_prefix, "_", upcall_wname, "\n", NULL); + // Declare the upcall function, which calls the method on + // the parent class. + + if (!gccgo_flag) { + Printv(f_go_wrappers, "var ", upcall_wname, " unsafe.Pointer\n\n", NULL); + } else { + Printv(f_go_wrappers, "//extern ", go_prefix, "_", upcall_wname, "\n", NULL); + } + + Printv(f_go_wrappers, "func ", upcall_gc_name, "(_swig_ptr ", go_type_name, NULL); + + p = parms; + for (int i = 0; i < parm_count; ++i) { + p = getParm(p); + String *tm = goWrapperType(p, Getattr(p, "type"), false); + Printv(f_go_wrappers, ", _ ", tm, NULL); + Delete(tm); + p = nextParm(p); + } + + Printv(f_go_wrappers, ")", NULL); + + if (SwigType_type(result) != T_VOID) { + String *tm = goWrapperType(n, result, true); + Printv(f_go_wrappers, " (_swig_ret ", tm, ")", NULL); + Delete(tm); + } + + if (!gccgo_flag) { + Printv(f_go_wrappers, " {\n", NULL); + Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&_swig_ptr))\n", NULL); + Printv(f_go_wrappers, "\t_cgo_runtime_cgocall(", upcall_wname, ", _swig_p)\n", NULL); + Printv(f_go_wrappers, "\treturn\n", NULL); + Printv(f_go_wrappers, "}", NULL); + } + + Printv(f_go_wrappers, "\n\n", NULL); } - - Printv(f_go_wrappers, "func ", upcall_gc_name, "(_swig_ptr ", go_type_name, NULL); - - p = parms; - for (int i = 0; i < parm_count; ++i) { - p = getParm(p); - String *tm = goWrapperType(p, Getattr(p, "type"), false); - Printv(f_go_wrappers, ", _ ", tm, NULL); - Delete(tm); - p = nextParm(p); - } - - Printv(f_go_wrappers, ")", NULL); - - if (SwigType_type(result) != T_VOID) { - String *tm = goWrapperType(n, result, true); - Printv(f_go_wrappers, " (_swig_ret ", tm, ")", NULL); - Delete(tm); - } - - if (!gccgo_flag) { - Printv(f_go_wrappers, " {\n", NULL); - Printv(f_go_wrappers, "\t_swig_p := uintptr(unsafe.Pointer(&_swig_ptr))\n", NULL); - Printv(f_go_wrappers, "\t_cgo_runtime_cgocall(", upcall_wname, ", _swig_p)\n", NULL); - Printv(f_go_wrappers, "\treturn\n", NULL); - Printv(f_go_wrappers, "}", NULL); - } - - Printv(f_go_wrappers, "\n\n", NULL); } // Define the method on the director class in Go. @@ -3542,14 +4351,26 @@ private: if (GetFlag(n, "abstract")) { Printv(f_go_wrappers, "\tpanic(\"call to pure virtual method\")\n", NULL); } else { + String *ret_type = NULL; + bool memcpy_ret = false; + String *wt = NULL; bool has_goout = false; String *goout = NULL; if (SwigType_type(result) != T_VOID) { - Printv(f_go_wrappers, "\tvar swig_r ", goImType(n, result), "\n", NULL); + ret_type = goImType(n, result); + Printv(f_go_wrappers, "\tvar swig_r ", ret_type, "\n", NULL); goout = goTypemapLookup("goout", n, "swig_r"); if (goout) { has_goout = true; } + + if (cgo_flag) { + bool c_struct_type; + Delete(cgoTypeForGoValue(n, result, &c_struct_type)); + if (c_struct_type) { + memcpy_ret = true; + } + } } p = parms; @@ -3563,7 +4384,7 @@ private: String *call = NewString(""); - if (gccgo_flag) { + if (gccgo_flag && !cgo_flag) { if (has_goout) { Printv(call, "\tfunc() {\n", NULL); } @@ -3573,9 +4394,33 @@ private: Printv(call, "\t", NULL); if (SwigType_type(result) != T_VOID) { - Printv(call, "swig_r = ", NULL); + if (memcpy_ret) { + Printv(call, "swig_r_p := ", NULL); + } else { + Printv(call, "swig_r = ", NULL); + if (cgo_flag) { + Printv(call, "(", ret_type, ")(", NULL); + } + } + if (cgo_flag && goTypeIsInterface(n, result)) { + wt = goWrapperType(n, result, true); + Printv(call, "(", wt, ")(", NULL); + } + } + + if (cgo_flag) { + Printv(call, "C.", upcall_wname, NULL); + } else { + Printv(call, upcall_gc_name, NULL); + } + Printv(call, "(", NULL); + if (cgo_flag) { + Printv(call, "C.uintptr_t(", NULL); + } + Printv(call, "swig_p.", go_type_name, NULL); + if (cgo_flag) { + Printv(call, ")", NULL); } - Printv(call, upcall_gc_name, "(swig_p.", go_type_name, NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -3585,42 +4430,71 @@ private: String *ln = Getattr(p, "lname"); + String *ivar = NewStringf("_swig_i_%d", i); + // This is an ordinary call from Go to C++, so adjust using // the goin typemap. String *goin = goGetattr(p, "tmap:goin"); if (goin == NULL) { - Printv(call, ln, NULL); + Printv(f_go_wrappers, "\t", ivar, " := ", ln, NULL); if (goTypeIsInterface(p, pt)) { - Printv(call, ".Swigcptr()", NULL); + Printv(f_go_wrappers, ".Swigcptr()", NULL); } - Setattr(p, "emit:goinput", ln); + Printv(f_go_wrappers, "\n", NULL); } else { - String *ivar = NewString(""); - Printf(ivar, "_swig_i_%d", i); String *itm = goImType(p, pt); - Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, NULL); + Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, "\n", NULL); goin = Copy(goin); Replaceall(goin, "$input", ln); Replaceall(goin, "$result", ivar); Printv(f_go_wrappers, goin, NULL); Delete(goin); + } + + Setattr(p, "emit:goinput", ivar); + + if (cgo_flag) { + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, pt, &c_struct_type); + if (c_struct_type) { + Printv(call, "*(*C.", ct, ")(unsafe.Pointer(&", ivar, "))", NULL); + } else { + Printv(call, "C.", ct, "(", ivar, ")", NULL); + } + } else { Printv(call, ivar, NULL); - Setattr(p, "emit:goinput", ivar); } p = nextParm(p); } - Printv(call, ")\n", NULL); + Printv(call, ")", NULL); - if (gccgo_flag && has_goout) { - Printv(call, "\t}()\n", NULL); + if (gccgo_flag && !cgo_flag && has_goout) { + Printv(call, "\n\t}()", NULL); } + if (cgo_flag) { + if (wt) { + // Close the type conversion to the wrapper type. + Printv(call, ")", NULL); + } + if (SwigType_type(result) != T_VOID && !memcpy_ret) { + // Close the type conversion of the return value. + Printv(call, ")", NULL); + } + } + + Printv(call, "\n", NULL); + Printv(f_go_wrappers, call, NULL); Delete(call); - goargout(parms, parm_count); + if (memcpy_ret) { + Printv(f_go_wrappers, "\tswig_r = *(*", ret_type, ")(unsafe.Pointer(&swig_r_p))\n", NULL); + } + + goargout(parms); if (SwigType_type(result) != T_VOID) { if (goout == NULL) { @@ -3634,6 +4508,13 @@ private: Printv(f_go_wrappers, "\treturn swig_r_1\n", NULL); } } + + if (ret_type) { + Delete(ret_type); + } + if (wt) { + Delete(wt); + } } Printv(f_go_wrappers, "}\n\n", NULL); @@ -3715,7 +4596,26 @@ private: Printv(action, ");", NULL); Setattr(n, "wrap:action", action); - if (!gccgo_flag) { + if (cgo_flag) { + cgoWrapperInfo info; + + info.n = n; + info.go_name = go_name; + info.overname = overname; + info.wname = upcall_wname; + info.base = NULL; + info.parms = first_parm; + info.result = result; + info.is_static = is_static; + info.receiver = NULL; + info.is_constructor = false; + info.is_destructor = false; + + int r = cgoGccWrapper(&info); + if (r != SWIG_OK) { + return r; + } + } else if (!gccgo_flag) { // Write the upcall wrapper function. This is compiled by gc // and calls the C++ function. int r = gcFunctionWrapper(upcall_wname); @@ -3766,15 +4666,27 @@ private: Printv(f_go_wrappers, " {\n", NULL); + String *ret_type = NULL; + bool memcpy_ret = false; + String *wt = NULL; String *goout = NULL; if (SwigType_type(result) != T_VOID) { - Printv(f_go_wrappers, "\tvar swig_r ", goImType(n, result), "\n", NULL); + ret_type = goImType(n, result); + Printv(f_go_wrappers, "\tvar swig_r ", ret_type, "\n", NULL); goout = goTypemapLookup("goout", n, "swig_r"); + + if (cgo_flag) { + bool c_struct_type; + Delete(cgoTypeForGoValue(n, result, &c_struct_type)); + if (c_struct_type) { + memcpy_ret = true; + } + } } String *call = NewString(""); - if (gccgo_flag) { + if (gccgo_flag && !cgo_flag) { if (goout != NULL) { Printv(call, "\tfunc() {\n", NULL); } @@ -3784,9 +4696,33 @@ private: Printv(call, "\t", NULL); if (SwigType_type(result) != T_VOID) { - Printv(call, "swig_r = ", NULL); + if (memcpy_ret) { + Printv(call, "swig_r_p := ", NULL); + } else { + Printv(call, "swig_r = ", NULL); + if (cgo_flag) { + Printv(call, "(", ret_type, ")(", NULL); + } + } + if (cgo_flag && goTypeIsInterface(n, result)) { + wt = goWrapperType(n, result, true); + Printv(call, "(", wt, ")(", NULL); + } + } + + if (cgo_flag) { + Printv(call, "C.", upcall_wname, NULL); + } else { + Printv(call, upcall_gc_name, NULL); + } + Printv(call, "(", NULL); + if (cgo_flag) { + Printv(call, "C.uintptr_t(", NULL); + } + Printv(call, "p.(*", director_struct_name, ").", go_type_name, NULL); + if (cgo_flag) { + Printv(call, ")", NULL); } - Printv(call, upcall_gc_name, "(p.(*", director_struct_name, ").", go_type_name, NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -3794,27 +4730,39 @@ private: p = getParm(p); SwigType *pt = Getattr(p, "type"); + String *ivar = NewStringf("_swig_i_%d", i); + String *ln = Copy(Getattr(p, "lname")); - if (goTypeIsInterface(p, pt)) { - Printv(ln, ".Swigcptr()", NULL); - } String *goin = goGetattr(p, "tmap:goin"); if (goin == NULL) { - Printv(call, ln, NULL); - Setattr(p, "emit:goinput", ln); + Printv(f_go_wrappers, "\t", ivar, " := ", ln, NULL); + if (goTypeIsInterface(p, pt)) { + Printv(f_go_wrappers, ".Swigcptr()", NULL); + } + Printv(f_go_wrappers, "\n", NULL); } else { - String *ivar = NewString(""); - Printf(ivar, "_swig_i_%d", i); String *itm = goImType(p, pt); - Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, NULL); + Printv(f_go_wrappers, "\tvar ", ivar, " ", itm, "\n", NULL); goin = Copy(goin); Replaceall(goin, "$input", ln); Replaceall(goin, "$result", ivar); Printv(f_go_wrappers, goin, NULL); Delete(goin); + } + + Setattr(p, "emit:goinput", ivar); + + if (cgo_flag) { + bool c_struct_type; + String *ct = cgoTypeForGoValue(p, pt, &c_struct_type); + if (c_struct_type) { + Printv(call, "*(*C.", ct, ")(unsafe.Pointer(&", ivar, "))", NULL); + } else { + Printv(call, "C.", ct, "(", ivar, ")", NULL); + } + } else { Printv(call, ivar, NULL); - Setattr(p, "emit:goinput", ivar); } Delete(ln); @@ -3822,16 +4770,33 @@ private: p = nextParm(p); } - Printv(call, ")\n", NULL); + Printv(call, ")", NULL); - if (gccgo_flag && goout != NULL) { - Printv(call, "\t}()\n", NULL); + if (gccgo_flag && !cgo_flag && goout != NULL) { + Printv(call, "\n\t}()", NULL); } + if (cgo_flag) { + if (wt) { + // Close the type conversion to the wrapper type. + Printv(call, ")", NULL); + } + if (SwigType_type(result) != T_VOID && !memcpy_ret) { + // Close the type conversion of the return value. + Printv(call, ")", NULL); + } + } + + Printv(call, "\n", NULL); + Printv(f_go_wrappers, call, NULL); Delete(call); - goargout(parms, parm_count); + if (memcpy_ret) { + Printv(f_go_wrappers, "\tswig_r = *(*", ret_type, ")(unsafe.Pointer(&swig_r_p))\n", NULL); + } + + goargout(parms); if (SwigType_type(result) != T_VOID) { if (goout == NULL) { @@ -3847,12 +4812,23 @@ private: } Printv(f_go_wrappers, "}\n\n", NULL); + + if (ret_type) { + Delete(ret_type); + } + if (wt) { + Delete(wt); + } } - // The Go function which invokes the method. This is called - // from by the C++ method on the director class. + // The Go function which invokes the method. This is called by + // the C++ method on the director class. - Printv(f_go_wrappers, "func ", callback_name, "(p *", director_struct_name, NULL); + if (cgo_flag) { + Printv(f_go_wrappers, "//export ", callback_name, "\n", NULL); + } + + Printv(f_go_wrappers, "func ", callback_name, "(swig_c int", NULL); p = parms; for (int i = 0; i < parm_count; ++i) { @@ -3897,7 +4873,7 @@ private: Printv(call, result_wrapper, "(", NULL); } } - Printv(call, "p.", go_with_over_name, "(", NULL); + Printv(call, "swig_p.", go_with_over_name, "(", NULL); String *goincode = NewString(""); @@ -3958,7 +4934,7 @@ private: } Printv(call, "\n", NULL); - if (gccgo_flag) { + if (gccgo_flag && !cgo_flag) { if (goout != NULL) { Printv(f_go_wrappers, "\tfunc() {\n", NULL); } @@ -3966,11 +4942,12 @@ private: Printv(f_go_wrappers, "\tdefer SwigCgocallBackDone()\n", NULL); } + Printv(f_go_wrappers, "\tswig_p := swigDirectorLookup(swig_c).(*", director_struct_name, ")\n", NULL); Printv(f_go_wrappers, goincode, NULL); Printv(f_go_wrappers, call, NULL); Delete(call); - if (gccgo_flag && goout != NULL) { + if (gccgo_flag && !cgo_flag && goout != NULL) { Printv(f_go_wrappers, "\t}()\n", NULL); } @@ -4049,6 +5026,7 @@ private: Delete(go_type_name); Delete(director_struct_name); Delete(interface_name); + Delete(callback_name); Delete(upcall_name); Delete(go_name); DelWrapper(w); @@ -4062,6 +5040,11 @@ private: * Emit the function wrapper for a director method. * ------------------------------------------------------------ */ void makeDirectorMethodWrapper(Node *n, Wrapper *w, String *callback_name) { + if (cgo_flag) { + makeCgoDirectorMethodWrapper(n, w, callback_name); + return; + } + ParmList *parms = Getattr(n, "wrap:parms"); SwigType *result = Getattr(n, "type"); @@ -4074,7 +5057,7 @@ private: Printv(f_c_directors, "extern \"C\" ", NULL); String *fnname = NewString(""); - Printv(fnname, callback_wname, "(void*", NULL); + Printv(fnname, callback_wname, "(int", NULL); Parm *p = parms; while (p) { @@ -4105,7 +5088,7 @@ private: if (!gccgo_flag) { Printv(w->code, " struct {\n", NULL); - Printv(w->code, " void *go_val;\n", NULL); + Printv(w->code, " intgo go_val;\n", NULL); Parm *p = parms; while (p) { @@ -4285,6 +5268,129 @@ private: Delete(callback_wname); } + /* ------------------------------------------------------------ + * makeDirectorMethodWrapper + * + * Emit the function wrapper for a director method for cgo. + * ------------------------------------------------------------ */ + + void makeCgoDirectorMethodWrapper(Node *n, Wrapper *w, String *callback_name) { + ParmList *parms = Getattr(n, "wrap:parms"); + SwigType *result = Getattr(n, "type"); + + Printv(f_c_directors, "extern \"C\" ", NULL); + + String *fnname = Copy(callback_name); + Append(fnname, "(int"); + + Parm *p = parms; + while (p) { + while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { + p = Getattr(p, "tmap:directorin:next"); + } + String *cg = gcCTypeForGoValue(p, Getattr(p, "type"), Getattr(p, "lname")); + Printv(fnname, ", ", cg, NULL); + Delete(cg); + p = Getattr(p, "tmap:directorin:next"); + } + + Printv(fnname, ")", NULL); + + if (SwigType_type(result) == T_VOID) { + Printv(f_c_directors, "void ", fnname, NULL); + } else { + String *tm = gcCTypeForGoValue(n, result, fnname); + Printv(f_c_directors, tm, NULL); + Delete(tm); + } + + Delete(fnname); + + Printv(f_c_directors, ";\n", NULL); + + if (SwigType_type(result) != T_VOID) { + String *r = NewString(Swig_cresult_name()); + String *tm = gcCTypeForGoValue(n, result, r); + Wrapper_add_local(w, r, tm); + Delete(tm); + Delete(r); + } + + String *args = NewString(""); + + p = parms; + while (p) { + while (checkAttribute(p, "tmap:directorin:numinputs", "0")) { + p = Getattr(p, "tmap:directorin:next"); + } + + String *pn = NewString("swig_"); + Append(pn, Getattr(p, "lname")); + Setattr(p, "emit:directorinput", pn); + + String *tm = gcCTypeForGoValue(p, Getattr(p, "type"), pn); + Wrapper_add_local(w, pn, tm); + Delete(tm); + + tm = Getattr(p, "tmap:directorin"); + if (!tm) { + Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, + line_number, "Unable to use type %s as director method argument\n", SwigType_str(Getattr(p, "type"), 0)); + } else { + tm = Copy(tm); + Replaceall(tm, "$input", pn); + Replaceall(tm, "$owner", 0); + Printv(w->code, " ", tm, "\n", NULL); + Delete(tm); + + Printv(args, ", ", pn, NULL); + } + + p = Getattr(p, "tmap:directorin:next"); + } + + Printv(w->code, " ", NULL); + if (SwigType_type(result) != T_VOID) { + Printv(w->code, Swig_cresult_name(), " = ", NULL); + } + Printv(w->code, callback_name, "(go_val", args, ");\n", NULL); + + /* Marshal outputs */ + for (p = parms; p; ) { + String *tm; + if ((tm = Getattr(p, "tmap:directorargout"))) { + tm = Copy(tm); + Replaceall(tm, "$result", "jresult"); + Replaceall(tm, "$input", Getattr(p, "emit:directorinput")); + Printv(w->code, tm, "\n", NULL); + Delete(tm); + p = Getattr(p, "tmap:directorargout:next"); + } else { + p = nextSibling(p); + } + } + + if (SwigType_type(result) != T_VOID) { + String *result_str = NewString("c_result"); + String *tm = Swig_typemap_lookup("directorout", n, result_str, NULL); + if (!tm) { + Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number, + "Unable to use type %s as director method result\n", SwigType_str(result, 0)); + } else { + tm = Copy(tm); + Replaceall(tm, "$input", Swig_cresult_name()); + Replaceall(tm, "$result", "c_result"); + Printv(w->code, " ", tm, "\n", NULL); + String *retstr = SwigType_rcaststr(result, "c_result"); + Printv(w->code, " return ", retstr, ";\n", NULL); + Delete(retstr); + Delete(tm); + } + Delete(result_str); + } + } + + /* ------------------------------------------------------------ * classDirectorEnd * @@ -4295,7 +5401,7 @@ private: (void) n; Printv(f_c_directors_h, " private:\n", NULL); - Printv(f_c_directors_h, " void *go_val;\n", NULL); + Printv(f_c_directors_h, " intgo go_val;\n", NULL); Printv(f_c_directors_h, " Swig_memory *swig_mem;\n", NULL); Printv(f_c_directors_h, "};\n\n", NULL); @@ -4543,9 +5649,9 @@ private: break; } - // If all the wrappers have the same type in this position, + // If all the overloads have the same type in this position, // we can omit the check. - SwigType *tm = goWrapperType(pj, Getattr(pj, "type"), true); + SwigType *tm = goOverloadType(pj, Getattr(pj, "type")); bool emitcheck = false; for (int k = 0; k < Len(coll) && !emitcheck; ++k) { Node *nk = Getitem(coll, k); @@ -4567,7 +5673,7 @@ private: break; } if (l == j) { - SwigType *tml = goWrapperType(pl, Getattr(pl, "type"), true); + SwigType *tml = goOverloadType(pl, Getattr(pl, "type")); if (Cmp(tm, tml) != 0) { emitcheck = true; } @@ -4585,7 +5691,7 @@ private: } fn = i + 1; - Printf(f_go_wrappers, "\t\tif _, ok := a[%d].(%s); !ok {\n", j, goType(pj, Getattr(pj, "type"))); + Printf(f_go_wrappers, "\t\tif _, ok := a[%d].(%s); !ok {\n", j, tm); Printf(f_go_wrappers, "\t\t\tgoto check_%d\n", fn); Printv(f_go_wrappers, "\t\t}\n", NULL); } @@ -5096,7 +6202,7 @@ private: Setattr(undefined_types, t, t); } else { String *nw = NewString(""); - Printv(nw, Getattr(cnmod, "name"), ".", ret, NULL); + Printv(nw, getModuleName(Getattr(cnmod, "name")), ".", ret, NULL); Delete(ret); ret = nw; } @@ -5205,6 +6311,118 @@ private: return ret; } + /* ---------------------------------------------------------------------- + * cgoTypeForGoValue() + * + * Given a SWIG type, return a string for the C type to use for the + * cgo wrapper code. This always returns a simple identifier, since + * it is used in Go code as C.name. + * + * This sets *c_struct_type if the C type uses a struct where the Go + * type uses a simple type. This is true for strings and slices. + * When this is true the Go code has to jump through unsafe hoops to + * pass the type checker. + * ---------------------------------------------------------------------- */ + + String *cgoTypeForGoValue(Node *n, SwigType *type, bool *c_struct_type) { + *c_struct_type = false; + + bool is_interface; + String *go_type = goTypeWithInfo(n, type, true, &is_interface); + if (is_interface) { + Delete(go_type); + return NewString("uintptr_t"); + } + if (Strcmp(go_type, "uintptr") == 0) { + Delete(go_type); + return NewString("uintptr_t"); + } + if (((char*)Char(go_type))[0] == '*') { + // Treat all pointers as void*. There is no meaningful type + // checking going on here anyhow, and that lets us avoid + // worrying about defining the base type of the pointer. + Delete(go_type); + return NewString("swig_voidp"); + } + + // Check for some Go types that are really pointers under the covers. + bool is_hidden_pointer = Strncmp(go_type, "func(", 5) == 0 || Strncmp(go_type, "map[", 4) == 0 || Strncmp(go_type, "chan ", 5) == 0; + + Delete(go_type); + + String *ct = Getattr(n, "emit:cgotype"); + if (ct) { + *c_struct_type = Getattr(n, "emit:cgotypestruct") ? true : false; + return Copy(ct); + } + + String *t = Copy(type); + if (SwigType_isarray(t)) { + SwigType_del_array(t); + SwigType_add_pointer(t); + } + + bool add_typedef = true; + + static int count; + ++count; + ct = NewStringf("swig_type_%d", count); + + String *gct = gcCTypeForGoValue(n, t, ct); + Delete(t); + + if (Strncmp(gct, "_gostring_", 10) == 0 || Strncmp(gct, "_goslice_", 9) == 0) { + *c_struct_type = true; + Setattr(n, "emit:cgotypestruct", type); + } else { + char *p = Strstr(gct, ct); + if (p != NULL && p > (char*)Char(gct) && p[-1] == '*' && p[Len(ct)] == '\0') { + // Treat all pointers as void*. See above. + Delete(ct); + --count; + ct = NewString("swig_voidp"); + add_typedef = false; + if (is_hidden_pointer) { + // A Go type that is really a pointer, like func, map, chan, + // is being represented in C by a pointer. This is fine, + // but we have to memcpy the type rather than simply + // converting it. + *c_struct_type = true; + Setattr(n, "emit:cgotypestruct", type); + } + } + + if (Strncmp(gct, "bool ", 5) == 0) { + // Change the C++ type bool to the C type _Bool. + Replace(gct, "bool", "_Bool", DOH_REPLACE_FIRST); + } + if (Strncmp(gct, "intgo ", 6) == 0) { + // We #define intgo to swig_intgo for the cgo comment. + Replace(gct, "intgo", "swig_intgo", DOH_REPLACE_FIRST); + } + p = Strstr(gct, ct); + if (p != NULL && p > (char*)Char(gct) && p[-1] == ' ' && p[Len(ct)] == '\0') { + String *q = NewStringWithSize(gct, Len(gct) - Len(ct) - 1); + if (validIdentifier(q)) { + // This is a simple type name, and we can use it directly. + Delete(ct); + --count; + ct = q; + add_typedef = false; + } + } + } + if (add_typedef) { + Printv(f_cgo_comment_typedefs, "typedef ", gct, ";\n", NULL); + } + + Setattr(n, "emit:cgotype", ct); + + Delete(gct); + + return Copy(ct); + } + /* ---------------------------------------------------------------------- * goWrapperType() * @@ -5247,6 +6465,46 @@ private: return ret; } + /* ---------------------------------------------------------------------- + * goOverloadType() + * + * Given a type, return the Go type to use when dispatching of + * overloaded functions. This is normally just the usual Go type. + * However, for a C++ class, the usual Go type is an interface type. + * And if that interface type represents a C++ type that SWIG does + * not know about, then the interface type generated for any C++ + * class will match that interface. So for that case, we match on + * the underlying integer type. + * + * It has to work this way so that we can handle a derived type of a + * %ignore'd type. It's unlikely that anybody will have a value of + * an undefined type, but we support it because it worked in the + * past. + * ---------------------------------------------------------------------- */ + + String *goOverloadType(Node *n, SwigType *type) { + SwigType *ty = SwigType_typedef_resolve_all(type); + while (true) { + if (SwigType_ispointer(ty)) { + SwigType_del_pointer(ty); + } else if (SwigType_isarray(ty)) { + SwigType_del_array(ty); + } else if (SwigType_isreference(ty)) { + SwigType_del_reference(ty); + } else if (SwigType_isqualifier(ty)) { + SwigType_del_qualifier(ty); + } else { + break; + } + } + + if (Getattr(undefined_types, ty) && !Getattr(defined_types, ty)) { + return goWrapperType(n, type, true); + } + + return goType(n, type); + } + /* ---------------------------------------------------------------------- * goCPointerType() * @@ -5282,7 +6540,7 @@ private: Append(ret, ex); } else { ret = NewString(""); - Printv(ret, Getattr(cnmod, "name"), ".Swigcptr", ex, NULL); + Printv(ret, getModuleName(Getattr(cnmod, "name")), ".Swigcptr", ex, NULL); } } Delete(ty); @@ -5317,6 +6575,7 @@ private: bool is_member = Strcmp(gt, "_swig_memberptr") == 0; bool is_complex64 = Strcmp(gt, "complex64") == 0; bool is_complex128 = Strcmp(gt, "complex128") == 0; + bool is_bool = false; bool is_int8 = false; bool is_int16 = false; bool is_int = Strcmp(gt, "int") == 0 || Strcmp(gt, "uint") == 0; @@ -5324,7 +6583,10 @@ private: bool is_int64 = false; bool is_float32 = false; bool is_float64 = false; - if ((n != NULL && Getattr(n, "tmap:gotype") != NULL) || hasGoTypemap(n, type)) { + + bool has_typemap = (n != NULL && Getattr(n, "tmap:gotype") != NULL) || hasGoTypemap(n, type); + if (has_typemap) { + is_bool = Strcmp(gt, "bool") == 0; is_int8 = Strcmp(gt, "int8") == 0 || Strcmp(gt, "uint8") == 0 || Strcmp(gt, "byte") == 0; is_int16 = Strcmp(gt, "int16") == 0 || Strcmp(gt, "uint16") == 0; is_int32 = Strcmp(gt, "int32") == 0 || Strcmp(gt, "uint32") == 0; @@ -5373,7 +6635,7 @@ private: return ret; } else { SwigType *t = SwigType_typedef_resolve_all(type); - if (SwigType_isreference(t)) { + if (!has_typemap && SwigType_isreference(t)) { // A const reference to a known type, or to a pointer, is not // mapped to a pointer. SwigType_del_reference(t); @@ -5411,7 +6673,9 @@ private: } Delete(t); - if (is_int8) { + if (is_bool) { + ret = NewString("bool "); + } else if (is_int8) { ret = NewString("char "); } else if (is_int16) { ret = NewString("short "); @@ -5432,7 +6696,7 @@ private: } Append(ret, tail); - if (SwigType_isreference(type)) { + if (!has_typemap && SwigType_isreference(type)) { Append(ret, "* "); } Append(ret, name); @@ -5603,6 +6867,21 @@ private: return ret; } + /* ---------------------------------------------------------------------- + * getModuleName + * + * Return the name of a module. This is different from module path: + * "some/path/to/module" -> "module". + * ---------------------------------------------------------------------- */ + + String *getModuleName(String *module_path) { + char *suffix = strrchr(Char(module_path), '/'); + if (suffix == NULL) { + return module_path; + } + return Str(suffix + 1); + } + }; /* class GO */ /* ----------------------------------------------------------------------------- @@ -5623,6 +6902,7 @@ extern "C" Language *swig_go(void) { // Usage message. const char * const GO::usage = "\ Go Options (available with -go)\n\ + -cgo - Generate cgo input files\n\ -gccgo - Generate code for gccgo rather than 6g/8g\n\ -go-pkgpath

    - Like gccgo -fgo-pkgpath option\n\ -go-prefix

    - Like gccgo -fgo-prefix option\n\ diff --git a/Source/Modules/java.cxx b/Source/Modules/java.cxx index dcbc2718c..7af93b589 100644 --- a/Source/Modules/java.cxx +++ b/Source/Modules/java.cxx @@ -508,6 +508,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } // Generate the intermediary class @@ -1892,7 +1893,7 @@ public: } else if (Len(pure_baseclass) > 0 && Len(baseclass) > 0) { Swig_warning(WARN_JAVA_MULTIPLE_INHERITANCE, Getfile(n), Getline(n), "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Java. " - "Perhaps you need one of the 'replace' or 'notderived' attributes in the csbase typemap?\n", typemap_lookup_type, pure_baseclass); + "Perhaps you need one of the 'replace' or 'notderived' attributes in the javabase typemap?\n", typemap_lookup_type, pure_baseclass); } // Pure Java interfaces @@ -3569,7 +3570,7 @@ public: Printf(f_runtime, "namespace Swig {\n"); Printf(f_runtime, " namespace {\n"); Printf(f_runtime, " jclass jclass_%s = NULL;\n", imclass_name); - Printf(f_runtime, " jmethodID director_methids[%d];\n", n_methods); + Printf(f_runtime, " jmethodID director_method_ids[%d];\n", n_methods); Printf(f_runtime, " }\n"); Printf(f_runtime, "}\n"); @@ -3586,8 +3587,8 @@ public: Printf(w->code, "Swig::jclass_%s = (jclass) jenv->NewGlobalRef(jcls);\n", imclass_name); Printf(w->code, "if (!Swig::jclass_%s) return;\n", imclass_name); Printf(w->code, "for (i = 0; i < (int) (sizeof(methods)/sizeof(methods[0])); ++i) {\n"); - Printf(w->code, " Swig::director_methids[i] = jenv->GetStaticMethodID(jcls, methods[i].method, methods[i].signature);\n"); - Printf(w->code, " if (!Swig::director_methids[i]) return;\n"); + Printf(w->code, " Swig::director_method_ids[i] = jenv->GetStaticMethodID(jcls, methods[i].method, methods[i].signature);\n"); + Printf(w->code, " if (!Swig::director_method_ids[i]) return;\n"); Printf(w->code, "}\n"); Printf(w->code, "}\n"); @@ -4241,7 +4242,7 @@ public: if (!is_void) Printf(w->code, "jresult = (%s) ", c_ret_type); - Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_methids[%s], %s);\n", methop, imclass_name, methid, jupcall_args); + Printf(w->code, "jenv->%s(Swig::jclass_%s, Swig::director_method_ids[%s], %s);\n", methop, imclass_name, methid, jupcall_args); // Generate code to handle any Java exception thrown by director delegation directorExceptHandler(n, catches_list ? catches_list : throw_parm_list, w); @@ -4630,7 +4631,7 @@ public: Printf(f_directors_h, " return (n < %d ? swig_override[n] : false);\n", n_methods); Printf(f_directors_h, " }\n"); Printf(f_directors_h, "protected:\n"); - Printf(f_directors_h, " bool swig_override[%d];\n", n_methods); + Printf(f_directors_h, " Swig::BoolArray<%d> swig_override;\n", n_methods); /* Emit the code to look up the class's methods, initialize the override array */ diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 7f92ffead..8869c30fb 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -943,7 +943,7 @@ int Language::cDeclaration(Node *n) { } if (!validIdentifier(symname)) { - Swig_warning(WARN_LANG_IDENTIFIER, input_file, line_number, "Can't wrap '%s' unless renamed to a valid identifier.\n", symname); + Swig_warning(WARN_LANG_IDENTIFIER, input_file, line_number, "Can't wrap '%s' unless renamed to a valid identifier.\n", SwigType_namestr(symname)); return SWIG_NOWRAP; } @@ -3699,14 +3699,26 @@ int Language::abstractClassTest(Node *n) { return 0; if (Getattr(n, "allocate:nonew")) return 1; + + // A class cannot be instantiated if one of its bases has a private destructor + // Note that if the above does not hold the class can be instantiated if its own destructor is private + List *bases = Getattr(n, "bases"); + if (bases) { + for (int i = 0; i < Len(bases); i++) { + Node *b = Getitem(bases, i); + if (GetFlag(b, "allocate:private_destructor")) + return 1; + } + } + /* now check for the rest */ List *abstracts = Getattr(n, "abstracts"); if (!abstracts) return 0; int labs = Len(abstracts); #ifdef SWIG_DEBUG - List *bases = Getattr(n, "allbases"); - Printf(stderr, "testing %s %d %d\n", Getattr(n, "name"), labs, Len(bases)); + List *allbases = Getattr(n, "allbases"); + Printf(stderr, "testing %s %d %d\n", Getattr(n, "name"), labs, Len(allbases)); #endif if (!labs) return 0; /*strange, but need to be fixed */ diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index aa0d7d589..632a001ac 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -131,8 +131,8 @@ static const char *usage3 = (const char *) "\ static const char *usage4 = (const char *) "\ -O - Enable the optimization options: \n\ -fastdispatch -fvirtual \n\ - -o - Set name of the output file to \n\ - -oh - Set name of the output header file to \n\ + -o - Set name of C/C++ output file to \n\ + -oh - Set name of C++ output header file for directors to \n\ -outcurrentdir - Set default output dir to current dir instead of input file's path\n\ -outdir

    - Set language specific files output directory to \n\ -pcreversion - Display PCRE version information\n\ @@ -595,7 +595,7 @@ void SWIG_getoptions(int argc, char *argv[]) { Swig_filename_correct(outfile_name); if (!outfile_name_h || !dependencies_file) { char *ext = strrchr(Char(outfile_name), '.'); - String *basename = ext ? NewStringWithSize(Char(outfile_name), Char(ext) - Char(outfile_name)) : NewString(outfile_name); + String *basename = ext ? NewStringWithSize(Char(outfile_name), (int)(Char(ext) - Char(outfile_name))) : NewString(outfile_name); if (!dependencies_file) { dependencies_file = NewStringf("%s.%s", basename, depends_extension); } @@ -899,7 +899,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { String *vers = NewString("SWIG_VERSION 0x"); int count = 0; while (token) { - int len = strlen(token); + int len = (int)strlen(token); assert(len == 1 || len == 2); Printf(vers, "%s%s", (len == 1) ? "0" : "", token); token = strtok(NULL, "."); @@ -1221,7 +1221,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { Printf(stdout, "debug-top stage 3\n"); Swig_print_tree(top); } - if (dump_module & STAGE3) { + if (top && (dump_module & STAGE3)) { Printf(stdout, "debug-module stage 3\n"); Swig_print_tree(Getattr(top, "module")); } @@ -1230,7 +1230,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { Printf(stdout, "Generating wrappers...\n"); } - if (dump_classes) { + if (top && dump_classes) { Hash *classes = Getattr(top, "classes"); if (classes) { Printf(stdout, "Classes\n"); diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index c4ab6a8ea..0fcd5ad18 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -340,6 +340,8 @@ static void insertNodeAfter(Node *n, Node *c) { } void Swig_nested_name_unnamed_c_structs(Node *n) { + if (!n) + return; if (!classhash) classhash = Getattr(n, "classes"); Node *c = firstChild(n); @@ -427,6 +429,8 @@ static void remove_outer_class_reference(Node *n) { } void Swig_nested_process_classes(Node *n) { + if (!n) + return; Node *c = firstChild(n); while (c) { Node *next = nextSibling(c); diff --git a/Source/Modules/ocaml.cxx b/Source/Modules/ocaml.cxx index ac73c1f0c..87b430b02 100644 --- a/Source/Modules/ocaml.cxx +++ b/Source/Modules/ocaml.cxx @@ -325,6 +325,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } @@ -619,9 +620,9 @@ public: } /* if the object is a director, and the method call originated from its - * underlying python object, resolve the call by going up the c++ - * inheritance chain. otherwise try to resolve the method in python. - * without this check an infinite loop is set up between the director and + * underlying ocaml object, resolve the call by going up the c++ + * inheritance chain. otherwise try to resolve the method in ocaml. + * without this check an infinite loop is set up between the director and * shadow class method calls. */ @@ -989,7 +990,7 @@ public: find_marker += strlen("(*Stream:"); if (next) { - int num_chars = next - find_marker; + int num_chars = (int)(next - find_marker); String *stream_name = NewString(find_marker); Delslice(stream_name, num_chars, Len(stream_name)); File *fout = Swig_filebyname(stream_name); @@ -1000,7 +1001,7 @@ public: if (!following) following = next + strlen(next); String *chunk = NewString(next); - Delslice(chunk, following - next, Len(chunk)); + Delslice(chunk, (int)(following - next), Len(chunk)); Printv(fout, chunk, NIL); } } diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index 236598c1f..e5f18cae8 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -228,8 +228,10 @@ public: if (Len(docs)) emit_doc_texinfo(); - if (directorsEnabled()) + if (directorsEnabled()) { + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); + } Printf(f_init, "return true;\n}\n"); Printf(s_global_tab, "{0,0,0,0,0}\n};\n"); @@ -1385,7 +1387,7 @@ public: SwigType_namestr(name)); } } else { - // attach typemaps to arguments (C/C++ -> Python) + // attach typemaps to arguments (C/C++ -> Octave) String *parse_args = NewString(""); Swig_director_parms_fixup(l); diff --git a/Source/Modules/overload.cxx b/Source/Modules/overload.cxx index e95ef557f..dd3ca4972 100644 --- a/Source/Modules/overload.cxx +++ b/Source/Modules/overload.cxx @@ -158,12 +158,12 @@ List *Swig_overload_rank(Node *n, bool script_lang_wrapping) { String *t2 = Getattr(p2, "tmap:typecheck:precedence"); if ((!t1) && (!nodes[i].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n), - "Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[i].n), SwigType_str(Getattr(p1, "type"), 0)); nodes[i].error = 1; } else if ((!t2) && (!nodes[j].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n), - "Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[j].n), SwigType_str(Getattr(p2, "type"), 0)); nodes[j].error = 1; } diff --git a/Source/Modules/perl5.cxx b/Source/Modules/perl5.cxx index e1b0e69c6..979f96484 100644 --- a/Source/Modules/perl5.cxx +++ b/Source/Modules/perl5.cxx @@ -13,8 +13,6 @@ #include "swigmod.h" #include "cparse.h" -static int treduce = SWIG_cparse_template_reduce(0); - #include static const char *usage = "\ @@ -470,6 +468,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } @@ -2254,7 +2253,7 @@ public: if (SwigType_isreference(ptype)) { Insert(ppname, 0, "&"); } - /* if necessary, cast away const since Python doesn't support it! */ + /* if necessary, cast away const since Perl doesn't support it! */ if (SwigType_isconst(nptype)) { nonconst = NewStringf("nc_tmp_%s", pname); String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname); diff --git a/Source/Modules/php.cxx b/Source/Modules/php.cxx index e6105eb3e..37a8f9628 100644 --- a/Source/Modules/php.cxx +++ b/Source/Modules/php.cxx @@ -190,7 +190,7 @@ class PHP : public Language { p = strchr(p, '"'); if (p) { ++p; - Insert(action, p - Char(action), " TSRMLS_CC"); + Insert(action, (int)(p - Char(action)), " TSRMLS_CC"); } } } @@ -473,6 +473,7 @@ public: if (directorsEnabled()) { // Insert director runtime + Swig_insert_file("director_common.swg", s_header); Swig_insert_file("director.swg", s_header); } @@ -1721,7 +1722,7 @@ public: Printf(output, "\t\t\treturn new %s%s($r);\n", prefix, Getattr(classLookup(d), "sym:name")); } else { Printf(output, "\t\t\t$c = new stdClass();\n"); - Printf(output, "\t\t\t$c->"SWIG_PTR" = $r;\n"); + Printf(output, "\t\t\t$c->" SWIG_PTR " = $r;\n"); Printf(output, "\t\t\treturn $c;\n"); } Printf(output, "\t\t}\n\t\treturn $r;\n"); @@ -2423,7 +2424,7 @@ done: String *target = Swig_method_decl(0, decl, classname, parms, 0, 0); const char * p = Char(target); const char * comma = strchr(p, ','); - size_t ins = comma ? comma - p : Len(target) - 1; + int ins = comma ? (int)(comma - p) : Len(target) - 1; Insert(target, ins, " TSRMLS_DC"); call = Swig_csuperclass_call(0, basetype, superparms); @@ -2442,7 +2443,7 @@ done: String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); const char * p = Char(target); const char * comma = strchr(p, ','); - size_t ins = comma ? comma - p : Len(target) - 1; + int ins = comma ? (int)(comma - p) : Len(target) - 1; Insert(target, ins, " TSRMLS_DC"); Printf(f_directors_h, " %s;\n", target); diff --git a/Source/Modules/python.cxx b/Source/Modules/python.cxx index c1b2b1415..808d9a365 100644 --- a/Source/Modules/python.cxx +++ b/Source/Modules/python.cxx @@ -13,9 +13,6 @@ #include "swigmod.h" #include "cparse.h" - -static int treduce = SWIG_cparse_template_reduce(0); - #include #include #include @@ -993,6 +990,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } @@ -1212,7 +1210,7 @@ public: const char *py3_end1 = Strchr(rpkg, '.'); if (!py3_end1) py3_end1 = (Char(rpkg)) + Len(rpkg); - py3_rlen1 = py3_end1 - (Char(rpkg)); + py3_rlen1 = (int)(py3_end1 - Char(rpkg)); } else { rpkg = NewString(""); } @@ -1389,7 +1387,7 @@ public: * pythoncode() - Output python code into the shadow file * ------------------------------------------------------------ */ - String *pythoncode(String *code, const_String_or_char_ptr indent) { + String *pythoncode(String *code, const_String_or_char_ptr indent, String * file, int line) { String *out = NewString(""); String *temp; char *t; @@ -1407,38 +1405,91 @@ public: /* Split the input text into lines */ List *clist = SplitLines(temp); Delete(temp); - int initial = 0; - String *s = 0; - Iterator si; - /* Get the initial indentation */ - for (si = First(clist); si.item; si = Next(si)) { - s = si.item; - if (Len(s)) { - char *c = Char(s); - while (*c) { - if (!isspace(*c)) - break; - initial++; - c++; - } - if (*c && !isspace(*c)) { - break; - } else { - initial = 0; - } + // Line number within the pythoncode. + int py_line = 0; + + String * initial = 0; + Iterator si; + + /* Get the initial indentation. Skip lines which only contain whitespace + * and/or a comment, as the indentation of those doesn't matter: + * + * A logical line that contains only spaces, tabs, formfeeds and + * possibly a comment, is ignored (i.e., no NEWLINE token is + * generated). + * + * see: + * https://docs.python.org/2/reference/lexical_analysis.html#blank-lines + * https://docs.python.org/3/reference/lexical_analysis.html#blank-lines + */ + for (si = First(clist); si.item; si = Next(si), ++py_line) { + const char *c = Char(si.item); + int i; + for (i = 0; isspace((unsigned char)c[i]); i++) { + // Scan forward until we find a non-space (which may be a nul byte). } + char ch = c[i]; + if (ch && ch != '#') { + // Found a line with actual content. + initial = NewStringWithSize(c, i); + break; + } + if (ch) { + Printv(out, indent, c, NIL); + } + Putc('\n', out); } - while (si.item) { - s = si.item; - if (Len(s) > initial) { - char *c = Char(s); - c += initial; + + // Process remaining lines. + for ( ; si.item; si = Next(si), ++py_line) { + const char *c = Char(si.item); + // If no prefixed line was found, the above loop should have completed. + assert(initial); + + int i; + for (i = 0; isspace((unsigned char)c[i]); i++) { + // Scan forward until we find a non-space (which may be a nul byte). + } + char ch = c[i]; + if (!ch) { + // Line is just whitespace - emit an empty line. + Putc('\n', out); + continue; + } + + if (ch == '#') { + // Comment - the indentation doesn't matter to python, but try to + // adjust the whitespace for the benefit of human readers (though SWIG + // currently seems to always remove any whitespace before a '#' before + // we get here, in which case we'll just leave the comment at the start + // of the line). + if (i >= Len(initial)) { + Printv(out, indent, NIL); + } + + Printv(out, c + i, "\n", NIL); + continue; + } + + if (i < Len(initial)) { + // There's non-whitespace in the initial prefix of this line. + Swig_error(file, line, "Line indented less than expected (line %d of pythoncode)\n", py_line); Printv(out, indent, c, "\n", NIL); } else { - Printv(out, "\n", NIL); + if (memcmp(c, Char(initial), Len(initial)) == 0) { + // Prefix matches initial, so just remove it. + Printv(out, indent, c + Len(initial), "\n", NIL); + continue; + } + Swig_warning(WARN_PYTHON_INDENT_MISMATCH, + file, line, "Whitespace prefix doesn't match (line %d of pythoncode)\n", py_line); + // To avoid gratuitously breaking interface files which worked with + // SWIG <= 3.0.5, we remove a prefix of the same number of bytes for + // lines which start with different whitespace to the line we got + // 'initial' from. + Printv(out, indent, c + Len(initial), "\n", NIL); } - si = Next(si); } Delete(clist); return out; @@ -1811,10 +1862,17 @@ public: // Only do the autodoc if there isn't a docstring for the class String *str = Getattr(n, "feature:docstring"); if (!str || Len(str) == 0) { - if (CPlusPlus) { - Printf(doc, "Proxy of C++ %s class", real_classname); + if (builtin) { + String *name = Getattr(n, "name"); + String *rname = add_explicit_scope(SwigType_namestr(name)); + Printf(doc, "%s", rname); + Delete(rname); } else { - Printf(doc, "Proxy of C %s struct", real_classname); + if (CPlusPlus) { + Printf(doc, "Proxy of C++ %s class", real_classname); + } else { + Printf(doc, "Proxy of C %s struct", real_classname); + } } } } @@ -1926,7 +1984,7 @@ public: // Avoid unnecessary string allocation in the common case when we don't // need to remove any suffix. - return *end == '\0' ? v : NewStringWithSize(s, end - s); + return *end == '\0' ? v : NewStringWithSize(s, (int)(end - s)); } return NIL; @@ -1937,9 +1995,12 @@ public: * Check if string v can be a Python value literal or a * constant. Return NIL if it isn't. * ------------------------------------------------------------ */ - String *convertValue(String *v, SwigType *t) { + String *convertValue(String *v, SwigType *type) { const char *const s = Char(v); char *end; + String *result = NIL; + bool fail = false; + SwigType *resolved_type = 0; // Check if this is a number in any base. long value = strtol(s, &end, 0); @@ -1948,93 +2009,108 @@ public: if (errno == ERANGE) { // There was an overflow, we could try representing the value as Python // long integer literal, but for now don't bother with it. - return NIL; - } + fail = true; + } else { + if (*end != '\0') { + // If there is a suffix after the number, we can safely ignore any + // combination of "l" and "u", but not anything else (again, stuff like + // "LL" could be handled, but we don't bother to do it currently). + bool seen_long = false; + for (char* p = end; *p != '\0'; ++p) { + switch (*p) { + case 'l': + case 'L': + // Bail out on "LL". + if (seen_long) { + fail = true; + break; + } + seen_long = true; + break; - if (*end != '\0') { - // If there is a suffix after the number, we can safely ignore any - // combination of "l" and "u", but not anything else (again, stuff like - // "LL" could be handled, but we don't bother to do it currently). - bool seen_long = false; - for (char* p = end; *p != '\0'; ++p) { - switch (*p) { - case 'l': - case 'L': - // Bail out on "LL". - if (seen_long) - return NIL; - seen_long = true; - break; + case 'u': + case 'U': + break; - case 'u': - case 'U': - break; - - default: - // Except that our suffix could actually be the fractional part of - // a floating point number, so we still have to check for this. - return convertDoubleValue(v); - } - } - } - - // Deal with the values starting with 0 first as they can be octal or - // hexadecimal numbers or even pointers. - if (s[0] == '0') { - if (Len(v) == 1) { - // This is just a lone 0, but it needs to be represented differently - // in Python depending on whether it's a zero or a null pointer. - if (SwigType_ispointer(t)) - return NewString("None"); - else - return v; - } else if (s[1] == 'x' || s[1] == 'X') { - // This must have been a hex number, we can use it directly in Python, - // so nothing to do here. - } else { - // This must have been an octal number, we have to change its prefix - // to be "0o" in Python 3 only (and as long as we still support Python - // 2.5, this can't be done unconditionally). - if (py3) { - if (end - s > 1) { - String *res = NewString("0o"); - Append(res, NewStringWithSize(s + 1, end - s - 1)); - return res; + default: + // Except that our suffix could actually be the fractional part of + // a floating point number, so we still have to check for this. + result = convertDoubleValue(v); } } } - } - // Avoid unnecessary string allocation in the common case when we don't - // need to remove any suffix. - return *end == '\0' ? v : NewStringWithSize(s, end - s); + if (!fail) { + // Allow integers as the default value for a bool parameter. + resolved_type = SwigType_typedef_resolve_all(type); + if (Cmp(resolved_type, "bool") == 0) { + result = NewString(value ? "True" : "False"); + } else { + // Deal with the values starting with 0 first as they can be octal or + // hexadecimal numbers or even pointers. + if (s[0] == '0') { + if (Len(v) == 1) { + // This is just a lone 0, but it needs to be represented differently + // in Python depending on whether it's a zero or a null pointer. + if (SwigType_ispointer(resolved_type)) + result = NewString("None"); + else + result = v; + } else if (s[1] == 'x' || s[1] == 'X') { + // This must have been a hex number, we can use it directly in Python, + // so nothing to do here. + } else { + // This must have been an octal number, we have to change its prefix + // to be "0o" in Python 3 only (and as long as we still support Python + // 2.5, this can't be done unconditionally). + if (py3) { + if (end - s > 1) { + result = NewString("0o"); + Append(result, NewStringWithSize(s + 1, (int)(end - s - 1))); + } + } + } + } + + // Avoid unnecessary string allocation in the common case when we don't + // need to remove any suffix. + if (!result) + result = *end == '\0' ? v : NewStringWithSize(s, (int)(end - s)); + } + } + } } // Check if this is a floating point number (notice that it wasn't // necessarily parsed as a long above, consider e.g. ".123"). - if (String *res = convertDoubleValue(v)) { - return res; - } + if (!fail && !result) { + result = convertDoubleValue(v); + if (!result) { + if (Strcmp(v, "true") == 0 || Strcmp(v, "TRUE") == 0) + result = NewString("True"); + else if (Strcmp(v, "false") == 0 || Strcmp(v, "FALSE") == 0) + result = NewString("False"); + else if (Strcmp(v, "NULL") == 0 || Strcmp(v, "nullptr") == 0) { + if (!resolved_type) + resolved_type = SwigType_typedef_resolve_all(type); + result = SwigType_ispointer(resolved_type) ? NewString("None") : NewString("0"); + } - if (Strcmp(v, "true") == 0 || Strcmp(v, "TRUE") == 0) - return NewString("True"); - if (Strcmp(v, "false") == 0 || Strcmp(v, "FALSE") == 0) - return NewString("False"); - if (Strcmp(v, "NULL") == 0 || Strcmp(v, "nullptr") == 0) - return SwigType_ispointer(t) ? NewString("None") : NewString("0"); - - // This could also be an enum type, default value of which could be - // representable in Python if it doesn't include any scope (which could, - // but currently is not, translated). - if (!Strchr(s, ':')) { - Node *lookup = Swig_symbol_clookup(v, 0); - if (lookup) { - if (Cmp(Getattr(lookup, "nodeType"), "enumitem") == 0) - return Getattr(lookup, "sym:name"); + // This could also be an enum type, default value of which could be + // representable in Python if it doesn't include any scope (which could, + // but currently is not, translated). + else if (!Strchr(s, ':')) { + Node *lookup = Swig_symbol_clookup(v, 0); + if (lookup) { + if (Cmp(Getattr(lookup, "nodeType"), "enumitem") == 0) + result = Getattr(lookup, "sym:name"); + } + } } } - return NIL; + Delete(resolved_type); + return result; } /* ------------------------------------------------------------ @@ -2047,34 +2123,40 @@ public: * at C++ code level where they can always be handled. * ------------------------------------------------------------ */ bool is_representable_as_pyargs(Node *n) { - bool is_representable = true; - ParmList *plist = CopyParmList(Getattr(n, "parms")); + Swig_typemap_attach_parms("default", plist, NULL); + Parm *p; Parm *pnext; for (p = plist; p; p = pnext) { - pnext = NIL; + pnext = nextSibling(p); String *tm = Getattr(p, "tmap:in"); if (tm) { - pnext = Getattr(p, "tmap:in:next"); + Parm *in_next = Getattr(p, "tmap:in:next"); + if (in_next) + pnext = in_next; if (checkAttribute(p, "tmap:in:numinputs", "0")) { continue; } } - if (!pnext) { - pnext = nextSibling(p); - } + + // "default" typemap can contain arbitrary C++ code, so while it could, in + // principle, be possible to examine it and check if it's just something + // simple of the form "$1 = expression" and then use convertValue() to + // check if expression can be used in Python, but for now we just + // pessimistically give up and prefer to handle this at C++ level only. + if (Getattr(p, "tmap:default")) + return false; + if (String *value = Getattr(p, "value")) { String *type = Getattr(p, "type"); - if (!convertValue(value, type)) { - is_representable = false; - break; - } + if (!convertValue(value, type)) + return false; } } - return is_representable; + return true; } @@ -2116,8 +2198,17 @@ public: if (nn) n = nn; - /* For overloaded function, just use *args */ - if (is_real_overloaded(n) || GetFlag(n, "feature:compactdefaultargs") || !is_representable_as_pyargs(n)) { + /* We prefer to explicitly list all parameters of the C function in the + generated Python code as this makes the function more convenient to use, + however in some cases we must replace the real parameters list with just + the catch all "*args". This happens when: + + 1. The function is overloaded as Python doesn't support this. + 2. We were explicitly asked to use the "compact" arguments form. + 3. We were explicitly asked to use default args from C via the "python:cdefaultargs" feature. + 4. One of the default argument values can't be represented in Python. + */ + if (is_real_overloaded(n) || GetFlag(n, "feature:compactdefaultargs") || GetFlag(n, "feature:python:cdefaultargs") || !is_representable_as_pyargs(n)) { String *parms = NewString(""); if (in_class) Printf(parms, "self, "); @@ -2256,10 +2347,10 @@ public: if (have_docstring(n)) Printv(f_dest, tab4, docstring(n, AUTODOC_FUNC), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_dest, pythoncode(pythonprepend(n), tab4), "\n", NIL); + Printv(f_dest, pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); if (have_pythonappend(n)) { Printv(f_dest, tab4 "val = ", funcCall(name, callParms), "\n", NIL); - Printv(f_dest, pythoncode(pythonappend(n), tab4), "\n", NIL); + Printv(f_dest, pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); Printv(f_dest, tab4 "return val\n", NIL); } else { Printv(f_dest, tab4 "return ", funcCall(name, callParms), "\n", NIL); @@ -2746,14 +2837,12 @@ public: Printv(f->locals, " char * kwnames[] = ", kwargs, ";\n", NIL); } - if (use_parse || allow_kwargs || !modernargs) { - if (builtin && in_class && tuple_arguments == 0) { - Printf(parse_args, " if (args && PyTuple_Check(args) && PyTuple_GET_SIZE(args) > 0) SWIG_fail;\n"); - } else { - Printf(parse_args, ":%s\"", iname); - Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL); - funpack = 0; - } + if (builtin && !funpack && in_class && tuple_arguments == 0) { + Printf(parse_args, " if (args && PyTuple_Check(args) && PyTuple_GET_SIZE(args) > 0) SWIG_exception_fail(SWIG_TypeError, \"%s takes no arguments\");\n", iname); + } else if (use_parse || allow_kwargs || !modernargs) { + Printf(parse_args, ":%s\"", iname); + Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL); + funpack = 0; } else { Clear(parse_args); if (funpack) { @@ -3120,6 +3209,17 @@ public: } /* If this is a builtin type, create a PyGetSetDef entry for this member variable. */ + if (builtin) { + const char *memname = "__dict__"; + Hash *h = Getattr(builtin_getset, memname); + if (!h) { + h = NewHash(); + Setattr(builtin_getset, memname, h); + Delete(h); + } + Setattr(h, "getter", "SwigPyObject_get___dict__"); + } + if (builtin_getter) { String *memname = Getattr(n, "membervariableHandler:sym:name"); if (!memname) @@ -3853,7 +3953,7 @@ public: else quoted_symname = NewStringf("\"%s\"", symname); } - String *quoted_rname = NewStringf("\"%s\"", rname); + String *quoted_tp_doc_str = NewStringf("\"%s\"", getSlot(n, "feature:python:tp_doc")); char const *tp_init = builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit"; String *tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES"); String *py3_tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"); @@ -3904,7 +4004,7 @@ public: printSlot(f, tp_doc, "tp_doc"); Delete(tp_doc); } else { - printSlot(f, quoted_rname, "tp_doc"); + printSlot(f, quoted_tp_doc_str, "tp_doc"); } printSlot(f, getSlot(n, "feature:python:tp_traverse"), "tp_traverse", "traverseproc"); printSlot(f, getSlot(n, "feature:python:tp_clear"), "tp_clear", "inquiry"); @@ -4088,7 +4188,7 @@ public: Delete(tp_flags); Delete(py3_tp_flags); Delete(quoted_symname); - Delete(quoted_rname); + Delete(quoted_tp_doc_str); Delete(clientdata_klass); Delete(richcompare_func); Delete(getset_name); @@ -4183,7 +4283,18 @@ public: Printv(base_class, abcs, NIL); } - if (!builtin) { + if (builtin) { + if (have_docstring(n)) { + String *str = cdocstring(n, AUTODOC_CLASS); + Setattr(n, "feature:python:tp_doc", str); + Delete(str); + } else { + String *name = Getattr(n, "name"); + String *rname = add_explicit_scope(SwigType_namestr(name)); + Setattr(n, "feature:python:tp_doc", rname); + Delete(rname); + } + } else { Printv(f_shadow, "class ", class_name, NIL); if (Len(base_class)) { @@ -4462,7 +4573,7 @@ public: have_repr = 1; } if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); + String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); String *pyaction = NewStringf("%s.%s", module, fullname); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4484,12 +4595,12 @@ public: Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD), "\n", NIL); if (have_pythonprepend(n)) { fproxy = 0; - Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); } if (have_pythonappend(n)) { fproxy = 0; Printv(f_shadow, tab8, "val = ", funcCall(fullname, callParms), "\n", NIL); - Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); Printv(f_shadow, tab8, "return val\n\n", NIL); } else { Printv(f_shadow, tab8, "return ", funcCall(fullname, callParms), "\n\n", NIL); @@ -4569,10 +4680,10 @@ public: if (have_docstring(n)) Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); if (have_pythonappend(n)) { Printv(f_shadow, tab8, "val = ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n", NIL); - Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); Printv(f_shadow, tab8, "return val\n\n", NIL); } else { Printv(f_shadow, tab8, "return ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n\n", NIL); @@ -4657,7 +4768,7 @@ public: if (!have_constructor && handled_as_init) { if (!builtin) { if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); + String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4686,17 +4797,17 @@ public: if (have_docstring(n)) Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); Printv(f_shadow, pass_self, NIL); if (fastinit) { - Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self,", funcCall(Swig_name_construct(NSPACE_TODO, symname), callParms), ")\n", NIL); + Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self, ", funcCall(Swig_name_construct(NSPACE_TODO, symname), callParms), ")\n", NIL); } else { Printv(f_shadow, tab8, "this = ", funcCall(Swig_name_construct(NSPACE_TODO, symname), callParms), "\n", tab8, "try:\n", tab8, tab4, "self.this.append(this)\n", tab8, "except:\n", tab8, tab4, "self.this = this\n", NIL); } if (have_pythonappend(n)) - Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n\n", NIL); + Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n\n", NIL); Delete(pass_self); } have_constructor = 1; @@ -4705,7 +4816,7 @@ public: /* Hmmm. We seem to be creating a different constructor. We're just going to create a function for it. */ if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), ""); + String *pycode = pythoncode(Getattr(n, "feature:shadow"), "", Getfile(n), Getline(n)); String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4719,7 +4830,7 @@ public: if (have_docstring(n)) Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow_stubs, pythoncode(pythonprepend(n), tab4), "\n", NIL); + Printv(f_shadow_stubs, pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); String *subfunc = NULL; /* if (builtin) @@ -4732,7 +4843,7 @@ public: Printv(f_shadow_stubs, tab4, "val.thisown = 1\n", NIL); #endif if (have_pythonappend(n)) - Printv(f_shadow_stubs, pythoncode(pythonappend(n), tab4), "\n", NIL); + Printv(f_shadow_stubs, pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n)), "\n", NIL); Printv(f_shadow_stubs, tab4, "return val\n", NIL); Delete(subfunc); } @@ -4769,7 +4880,7 @@ public: if (shadow) { if (Getattr(n, "feature:shadow")) { - String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); + String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n)); String *pyaction = NewStringf("%s.%s", module, Swig_name_destroy(NSPACE_TODO, symname)); Replaceall(pycode, "$action", pyaction); Delete(pyaction); @@ -4787,7 +4898,7 @@ public: if (have_docstring(n)) Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR), "\n", NIL); if (have_pythonprepend(n)) - Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); #ifdef USE_THISOWN Printv(f_shadow, tab8, "try:\n", NIL); Printv(f_shadow, tab8, tab4, "if self.thisown:", module, ".", Swig_name_destroy(NSPACE_TODO, symname), "(self)\n", NIL); @@ -4795,7 +4906,7 @@ public: #else #endif if (have_pythonappend(n)) - Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); + Printv(f_shadow, pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n)), "\n", NIL); Printv(f_shadow, tab8, "pass\n", NIL); Printv(f_shadow, "\n", NIL); } @@ -4977,12 +5088,12 @@ public: if (!ImportMode && (Cmp(section, "python") == 0 || Cmp(section, "shadow") == 0)) { if (shadow) { - String *pycode = pythoncode(code, shadow_indent); + String *pycode = pythoncode(code, shadow_indent, Getfile(n), Getline(n)); Printv(f_shadow, pycode, NIL); Delete(pycode); } } else if (!ImportMode && (Cmp(section, "pythonbegin") == 0)) { - String *pycode = pythoncode(code, ""); + String *pycode = pythoncode(code, "", Getfile(n), Getline(n)); Printv(f_shadow_begin, pycode, NIL); Delete(pycode); } else { diff --git a/Source/Modules/r.cxx b/Source/Modules/r.cxx index 3befcfbdd..0e8e23063 100644 --- a/Source/Modules/r.cxx +++ b/Source/Modules/r.cxx @@ -281,6 +281,7 @@ public: void dispatchFunction(Node *n); int functionWrapper(Node *n); + int constantWrapper(Node *n); int variableWrapper(Node *n); int classDeclaration(Node *n); @@ -1381,12 +1382,12 @@ List * R::Swig_overload_rank(Node *n, } if ((!t1) && (!nodes[i].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[i].n), Getline(nodes[i].n), - "Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[i].n), SwigType_str(Getattr(p1, "type"), 0)); nodes[i].error = 1; } else if ((!t2) && (!nodes[j].error)) { Swig_warning(WARN_TYPEMAP_TYPECHECK, Getfile(nodes[j].n), Getline(nodes[j].n), - "xx Overloaded method %s not supported (no type checking rule for '%s').\n", + "Overloaded method %s not supported (incomplete type checking rule - no precedence level in typecheck typemap for '%s').\n", Swig_name_decl(nodes[j].n), SwigType_str(Getattr(p2, "type"), 0)); nodes[j].error = 1; } @@ -2181,6 +2182,16 @@ int R::functionWrapper(Node *n) { return SWIG_OK; } +/* ---------------------------------------------------------------------- + * R::constantWrapper() + * ---------------------------------------------------------------------- */ + +int R::constantWrapper(Node *n) { + (void) n; + // TODO + return SWIG_OK; +} + /***************************************************** Add the specified routine name to the collection of generated routines that are called from R functions. diff --git a/Source/Modules/ruby.cxx b/Source/Modules/ruby.cxx index 310e89b82..4b45b87ca 100644 --- a/Source/Modules/ruby.cxx +++ b/Source/Modules/ruby.cxx @@ -13,14 +13,12 @@ #include "swigmod.h" #include "cparse.h" -static int treduce = SWIG_cparse_template_reduce(0); - -#define SWIG_PROTECTED_TARGET_METHODS 1 - #include #include #include /* for INT_MAX */ +#define SWIG_PROTECTED_TARGET_METHODS 1 + class RClass { private: String *temp; @@ -1171,6 +1169,7 @@ public: if (directorsEnabled()) { // Insert director runtime into the f_runtime file (make it occur before %header section) + Swig_insert_file("director_common.swg", f_runtime); Swig_insert_file("director.swg", f_runtime); } @@ -1794,8 +1793,8 @@ public: /* if the object is a director, and the method call originated from its * underlying Ruby object, resolve the call by going up the c++ - * inheritance chain. otherwise try to resolve the method in python. - * without this check an infinite loop is set up between the director and + * inheritance chain. otherwise try to resolve the method in Ruby. + * without this check an infinite loop is set up between the director and * shadow class method calls. */ diff --git a/Source/Modules/scilab.cxx b/Source/Modules/scilab.cxx index 6d9930431..dd0645bd2 100644 --- a/Source/Modules/scilab.cxx +++ b/Source/Modules/scilab.cxx @@ -346,14 +346,18 @@ public: emit_attach_parmmaps(functionParamsList, wrapper); Setattr(node, "wrap:parms", functionParamsList); - /* Check arguments */ + /* Check input/output arguments count */ int maxInputArguments = emit_num_arguments(functionParamsList); int minInputArguments = emit_num_required(functionParamsList); int minOutputArguments = 0; int maxOutputArguments = 0; - /* Insert calls to CheckInputArgument and CheckOutputArgument */ - Printf(wrapper->code, "SWIG_CheckInputArgument(pvApiCtx, $mininputarguments, $maxinputarguments);\n"); + if (!emit_isvarargs(functionParamsList)) { + Printf(wrapper->code, "SWIG_CheckInputArgument(pvApiCtx, $mininputarguments, $maxinputarguments);\n"); + } + else { + Printf(wrapper->code, "SWIG_CheckInputArgumentAtLeast(pvApiCtx, $mininputarguments-1);\n"); + } Printf(wrapper->code, "SWIG_CheckOutputArgument(pvApiCtx, $minoutputarguments, $maxoutputarguments);\n"); /* Set context */ @@ -675,7 +679,7 @@ public: } } - /* Create variables for member pointer constants, not suppported by typemaps (like Python wrapper does) */ + /* Create variables for member pointer constants, not supported by typemaps (like Python wrapper does) */ if (SwigType_type(type) == T_MPOINTER) { String *wname = Swig_name_wrapper(constantName); String *str = SwigType_str(type, wname); diff --git a/Source/Modules/tcl8.cxx b/Source/Modules/tcl8.cxx index ac356098b..2e32fc808 100644 --- a/Source/Modules/tcl8.cxx +++ b/Source/Modules/tcl8.cxx @@ -13,7 +13,6 @@ #include "swigmod.h" #include "cparse.h" -static int treduce = SWIG_cparse_template_reduce(0); static const char *usage = "\ Tcl 8 Options (available with -tcl)\n\ diff --git a/Source/Preprocessor/cpp.c b/Source/Preprocessor/cpp.c index ac912f49e..a183eecde 100644 --- a/Source/Preprocessor/cpp.c +++ b/Source/Preprocessor/cpp.c @@ -1771,7 +1771,10 @@ String *Preprocessor_parse(String *s) { } else if (Equal(id, "")) { /* Null directive */ } else { - Swig_error(Getfile(s), Getline(id), "Unknown SWIG preprocessor directive: %s (if this is a block of target language code, delimit it with %%{ and %%})\n", id); + /* Ignore unknown preprocessor directives which are inside an inactive + * conditional (github issue #394). */ + if (allow) + Swig_error(Getfile(s), Getline(id), "Unknown SWIG preprocessor directive: %s (if this is a block of target language code, delimit it with %%{ and %%})\n", id); } for (i = 0; i < cpp_lines; i++) Putc('\n', ns); diff --git a/Source/Swig/include.c b/Source/Swig/include.c index 7e80172ba..08226a25c 100644 --- a/Source/Swig/include.c +++ b/Source/Swig/include.c @@ -194,7 +194,7 @@ static FILE *Swig_open_file(const_String_or_char_ptr name, int sysfile, int use_ lastpath = filename; /* Skip the UTF-8 BOM if it's present */ - nbytes = fread(bom, 1, 3, f); + nbytes = (int)fread(bom, 1, 3, f); if (nbytes == 3 && bom[0] == (char)0xEF && bom[1] == (char)0xBB && bom[2] == (char)0xBF) { /* skip */ } else { @@ -369,7 +369,7 @@ String *Swig_file_filename(const_String_or_char_ptr filename) { String *Swig_file_dirname(const_String_or_char_ptr filename) { const char *delim = SWIG_FILE_DELIMITER; const char *c = strrchr(Char(filename), *delim); - return c ? NewStringWithSize(filename, c - Char(filename) + 1) : NewString(""); + return c ? NewStringWithSize(filename, (int)(c - Char(filename) + 1)) : NewString(""); } /* diff --git a/Source/Swig/misc.c b/Source/Swig/misc.c index d41a7c12d..11c14d900 100644 --- a/Source/Swig/misc.c +++ b/Source/Swig/misc.c @@ -127,7 +127,7 @@ String *Swig_strip_c_comments(const String *s) { } if (comment_begin && comment_end) { - int size = comment_begin - Char(s); + int size = (int)(comment_begin - Char(s)); String *stripmore = 0; stripped = NewStringWithSize(s, size); Printv(stripped, comment_end + 1, NIL); @@ -808,7 +808,7 @@ void Swig_scopename_split(const String *s, String **rprefix, String **rlast) { *rlast = Copy(s); return; } else { - *rprefix = NewStringWithSize(cc, co - cc - 2); + *rprefix = NewStringWithSize(cc, (int)(co - cc - 2)); *rlast = NewString(co); return; } @@ -835,7 +835,7 @@ void Swig_scopename_split(const String *s, String **rprefix, String **rlast) { } if (cc != tmp) { - *rprefix = NewStringWithSize(tmp, cc - tmp); + *rprefix = NewStringWithSize(tmp, (int)(cc - tmp)); *rlast = NewString(cc + 2); return; } else { @@ -858,7 +858,7 @@ String *Swig_scopename_prefix(const String *s) { if (co == cc) { return 0; } else { - String *prefix = NewStringWithSize(cc, co - cc - 2); + String *prefix = NewStringWithSize(cc, (int)(co - cc - 2)); return prefix; } } @@ -884,7 +884,7 @@ String *Swig_scopename_prefix(const String *s) { } if (cc != tmp) { - return NewStringWithSize(tmp, cc - tmp); + return NewStringWithSize(tmp, (int)(cc - tmp)); } else { return 0; } @@ -977,7 +977,7 @@ String *Swig_scopename_first(const String *s) { } } if (*c && (c != tmp)) { - return NewStringWithSize(tmp, c - tmp); + return NewStringWithSize(tmp, (int)(c - tmp)); } else { return 0; } @@ -1219,8 +1219,8 @@ static int split_regex_pattern_subst(String *s, String **pattern, String **subst if (!p) goto err_out; sube = p; - *pattern = NewStringWithSize(pats, pate - pats); - *subst = NewStringWithSize(subs, sube - subs); + *pattern = NewStringWithSize(pats, (int)(pate - pats)); + *subst = NewStringWithSize(subs, (int)(sube - subs)); *input = p + 1; return 1; @@ -1270,10 +1270,10 @@ String *replace_captures(int num_captures, const char *input, String *subst, int /* Copy part without substitutions */ const char *q = strchr(p, '\\'); if (!q) { - copy_with_maybe_case_conversion(result, p, strlen(p), &convertCase, convertNextOnly); + copy_with_maybe_case_conversion(result, p, (int)strlen(p), &convertCase, convertNextOnly); break; } - copy_with_maybe_case_conversion(result, p, q - p, &convertCase, convertNextOnly); + copy_with_maybe_case_conversion(result, p, (int)(q - p), &convertCase, convertNextOnly); p = q + 1; /* Handle substitution */ @@ -1350,7 +1350,7 @@ String *Swig_string_regex(String *s) { pcre_error, Char(pattern), pcre_errorpos); exit(1); } - rc = pcre_exec(compiled_pat, NULL, input, strlen(input), 0, 0, captures, 30); + rc = pcre_exec(compiled_pat, NULL, input, (int)strlen(input), 0, 0, captures, 30); if (rc >= 0) { res = replace_captures(rc, input, subst, captures, pattern, s); } else if (rc != PCRE_ERROR_NOMATCH) { diff --git a/Source/Swig/naming.c b/Source/Swig/naming.c index 9e2b4a436..2d1effa18 100644 --- a/Source/Swig/naming.c +++ b/Source/Swig/naming.c @@ -578,7 +578,7 @@ void Swig_name_object_inherit(Hash *namehash, String *base, String *derived) { bprefix = NewStringf("%s::", base); dprefix = NewStringf("%s::", derived); cbprefix = Char(bprefix); - plen = strlen(cbprefix); + plen = (int)strlen(cbprefix); for (ki = First(namehash); ki.key; ki = Next(ki)) { char *k = Char(ki.key); if (strncmp(k, cbprefix, plen) == 0) { @@ -1003,6 +1003,10 @@ static int nodes_are_equivalent(Node *a, Node *b, int a_inclass) { } return 0; } + if (Equal(ta, "template") && Equal(tb, "template")) { + if (Cmp(a_storage, "friend") == 0 || Cmp(b_storage, "friend") == 0) + return 1; + } } return 0; } @@ -1070,7 +1074,7 @@ static List *Swig_make_attrlist(const char *ckey) { String *nattr; const char *rattr = strchr(++cattr, '$'); while (rattr) { - nattr = NewStringWithSize(cattr, rattr - cattr); + nattr = NewStringWithSize(cattr, (int)(rattr - cattr)); Append(list, nattr); Delete(nattr); cattr = rattr + 1; diff --git a/Source/Swig/scanner.c b/Source/Swig/scanner.c index b0d608c9e..227a1d00c 100644 --- a/Source/Swig/scanner.c +++ b/Source/Swig/scanner.c @@ -336,7 +336,7 @@ static void brackets_reset(Scanner *s) { * Usually called when '(' is found. * ----------------------------------------------------------------------------- */ static void brackets_push(Scanner *s) { - int *newInt = malloc(sizeof(int)); + int *newInt = (int *)malloc(sizeof(int)); *newInt = 0; Push(s->brackets, NewVoid(newInt, free)); } diff --git a/Source/Swig/stype.c b/Source/Swig/stype.c index 506878799..a57222745 100644 --- a/Source/Swig/stype.c +++ b/Source/Swig/stype.c @@ -195,7 +195,7 @@ int SwigType_ispointer_return(const SwigType *t) { if (!t) return 0; c = Char(t); - idx = strlen(c) - 4; + idx = (int)strlen(c) - 4; if (idx >= 0) { return (strcmp(c + idx, ").p.") == 0); } @@ -208,7 +208,7 @@ int SwigType_isreference_return(const SwigType *t) { if (!t) return 0; c = Char(t); - idx = strlen(c) - 4; + idx = (int)strlen(c) - 4; if (idx >= 0) { return (strcmp(c + idx, ").r.") == 0); } @@ -485,7 +485,7 @@ String *SwigType_namestr(const SwigType *t) { if (!c || !strstr(c + 2, ")>")) return NewString(t); - r = NewStringWithSize(d, c - d); + r = NewStringWithSize(d, (int)(c - d)); if (*(c - 1) == '<') Putc(' ', r); Putc('<', r); diff --git a/Source/Swig/symbol.c b/Source/Swig/symbol.c index 2202f61c6..d72451a14 100644 --- a/Source/Swig/symbol.c +++ b/Source/Swig/symbol.c @@ -1149,7 +1149,7 @@ Node *Swig_symbol_clookup(const_String_or_char_ptr name, Symtab *n) { Symtab *un = Getattr(s, "sym:symtab"); Node *ss = (!Equal(name, uname) || (un != n)) ? Swig_symbol_clookup(uname, un) : 0; /* avoid infinity loop */ if (!ss) { - Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname")); + Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); } s = ss; } @@ -1221,7 +1221,7 @@ Node *Swig_symbol_clookup_check(const_String_or_char_ptr name, Symtab *n, int (* Node *ss; ss = Swig_symbol_clookup(Getattr(s, "uname"), Getattr(s, "sym:symtab")); if (!ss && !checkfunc) { - Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname")); + Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); } s = ss; } @@ -1272,7 +1272,7 @@ Node *Swig_symbol_clookup_local(const_String_or_char_ptr name, Symtab *n) { while (s && Checkattr(s, "nodeType", "using")) { Node *ss = Swig_symbol_clookup_local(Getattr(s, "uname"), Getattr(s, "sym:symtab")); if (!ss) { - Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname")); + Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); } s = ss; } @@ -1320,7 +1320,7 @@ Node *Swig_symbol_clookup_local_check(const_String_or_char_ptr name, Symtab *n, while (s && Checkattr(s, "nodeType", "using")) { Node *ss = Swig_symbol_clookup_local_check(Getattr(s, "uname"), Getattr(s, "sym:symtab"), checkfunc); if (!ss && !checkfunc) { - Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", Getattr(s, "uname")); + Swig_warning(WARN_PARSE_USING_UNDEF, Getfile(s), Getline(s), "Nothing known about '%s'.\n", SwigType_namestr(Getattr(s, "uname"))); } s = ss; } diff --git a/Source/Swig/typemap.c b/Source/Swig/typemap.c index 0bfbb4bce..23b1e80e9 100644 --- a/Source/Swig/typemap.c +++ b/Source/Swig/typemap.c @@ -1844,7 +1844,7 @@ static List *split_embedded_typemap(String *s) { } } if ((level == 0) && angle_level == 0 && ((*c == ',') || (*c == ')'))) { - String *tmp = NewStringWithSize(start, c - start); + String *tmp = NewStringWithSize(start, (int)(c - start)); Append(args, tmp); Delete(tmp); start = c + 1; @@ -1915,10 +1915,10 @@ static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper c++; } if (end) { - dollar_typemap = NewStringWithSize(start, (end - start)); + dollar_typemap = NewStringWithSize(start, (int)((end - start))); syntax_error = 0; } else { - dollar_typemap = NewStringWithSize(start, (c - start)); + dollar_typemap = NewStringWithSize(start, (int)((c - start))); } if (!syntax_error) { @@ -1963,7 +1963,7 @@ static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper char *eq = strchr(Char(parm), '='); char *c = Char(parm); if (eq && (eq - c > 0)) { - String *name = NewStringWithSize(c, eq - c); + String *name = NewStringWithSize(c, (int)(eq - c)); String *value = NewString(eq + 1); Insert(name, 0, "$"); Setattr(vars, name, value); diff --git a/Source/Swig/typeobj.c b/Source/Swig/typeobj.c index 622eac118..b2832b6a9 100644 --- a/Source/Swig/typeobj.c +++ b/Source/Swig/typeobj.c @@ -361,7 +361,7 @@ SwigType *SwigType_del_pointer(SwigType *t) { printf("Fatal error. SwigType_del_pointer applied to non-pointer.\n"); abort(); } - Delslice(t, 0, (c - s) + 2); + Delslice(t, 0, (int)((c - s) + 2)); return t; } @@ -915,7 +915,7 @@ SwigType *SwigType_add_template(SwigType *t, ParmList *parms) { String *SwigType_templateprefix(const SwigType *t) { const char *s = Char(t); const char *c = strstr(s, "<("); - return c ? NewStringWithSize(s, c - s) : NewString(s); + return c ? NewStringWithSize(s, (int)(c - s)) : NewString(s); } /* ----------------------------------------------------------------------------- @@ -966,7 +966,7 @@ String *SwigType_templatesuffix(const SwigType *t) { String *SwigType_istemplate_templateprefix(const SwigType *t) { const char *s = Char(t); const char *c = strstr(s, "<("); - return c ? NewStringWithSize(s, c - s) : 0; + return c ? NewStringWithSize(s, (int)(c - s)) : 0; } /* ----------------------------------------------------------------------------- @@ -989,7 +989,7 @@ String *SwigType_istemplate_only_templateprefix(const SwigType *t) { const char *s = Char(t); if (len >= 4 && strcmp(s + len - 2, ")>") == 0) { const char *c = strstr(s, "<("); - return c ? NewStringWithSize(s, c - s) : 0; + return c ? NewStringWithSize(s, (int)(c - s)) : 0; } else { return 0; } @@ -1022,7 +1022,7 @@ String *SwigType_templateargs(const SwigType *t) { nest--; c++; } - return NewStringWithSize(start, c - start); + return NewStringWithSize(start, (int)(c - start)); } c++; } diff --git a/Tools/config/ac_compare_version.m4 b/Tools/config/ac_compare_version.m4 deleted file mode 100644 index 0828f4789..000000000 --- a/Tools/config/ac_compare_version.m4 +++ /dev/null @@ -1,40 +0,0 @@ -dnl @synopsis AC_COMPARE_VERSION\ -dnl (version-a, version-b, action-if-greater, action-if-equal, action-if-less) -dnl -dnl This macro compares two version numbers and executes the indicated action -dnl based on whether they're equal or one is greater than the other. -dnl It's needed to determine whether ocaml is new enough that the incompatible -dnl change 'loc' -> '_loc' is present in this version of camlp4. -dnl -dnl It's implemented from scratch just for SWIG by arty. -dnl -dnl @category Misc -dnl @author arty -dnl @version 2006-11-02 -dnl @license GPLWithACException - -AC_DEFUN([AC_COMPARE_VERSION], [ - # Split the version into units. - ver_a="[$1]" - ver_b="[$2]" - nodots_a=`echo $ver_a | sed -e 's/\./ /g'` - condition="equal" - isolate_b_regex='\([[0-9]]\+\).*' - for ver_part in $nodots_a ; do - b_ver_part=`echo "$ver_b" | sed -e 's/'"$isolate_b_regex"'/\1/'` - if test \( "$ver_part" -lt "$b_ver_part" \) -a \( "x$condition" = "xequal" \) ; then - condition=less - elif test \( "$ver_part" -gt "$b_ver_part" \) -a \( "x$condition" = "xequal" \) ; then - condition=greater - fi - isolate_b_regex='[[0-9]]\+\.'"$isolate_b_regex" - done - - if test "x$condition" = "xequal" ; then - [$4] - elif test "x$condition" = "xless" ; then - [$3] - elif test "x$condition" = "xgreater" ; then - [$5] - fi -]) diff --git a/Tools/config/ax_boost_base.m4 b/Tools/config/ax_boost_base.m4 index 550b64138..f3279f2b7 100644 --- a/Tools/config/ax_boost_base.m4 +++ b/Tools/config/ax_boost_base.m4 @@ -33,7 +33,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 23 +#serial 26 AC_DEFUN([AX_BOOST_BASE], [ @@ -92,8 +92,11 @@ if test "x$want_boost" = "xyes"; then libsubdirs="lib" ax_arch=`uname -m` case $ax_arch in - x86_64|ppc64|s390x|sparc64|aarch64) - libsubdirs="lib64 lib lib64" + x86_64) + libsubdirs="lib64 libx32 lib lib64" + ;; + ppc64|s390x|sparc64|aarch64|ppc64le) + libsubdirs="lib64 lib lib64 ppc64le" ;; esac @@ -170,6 +173,10 @@ if test "x$want_boost" = "xyes"; then dnl if we found no boost with system layout we search for boost libraries dnl built and installed without the --layout=system option or for a staged(not installed) version if test "x$succeeded" != "xyes"; then + CPPFLAGS="$CPPFLAGS_SAVED" + LDFLAGS="$LDFLAGS_SAVED" + BOOST_CPPFLAGS= + BOOST_LDFLAGS= _version=0 if test "$ac_boost_path" != ""; then if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then @@ -182,6 +189,12 @@ if test "x$want_boost" = "xyes"; then VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` BOOST_CPPFLAGS="-I$ac_boost_path/include/boost-$VERSION_UNDERSCORE" done + dnl if nothing found search for layout used in Windows distributions + if test -z "$BOOST_CPPFLAGS"; then + if test -d "$ac_boost_path/boost" && test -r "$ac_boost_path/boost"; then + BOOST_CPPFLAGS="-I$ac_boost_path" + fi + fi fi else if test "$cross_compiling" != yes; then @@ -270,4 +283,3 @@ if test "x$want_boost" = "xyes"; then fi ]) - diff --git a/Tools/config/ax_path_generic.m4 b/Tools/config/ax_path_generic.m4 index 6960d612a..f77fc78d6 100644 --- a/Tools/config/ax_path_generic.m4 +++ b/Tools/config/ax_path_generic.m4 @@ -69,7 +69,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 11 +#serial 13 AU_ALIAS([AC_PATH_GENERIC], [AX_PATH_GENERIC]) AC_DEFUN([AX_PATH_GENERIC],[ @@ -89,7 +89,7 @@ AC_DEFUN([AX_PATH_GENERIC],[ AC_ARG_VAR(UP[]_CFLAGS, [CFLAGS used for $1]) AC_ARG_VAR(UP[]_LIBS, [LIBS used for $1]) - AS_IF([test x$UP[]_CFLAGS != x -o x$UP[]_LIBS != x],[ + AS_IF([test x"$UP[]_CFLAGS" != x -o x"$UP[]_LIBS" != x],[ dnl Don't run config script at all, use user-provided values instead. AC_SUBST(UP[]_CFLAGS) AC_SUBST(UP[]_LIBS) diff --git a/Tools/convertpath b/Tools/convertpath new file mode 100755 index 000000000..fce5ac24b --- /dev/null +++ b/Tools/convertpath @@ -0,0 +1,27 @@ +#!/bin/sh + +# Unix to Windows relative path conversion in a script. +# Useful for avoiding backslash quoting difficulties in Makefiles. +# Acts as a much dumbed down 'cygpath -w' tool. + +usage() +{ + cat <&1 dos2unix | grep -v "\.cxx$" | grep -v "\.c$" | grep -v "^ Creating library" | grep -v "^Generating Code" +2>&1 dos2unix | grep -v -e "\.cxx$" -e "\.c$" -e "^ Creating library" -e "^Generating Code" diff --git a/appveyor.yml b/appveyor.yml new file mode 100755 index 000000000..25abcb342 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,85 @@ +platform: +- x86 +- x64 + +environment: + matrix: + - SWIGLANG: csharp + VSVER: 14 + - SWIGLANG: csharp + VSVER: 12 + - SWIGLANG: java + VSVER: 12 + - SWIGLANG: python + VSVER: 12 + VER: 27 + - SWIGLANG: python + VSVER: 12 + VER: 34 + PY3: 1 + +matrix: + allow_failures: + - platform: x64 + SWIGLANG: python + VSVER: 12 + VER: 27 + +install: +- date /T & time /T +- set PATH=C:\cygwin\bin;%PATH% +- set CYGWIN=nodosfilewarning +- git clone -q --depth=1 --single-branch --branch cccl-1.0 git://github.com/swig/cccl.git C:\cccl-1.0 +- bash -c "cp C:/cccl-1.0/cccl /usr/bin" +- ps: >- + If ($env:Platform -Match "x86") { + $env:PCRE_PLATFORM="Win32" + $env:JAVA_HOME="C:/Program Files (x86)/Java/jdk1.8.0" + $env:VCVARS_PLATFORM="x86" + $env:LANG_PLATFORM="" + } Else { + $env:PCRE_PLATFORM="x64" + $env:JAVA_HOME="C:/Program Files/Java/jdk1.8.0" + $env:VCVARS_PLATFORM="amd64" + $env:LANG_PLATFORM="-x64" + } +- ps: $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) +- echo "Using Visual Studio %VSVER%.0 at %VSCOMNTOOLS%" +- call "%VSCOMNTOOLS%\..\..\VC\vcvarsall.bat" %VCVARS_PLATFORM% +- nuget install pcre -Verbosity detailed -Version 8.33.0.1 -OutputDirectory C:\pcre +- set PCRE_ROOT=C:/pcre/pcre.8.33.0.1/build/native +- set PATH=C:\Python%VER%%LANG_PLATFORM%;%PATH% +- python -V +- bash -c "which python" +- bash -c "python -V" +- bash -c "which cl.exe" +- bash -c "cl.exe /? 2>&1 | head -n 2" +- bash -c "which csc.exe" +- bash -c "csc.exe /? | head -n 2" +- bash -c "which cccl" +- bash -c "cccl --version" +- make --version +- uname -a + +build_script: +- set CCCL_OPTIONS=--cccl-muffle /W3 +- set CHECK_OPTIONS=CSHARPOPTIONS=-platform:%Platform% + # Open dummy file descriptor to fix error on cygwin: ./configure: line 560: 0: Bad file descriptor +- bash -c "exec 0- + If ("$env:SWIGLANG$env:VER" -Match "python27") { + $env:CCCL_OPTIONS="$env:CCCL_OPTIONS /wd4717" + } +- .\swig.exe -version +- bash -c "file ./swig.exe" +- bash -c "time make -k check-%SWIGLANG%-version" +- bash -c "time make -k check-%SWIGLANG%-examples %CHECK_OPTIONS%" +- bash -c "time make -k check-%SWIGLANG%-test-suite %CHECK_OPTIONS%" + +# Do not build on tags (GitHub only) +skip_tags: true diff --git a/configure.ac b/configure.ac index c2a36fc95..713680f59 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[3.0.6],[http://www.swig.org]) +AC_INIT([swig],[3.0.7],[http://www.swig.org]) dnl NB: When this requirement is increased to 2.60 or later, AC_PROG_SED dnl definition below can be removed @@ -340,6 +340,7 @@ PLATCXXFLAGS="$PLATCFLAGS" if test x"$enable_cpp11_testing" = xyes; then AC_LANG_PUSH([C++]) CXXFLAGS_SAVED=$CXXFLAGS + CXXFLAGS= AX_CXX_COMPILE_STDCXX_11([noext], [nostop]) CXXFLAGS=$CXXFLAGS_SAVED AC_LANG_POP([C++]) @@ -601,6 +602,7 @@ AC_SUBST(TCLCXXSHARED) PYINCLUDE= PYLIB= +PYLINK= PYPACKAGE= AC_ARG_WITH(python, AS_HELP_STRING([--without-python], [Disable Python]) @@ -617,64 +619,106 @@ else PYTHON="$PYBIN" fi + PYVER=0 if test -n "$PYTHON"; then + AC_MSG_CHECKING([for $PYTHON major version number]) + PYVER=`($PYTHON -c "import sys; sys.stdout.write(sys.version[[0]])") 2>/dev/null` + AC_MSG_RESULT($PYVER) + if test -z "$PYVER"; then + PYVER=0 + fi + fi + + if test $PYVER -le 2; then AC_MSG_CHECKING(for Python prefix) - PYPREFIX=`($PYTHON -c "import sys; print sys.prefix") 2>/dev/null` + PYPREFIX=`($PYTHON -c "import sys; sys.stdout.write(sys.prefix)") 2>/dev/null` AC_MSG_RESULT($PYPREFIX) AC_MSG_CHECKING(for Python exec-prefix) - PYEPREFIX=`($PYTHON -c "import sys; print sys.exec_prefix") 2>/dev/null` + PYEPREFIX=`($PYTHON -c "import sys; sys.stdout.write(sys.exec_prefix)") 2>/dev/null` AC_MSG_RESULT($PYEPREFIX) + AC_MSG_CHECKING(for Python os.name) + PYOSNAME=`($PYTHON -c "import sys, os; sys.stdout.write(os.name)")` + AC_MSG_RESULT($PYOSNAME) + if test x"$PYOSNAME" = x"nt"; then + # Windows installations are quite different to posix installations + PYPREFIX=`echo "$PYPREFIX" | sed -e 's,\\\\,/,g'` # Forward slashes are easier to use and even work on Windows most of the time + PYTHON_SO=.pyd - # Note: I could not think of a standard way to get the version string from different versions. - # This trick pulls it out of the file location for a standard library file. - - AC_MSG_CHECKING(for Python version) - - # Need to do this hack since autoconf replaces __file__ with the name of the configure file - filehack="file__" - PYVERSION=`($PYTHON -c "import string,operator,os.path; print operator.getitem(os.path.split(operator.getitem(os.path.split(string.__$filehack),0)),1)")` - AC_MSG_RESULT($PYVERSION) - - # Find the directory for libraries this is necessary to deal with - # platforms that can have apps built for multiple archs: e.g. x86_64 - AC_MSG_CHECKING(for Python lib dir) - PYLIBDIR=`($PYTHON -c "import sys; print sys.lib") 2>/dev/null` - if test -z "$PYLIBDIR"; then - # Fedora patch Python to add sys.lib, for other distros we assume "lib". - PYLIBDIR="lib" - fi - AC_MSG_RESULT($PYLIBDIR) - - # Set the include directory - - AC_MSG_CHECKING(for Python header files) - if test -r $PYPREFIX/include/$PYVERSION/Python.h; then - PYINCLUDE="-I$PYPREFIX/include/$PYVERSION -I$PYEPREFIX/$PYLIBDIR/$PYVERSION/config" - fi - if test -z "$PYINCLUDE"; then - if test -r $PYPREFIX/include/Py/Python.h; then - PYINCLUDE="-I$PYPREFIX/include/Py -I$PYEPREFIX/$PYLIBDIR/python/lib" + AC_MSG_CHECKING(for Python header files) + if test -r $PYPREFIX/include/Python.h; then + PYINCLUDE="-I$PYPREFIX/include" fi - fi - AC_MSG_RESULT($PYINCLUDE) + AC_MSG_RESULT($PYINCLUDE) - # Set the library directory blindly. This probably won't work with older versions - AC_MSG_CHECKING(for Python library) - dirs="$PYVERSION/config $PYVERSION/$PYLIBDIR python/$PYLIBDIR" - for i in $dirs; do - if test -d $PYEPREFIX/$PYLIBDIR/$i; then - PYLIB="$PYEPREFIX/$PYLIBDIR/$i" - break + AC_MSG_CHECKING(for Python library directory) + if test -d $PYPREFIX/libs; then + PYLIB=$PYPREFIX/libs + PYLINKFILE=`ls $PYLIB/python*.lib | grep "python[[0-9]][[0-9]]\.lib"` + if test -r "$PYLINKFILE"; then + PYLINK=-l`basename $PYLINKFILE | sed -e 's/\.lib$//'` + else + PYLIB= + fi fi - done + else + # Note: I could not think of a standard way to get the version string from different versions. + # This trick pulls it out of the file location for a standard library file. + + AC_MSG_CHECKING(for Python version) + + # Need to do this hack since autoconf replaces __file__ with the name of the configure file + filehack="file__" + PYVERSION=`($PYTHON -c "import sys,string,operator,os.path; sys.stdout.write(operator.getitem(os.path.split(operator.getitem(os.path.split(string.__$filehack),0)),1))")` + AC_MSG_RESULT($PYVERSION) + + # Find the directory for libraries this is necessary to deal with + # platforms that can have apps built for multiple archs: e.g. x86_64 + AC_MSG_CHECKING(for Python lib dir) + PYLIBDIR=`($PYTHON -c "import sys; sys.stdout.write(sys.lib)") 2>/dev/null` + if test -z "$PYLIBDIR"; then + # Fedora patch Python to add sys.lib, for other distros we assume "lib". + PYLIBDIR="lib" + fi + AC_MSG_RESULT($PYLIBDIR) + + # Set the include directory + + AC_MSG_CHECKING(for Python header files) + if test -r $PYPREFIX/include/$PYVERSION/Python.h; then + PYINCLUDE="-I$PYPREFIX/include/$PYVERSION -I$PYEPREFIX/$PYLIBDIR/$PYVERSION/config" + fi + if test -z "$PYINCLUDE"; then + if test -r $PYPREFIX/include/Py/Python.h; then + PYINCLUDE="-I$PYPREFIX/include/Py -I$PYEPREFIX/$PYLIBDIR/python/lib" + fi + fi + AC_MSG_RESULT($PYINCLUDE) + + # Set the library directory blindly. This probably won't work with older versions + AC_MSG_CHECKING(for Python library directory) + dirs="$PYVERSION/config $PYVERSION/$PYLIBDIR python/$PYLIBDIR" + for i in $dirs; do + if test -d $PYEPREFIX/$PYLIBDIR/$i; then + PYLIB="$PYEPREFIX/$PYLIBDIR/$i" + break + fi + done + + PYLINK="-l$PYVERSION" + fi + if test -z "$PYLIB"; then AC_MSG_RESULT(Not found) else AC_MSG_RESULT($PYLIB) fi - - PYLINK="-l$PYVERSION" + AC_MSG_CHECKING(for Python library) + if test -z "$PYLINK"; then + AC_MSG_RESULT(Not found) + else + AC_MSG_RESULT($PYLINK) + fi fi # Cygwin (Windows) needs the library for dynamic linking @@ -697,11 +741,9 @@ AC_SUBST(PYTHONDYNAMICLINKING) # Look for Python 3.x #---------------------------------------------------------------- -# mostly copy & pasted from "Look for Python" section, -# did some trim, fix and rename - PY3INCLUDE= PY3LIB= +PY3LINK= PY3PACKAGE= AC_ARG_WITH(python3, AS_HELP_STRING([--without-python3], [Disable Python 3.x support]) @@ -712,7 +754,7 @@ if test x"${PY3BIN}" = xno -o x"${with_alllang}" = xno ; then AC_MSG_NOTICE([Disabling Python 3.x support]) else if test "x$PY3BIN" = xyes; then - for py_ver in 3 3.6 3.5 3.4 3.3 3.2 3.1 3.0; do + for py_ver in 3 3.9 3.8 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0 ""; do AC_CHECK_PROGS(PYTHON3, [python$py_ver]) if test -n "$PYTHON3"; then AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) @@ -726,63 +768,121 @@ else AC_CHECK_PROGS(PY3CONFIG, [$PYTHON3-config]) fi - - if test -n "$PYTHON3" -a -n "$PY3CONFIG"; then - AC_MSG_CHECKING([for Python 3.x prefix]) - PY3PREFIX=`($PY3CONFIG --prefix) 2>/dev/null` - AC_MSG_RESULT($PY3PREFIX) - AC_MSG_CHECKING(for Python 3.x exec-prefix) - PY3EPREFIX=`($PY3CONFIG --exec-prefix) 2>/dev/null` - AC_MSG_RESULT($PY3EPREFIX) - - # Note: I could not think of a standard way to get the version string from different versions. - # This trick pulls it out of the file location for a standard library file. - - AC_MSG_CHECKING([for Python 3.x version]) - - # Need to do this hack since autoconf replaces __file__ with the name of the configure file - filehack="file__" - PY3VERSION=`($PYTHON3 -c "import string,operator,os.path; print(operator.getitem(os.path.split(operator.getitem(os.path.split(string.__$filehack),0)),1))")` - AC_MSG_RESULT($PY3VERSION) - - # Find the directory for libraries this is necessary to deal with - # platforms that can have apps built for multiple archs: e.g. x86_64 - AC_MSG_CHECKING([for Python 3.x lib dir]) - PY3LIBDIR=`($PYTHON3 -c "import sys; print(sys.lib)") 2>/dev/null` - if test -z "$PY3LIBDIR"; then - # some dists don't have sys.lib so the best we can do is assume lib - PY3LIBDIR="lib" + PYVER=0 + if test -n "$PYTHON3"; then + AC_MSG_CHECKING([for $PYTHON3 major version number]) + PYVER=`($PYTHON3 -c "import sys; sys.stdout.write(sys.version[[0]])") 2>/dev/null` + AC_MSG_RESULT($PYVER) + if test -z "$PYVER"; then + PYVER=0 fi - AC_MSG_RESULT($PY3LIBDIR) + fi - # Set the include directory + if test $PYVER -ge 3; then + AC_MSG_CHECKING(for Python 3.x os.name) + PY3OSNAME=`($PYTHON3 -c "import sys, os; sys.stdout.write(os.name)")` + AC_MSG_RESULT($PY3OSNAME) - AC_MSG_CHECKING([for Python 3.x header files]) - PY3INCLUDE=`($PY3CONFIG --includes) 2>/dev/null` - AC_MSG_RESULT($PY3INCLUDE) + if test x"$PY3OSNAME" = x"nt"; then + # Windows installations are quite different to posix installations + # There is no python-config to use + AC_MSG_CHECKING(for Python 3.x prefix) + PY3PREFIX=`($PYTHON3 -c "import sys; sys.stdout.write(sys.prefix)") 2>/dev/null` + AC_MSG_RESULT($PY3PREFIX) + PY3PREFIX=`echo "$PY3PREFIX" | sed -e 's,\\\\,/,g'` # Forward slashes are easier to use and even work on Windows most of the time + PYTHON_SO=.pyd - # Set the library directory blindly. This probably won't work with older versions - AC_MSG_CHECKING([for Python 3.x library]) - dirs="$PY3VERSION/config $PY3VERSION/$PY3LIBDIR python/$PY3LIBDIR" - for i in $dirs; do - if test -d $PY3EPREFIX/$PY3LIBDIR/$i; then - PY3LIB="$PY3EPREFIX/$PY3LIBDIR/$i" - break + AC_MSG_CHECKING(for Python 3.x header files) + if test -r $PY3PREFIX/include/Python.h; then + PY3INCLUDE="-I$PY3PREFIX/include" fi - done - if test -z "$PY3LIB"; then - AC_MSG_RESULT([Not found]) - else - AC_MSG_RESULT($PY3LIB) - fi + AC_MSG_RESULT($PY3INCLUDE) - PY3LINK="-l$PY3VERSION" + AC_MSG_CHECKING(for Python 3.x library directory) + if test -d $PY3PREFIX/libs; then + PY3LIB=$PY3PREFIX/libs + PY3LINKFILE=`ls $PY3LIB/python*.lib | grep "python[[0-9]][[0-9]]\.lib"` + if test -r "$PY3LINKFILE"; then + PY3LINK=-l`basename $PY3LINKFILE | sed -e 's/\.lib$//'` + else + PY3LIB= + fi + fi + if test -z "$PY3LIB"; then + AC_MSG_RESULT([Not found]) + else + AC_MSG_RESULT($PY3LIB) + fi + AC_MSG_CHECKING([for Python 3.x library]) + if test -z "$PY3LINK"; then + AC_MSG_RESULT(Not found) + else + AC_MSG_RESULT($PY3LINK) + fi + elif test -n "$PY3CONFIG"; then + AC_MSG_CHECKING([for Python 3.x prefix]) + PY3PREFIX=`($PY3CONFIG --prefix) 2>/dev/null` + AC_MSG_RESULT($PY3PREFIX) + AC_MSG_CHECKING(for Python 3.x exec-prefix) + PY3EPREFIX=`($PY3CONFIG --exec-prefix) 2>/dev/null` + AC_MSG_RESULT($PY3EPREFIX) + + # Note: I could not think of a standard way to get the version string from different versions. + # This trick pulls it out of the file location for a standard library file. + + AC_MSG_CHECKING([for Python 3.x version]) + + # Need to do this hack since autoconf replaces __file__ with the name of the configure file + filehack="file__" + PY3VERSION=`($PYTHON3 -c "import string,operator,os.path; print(operator.getitem(os.path.split(operator.getitem(os.path.split(string.__$filehack),0)),1))")` + AC_MSG_RESULT($PY3VERSION) + + # Find the directory for libraries this is necessary to deal with + # platforms that can have apps built for multiple archs: e.g. x86_64 + AC_MSG_CHECKING([for Python 3.x lib dir]) + PY3LIBDIR=`($PYTHON3 -c "import sys; print(sys.lib)") 2>/dev/null` + if test -z "$PY3LIBDIR"; then + # some dists don't have sys.lib so the best we can do is assume lib + PY3LIBDIR="lib" + fi + AC_MSG_RESULT($PY3LIBDIR) + + # Set the include directory + + AC_MSG_CHECKING([for Python 3.x header files]) + PY3INCLUDE=`($PY3CONFIG --includes) 2>/dev/null` + AC_MSG_RESULT($PY3INCLUDE) + + # Set the library directory blindly. This probably won't work with older versions + AC_MSG_CHECKING([for Python 3.x library directory]) + dirs="$PY3VERSION/config $PY3VERSION/$PY3LIBDIR python/$PY3LIBDIR" + for i in $dirs; do + if test -d $PY3EPREFIX/$PY3LIBDIR/$i; then + PY3LIB="$PY3EPREFIX/$PY3LIBDIR/$i" + break + fi + done + if test -z "$PY3LIB"; then + AC_MSG_RESULT([Not found]) + else + AC_MSG_RESULT($PY3LIB) + fi + + PY3LINK="-l$PY3VERSION" + + AC_MSG_CHECKING([for Python 3.x library]) + if test -z "$PY3LINK"; then + AC_MSG_RESULT(Not found) + else + AC_MSG_RESULT($PY3LINK) + fi + fi fi # Cygwin (Windows) needs the library for dynamic linking case $host in *-*-cygwin* | *-*-mingw*) - PYTHON3DYNAMICLINKING="-L$PYLIB $PY3LINK" + PYTHON3DYNAMICLINKING="-L$PY3LIB $PY3LINK" DEFS="-DUSE_DL_IMPORT $DEFS" ;; *)PYTHON3DYNAMICLINKING="";; @@ -930,7 +1030,7 @@ fi if test -n "$OCTAVE"; then AC_MSG_CHECKING([for mkoctfile]) - mkoctfile="`dirname ${OCTAVE}`/mkoctfile" + mkoctfile="$(dirname $OCTAVE)/$(basename $OCTAVE | sed -e 's/octave/mkoctfile/')" AS_IF([test -x "${mkoctfile}"],[ AC_MSG_RESULT([${mkoctfile}]) ],[ @@ -1108,48 +1208,62 @@ fi AC_MSG_CHECKING(for java include file jni.h) AC_ARG_WITH(javaincl, [ --with-javaincl=path Set location of Java include directory], [JAVAINCDIR="$withval"], [JAVAINCDIR=]) +JAVAINC="" if test -z "$JAVAINCDIR" ; then JAVAINCDIR="/usr/j2sdk*/include /usr/local/j2sdk*/include /usr/jdk*/include /usr/local/jdk*/include /opt/j2sdk*/include /opt/jdk*/include /usr/java/include /usr/java/j2sdk*/include /usr/java/jdk*/include /usr/local/java/include /opt/java/include /usr/include/java /usr/local/include/java /usr/lib/java/include /usr/lib/jvm/java*/include /usr/lib64/jvm/java*/include /usr/include/kaffe /usr/local/include/kaffe /usr/include" # Add in default installation directory on Windows for Cygwin case $host in - *-*-cygwin* | *-*-mingw*) JAVAINCDIR="c:/Program*Files/Java/jdk*/include d:/Program*Files/Java/jdk*/include c:/j2sdk*/include d:/j2sdk*/include c:/jdk*/include d:/jdk*/include $JAVAINCDIR";; + *-*-cygwin* | *-*-mingw*) JAVAINCDIR="c:/Program*Files*/Java/jdk*/include d:/Program*Files*/Java/jdk*/include c:/j2sdk*/include d:/j2sdk*/include c:/jdk*/include d:/jdk*/include $JAVAINCDIR";; *-*-darwin*) JAVAINCDIR="/System/Library/Frameworks/JavaVM.framework/Headers $JAVAINCDIR";; *);; esac -fi -JAVAINC="" -for d in $JAVAINCDIR ; do - if test -r "$d/jni.h" ; then - AC_MSG_RESULT($d) - JAVAINCDIR=$d - JAVAINC=-I\"$d\" - break + for d in $JAVAINCDIR ; do + if test -r "$d/jni.h" ; then + JAVAINCDIR=$d + JAVAINC=-I\"$d\" + break + fi + done +else + if test -r "$JAVAINCDIR/jni.h" ; then + JAVAINC=-I\"$JAVAINCDIR\" fi -done +fi if test "$JAVAINC" = "" ; then AC_MSG_RESULT(not found) else + AC_MSG_RESULT($JAVAINC) # now look for /jni_md.h AC_MSG_CHECKING(for java include file jni_md.h) JAVAMDDIR=`find "$JAVAINCDIR" -follow -name jni_md.h -print` if test "$JAVAMDDIR" = "" ; then AC_MSG_RESULT(not found) else - JAVAMDDIR=`dirname "$JAVAMDDIR" | tail -1` - JAVAINC="${JAVAINC} -I\"$JAVAMDDIR\"" + JAVAMDDIR=-I\"`dirname "$JAVAMDDIR" | tail -1`\" AC_MSG_RESULT($JAVAMDDIR) + JAVAINC="${JAVAINC} ${JAVAMDDIR}" fi fi +case $host in +*-*-cygwin*) + # TODO: Only use this flag if the compiler supports it, later versions of gcc no longer have it + GCC_MNO_CYGWIN=" -mno-cygwin" + ;; +*) + GCC_MNO_CYGWIN="" + ;; +esac + # java.exe on Cygwin requires the Windows standard (Pascal) calling convention as it is a normal Windows executable and not a Cygwin built executable case $host in *-*-cygwin* | *-*-mingw*) if test "$GCC" = yes; then - JAVADYNAMICLINKING=" -mno-cygwin -mthreads -Wl,--add-stdcall-alias" - JAVACFLAGS="-mno-cygwin -mthreads" + JAVADYNAMICLINKING="$GCC_MNO_CYGWIN -mthreads -Wl,--add-stdcall-alias" + JAVACFLAGS="$GCC_MNO_CYGWIN -mthreads" else JAVADYNAMICLINKING="" JAVACFLAGS="" @@ -1185,6 +1299,15 @@ case $host in esac fi +# Quote for spaces in path to executables +if test -n "$JAVA"; then + JAVA=\"$JAVA\" +fi +if test -n "$JAVAC"; then + JAVAC=\"$JAVAC\" +fi + + AC_SUBST(JAVA) AC_SUBST(JAVAC) AC_SUBST(JAVAINC) @@ -1745,19 +1868,18 @@ AC_SUBST(PHPINC) # Look for ocaml #---------------------------------------------------------------- -AC_ARG_WITH(ocaml, AS_HELP_STRING([--without-ocaml], [Disable OCaml]) -AS_HELP_STRING([--with-ocaml=path], [Set location of ocaml executable]),[ OCAMLBIN="$withval"], [OCAMLBIN=yes]) +AC_ARG_WITH(ocaml, AS_HELP_STRING([--without-ocaml], [Disable OCaml]), [with_ocaml="$withval"], [with_ocaml=yes]) AC_ARG_WITH(ocamlc,[ --with-ocamlc=path Set location of ocamlc executable],[ OCAMLC="$withval"], [OCAMLC=]) AC_ARG_WITH(ocamldlgen,[ --with-ocamldlgen=path Set location of ocamldlgen],[ OCAMLDLGEN="$withval" ], [OCAMLDLGEN=]) AC_ARG_WITH(ocamlfind,[ --with-ocamlfind=path Set location of ocamlfind],[OCAMLFIND="$withval"],[OCAMLFIND=]) AC_ARG_WITH(ocamlmktop,[ --with-ocamlmktop=path Set location of ocamlmktop executable],[ OCAMLMKTOP="$withval"], [OCAMLMKTOP=]) +AC_ARG_WITH(camlp4,[ --with-camlp4=path Set location of camlp4 executable],[ CAMLP4="$withval"], [CAMLP4=]) # First, check for "--without-ocaml" or "--with-ocaml=no". -if test x"${OCAMLBIN}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_ocaml}" = xno -o x"${with_alllang}" = xno ; then AC_MSG_NOTICE([Disabling OCaml]) - OCAMLBIN= + OCAMLC= else - AC_MSG_CHECKING(for Ocaml DL load generator) if test -z "$OCAMLDLGEN"; then AC_CHECK_PROGS(OCAMLDLGEN, ocamldlgen, :) @@ -1773,60 +1895,22 @@ else AC_CHECK_PROGS(OCAMLC, ocamlc, :) fi - AC_MSG_CHECKING(for Ocaml interpreter) - if test "x$OCAMLBIN" = xyes; then - AC_CHECK_PROGS(OCAMLBIN, ocaml, :) - fi - AC_MSG_CHECKING(for Ocaml toplevel creator) if test -z "$OCAMLMKTOP"; then AC_CHECK_PROGS(OCAMLMKTOP, ocamlmktop, :) fi - OCAMLLOC=loc - if test "$OCAMLC" != ":" ; then - AC_MSG_CHECKING(for Ocaml header files) - dirs="/usr/lib/ocaml/caml /usr/local/lib/ocaml/caml" - dir="`$OCAMLC -where 2>/dev/null`" - if test "$dir"; then - dirs="$dir/caml $dirs" - fi - for i in $dirs; do - if test -r $i/mlvalues.h; then - AC_MSG_RESULT($i) - OCAMLEXT="$i" - OCAMLINC="-I$OCAMLEXT" - break - fi - done - if test -z "$OCAMLINC"; then - AC_MSG_RESULT(not found) - fi - - AC_MSG_CHECKING(for Ocaml version 3.08.2 or higher) - OCAMLVER=`$OCAMLC -version | sed -e 's/.*version //g'` - AC_COMPARE_VERSION([$OCAMLVER],[3.08.2],[:],[:],[OCAMLLOC=_loc]) - AC_MSG_RESULT($OCAMLVER) + AC_MSG_CHECKING(for Ocaml Pre-Processor-Pretty-Printer) + if test -z "$CAMLP4"; then + AC_CHECK_PROGS(CAMLP4, camlp4, :) fi fi # Disabling ocaml -export OCAMLLOC -export OCAMLVER -export OCAMLINC -export OCAMLBIN -export OCAMLC -export OCAMLDLGEN -export OCAMLFIND -export OCAMLMKTOP - -AC_SUBST(OCAMLLOC) -AC_SUBST(OCAMLVER) -AC_SUBST(OCAMLINC) -AC_SUBST(OCAMLBIN) AC_SUBST(OCAMLC) AC_SUBST(OCAMLDLGEN) AC_SUBST(OCAMLFIND) AC_SUBST(OCAMLMKTOP) +AC_SUBST(CAMLP4) #---------------------------------------------------------------- # Look for Pike @@ -2032,8 +2116,7 @@ else CSHARPCOMPILER="$CSHARPCOMPILERBIN" fi -CSHARPPATHSEPARATOR="/" -CSHARPCYGPATH_W=echo +CSHARPCONVERTPATH="Tools/convertpath -u" if test -z "$CSHARPBIN" ; then CSHARPCILINTERPRETER="" CSHARPCILINTERPRETER_FLAGS="" @@ -2060,8 +2143,7 @@ if test -z "$CSHARPBIN" ; then CSHARPCILINTERPRETER_FLAGS="--debug" else if test "csc" = "$CSHARPCOMPILER"; then - CSHARPPATHSEPARATOR="\\\\" - CSHARPCYGPATH_W='cygpath -w' + CSHARPCONVERTPATH="Tools/convertpath -w" fi fi fi @@ -2073,8 +2155,8 @@ fi case $host in *-*-cygwin* | *-*-mingw*) if test "$GCC" = yes; then - CSHARPDYNAMICLINKING=" -mno-cygwin -mthreads -Wl,--add-stdcall-alias" - CSHARPCFLAGS="-mno-cygwin -mthreads" + CSHARPDYNAMICLINKING="$GCC_MNO_CYGWIN -mthreads -Wl,--add-stdcall-alias" + CSHARPCFLAGS="$GCC_MNO_CYGWIN -mthreads" else CSHARPDYNAMICLINKING="" CSHARPCFLAGS="" @@ -2104,11 +2186,10 @@ fi AC_SUBST(CSHARPCILINTERPRETER_FLAGS) AC_SUBST(CSHARPCILINTERPRETER) -AC_SUBST(CSHARPPATHSEPARATOR) -AC_SUBST(CSHARPCYGPATH_W) +AC_SUBST(CSHARPCONVERTPATH) AC_SUBST(CSHARPCOMPILER) AC_SUBST(CSHARPDYNAMICLINKING) -AC_SUBST(CSHARPLIBRARYPREFIX) # Is this going to be used? +AC_SUBST(CSHARPLIBRARYPREFIX) AC_SUBST(CSHARPCFLAGS) AC_SUBST(CSHARPSO) @@ -2319,109 +2400,116 @@ if test x"${GOBIN}" = xno -o x"${with_alllang}" = xno ; then GO1=false GO12=false GO13=false + GO15=false GOGCC=false + GCCGO= GOOPT= + GCCGOOPT= GOVERSIONOPTION= else if test "x$GOBIN" = xyes; then - AC_CHECK_PROGS(GO, go 6g 8g gccgo) + AC_CHECK_PROGS(GO, go) else GO="$GOBIN" fi GOGCC=false + GCCGO= GO1=false GO12=false GO13=false + GO15=false GOOPT= + GCCGOOPT= GOVERSIONOPTION= + if test -n "$GO" ; then - if $GO --help 2>/dev/null | grep gccgo >/dev/null 2>&1 ; then - GOGCC=true - GOVERSIONOPTION=--version + GO1=true + GOVERSIONOPTION=version + go_version=$($GO $GOVERSIONOPTION | sed -e 's/go version //') + case "$go_version" in + go1 | go1.[[01234]]*) + GOC=$(sh -c "$(go env) && echo \$GOCHAR")c + ;; + *) + GOC=compile + ;; + esac + AC_MSG_CHECKING([whether go version is too old]) + case $go_version in + go1.0* | go1 ) + AC_MSG_RESULT([yes - minimum version is 1.1]) + GO= + GOOPT="-intgosize 32" + ;; + *) + AC_MSG_RESULT([no]) + case "$(go env GOARCH)" in + amd64 | arm64 | ppc64*) + GOOPT="-intgosize 64" + ;; + *) + GOOPT="-intgosize 32" + ;; + esac + ;; + esac + case $go_version in + go1.0* | go1 | go1.1*) + GOOPT="$GOOPT -use-shlib" + ;; + go1.2*) + GO12=true + ;; + go1.3* | go1.4*) + GO13=true + ;; + *) + GO15=true + ;; + esac + fi + + AC_CHECK_PROGS(GCCGO, gccgo) + + if test -n "$GCCGO" ; then + if $GCCGO --help 2>/dev/null | grep gccgo >/dev/null 2>&1 ; then AC_MSG_CHECKING([whether gccgo version is too old]) go_version=[`$GO $GOVERSIONOPTION | sed -n '1p' | sed -e 's/^.* \([0-9.]*\) *$/\1/' -e 's/[.]//g'`] if test "x$go_version" = x; then - AC_MSG_RESULT([could not determine gccgo version - disabling Go]) - GO= + AC_MSG_RESULT([could not determine gccgo version]) + GCCGO= elif test "$go_version" -lt 470; then AC_MSG_RESULT([yes - minimum version is 4.7.0]) - GO= + GCCGO= else - AC_MSG_RESULT([no]) + AC_MSG_RESULT([no]) if test "$go_version" -lt 480; then - GOOPT="-intgosize 32" - else - AC_CHECK_SIZEOF([void *], [4]) - if test "$ac_cv_sizeof_void_p" = "8"; then - GOOPT="-intgosize 64" - else - GOOPT="-intgosize 32" - fi + GCCGOOPT="-intgosize 32" + else + AC_CHECK_SIZEOF([void *], [4]) + if test "$ac_cv_sizeof_void_p" = "8"; then + GCCGOOPT="-intgosize 64" + else + GCCGOOPT="-intgosize 32" + fi fi fi - elif test "`echo $GO | sed -e 's|.*/||'`" = "go"; then - GO1=true - GOVERSIONOPTION=version - GOC=$(sh -c "$(go env) && echo \$GOCHAR")c - go_version=$($GO $GOVERSIONOPTION | sed -e 's/go version //') - AC_MSG_CHECKING([whether go version is too old]) - case $go_version in - go1.0* | go1 ) - AC_MSG_RESULT([yes - minimum version is 1.1]) - GO= - GOOPT="-intgosize 32" - ;; - *) - AC_MSG_RESULT([no]) - if test "$GOC" = "6c"; then - GOOPT="-intgosize 64" - else - GOOPT="-intgosize 32" - fi - ;; - esac - case $go_version in - go1.0* | go1 | go1.1*) - GOOPT="$GOOPT -use-shlib" - ;; - go1.2*) - GO12=true - ;; - *) - GO13=true - ;; - esac - else - GOC=`echo $GO | sed -e 's/g/c/'` - GOVERSIONOPTION=-V - AC_MSG_CHECKING([whether Go ($GO) version is too old]) - AC_MSG_RESULT([yes - minimum version is 1.1]) - GO= - dnl Old code retained for now in case we implement an option for it. - dnl go_version=`$GO $GOVERSIONOPTION 2>/dev/null | sed -e 's/.*version.* \([[0-9]]*\).*/\1/'` - dnl go_min_version=7077 - dnl if test "$go_version" != "" -a "$go_version" -lt $go_min_version; then - dnl AC_MSG_RESULT([yes - minimum version is $go_min_version]) - dnl GO= - dnl else - dnl AC_MSG_RESULT([no]) - dnl fi - GOOPT="-intgosize 32" - GO12=false - GO13=false fi fi fi AC_SUBST(GOGCC) +AC_SUBST(GCCGO) AC_SUBST(GO) AC_SUBST(GOC) AC_SUBST(GO1) AC_SUBST(GO12) AC_SUBST(GO13) +AC_SUBST(GO15) AC_SUBST(GOOPT) +AC_SUBST(GCCGOOPT) AC_SUBST(GOVERSIONOPTION) #---------------------------------------------------------------- @@ -2534,14 +2622,14 @@ AC_SUBST(SKIP_OCTAVE) SKIP_PYTHON= -if (test -z "$PYINCLUDE") && - (test -z "$PY3INCLUDE") ; then +if (test -z "$PYINCLUDE" || test -z "$PYLINK") && + (test -z "$PY3INCLUDE" || test -z "$PY3LINK") ; then SKIP_PYTHON="1" fi AC_SUBST(SKIP_PYTHON) SKIP_PYTHON3= -if test -z "$PY3INCLUDE" ; then +if test -z "$PY3INCLUDE" || test -z "$PY3LINK" ; then SKIP_PYTHON3="1" fi AC_SUBST(SKIP_PYTHON3) @@ -2587,7 +2675,7 @@ AC_SUBST(SKIP_PHP) SKIP_OCAML= -if test -z "$OCAMLBIN" || test -z "$OCAMLINC" ; then +if test -z "$OCAMLC" ; then SKIP_OCAML="1" fi AC_SUBST(SKIP_OCAML) @@ -2701,15 +2789,21 @@ AC_SUBST(SKIP_ANDROID) # Miscellaneous #---------------------------------------------------------------- +ABS_SRCDIR=`(cd ${srcdir} && pwd)` # Root directory -# Translate path for native Windows compilers for use with 'make check' ROOT_DIR=`pwd` case $host in -*-*-cygwin* | *-*-mingw*) +*-*-cygwin*) + # Translate path for native Windows compilers for use with 'make check' if (cygpath --mixed $ROOT_DIR) >/dev/null 2>/dev/null; then ROOT_DIR=`cygpath --mixed $ROOT_DIR` fi + ;; +esac + +case $host in +*-*-cygwin* | *-*-mingw*) # Extra files generated by some Windows compilers EXTRA_CLEAN="*.stackdump *.exp *.lib *.pdb *.ilk" ;; @@ -2734,6 +2828,14 @@ case $build in esac AC_DEFINE_UNQUOTED(SWIG_LIB_WIN_UNIX, ["$SWIG_LIB_WIN_UNIX"], [Directory for SWIG system-independent libraries (Unix install on native Windows)]) +# For testing - Windows builds of SWIG do not need SWIG_LIB set +AC_EGREP_CPP([yes], +[#ifdef _WIN32 + yes +#endif +], [SWIG_LIB_PREINST=], [SWIG_LIB_PREINST=$ABS_SRCDIR/Lib]) +AC_SUBST(SWIG_LIB_PREINST) + AC_CONFIG_FILES([ Makefile swig.spec diff --git a/preinst-swig.in b/preinst-swig.in index 384593ce1..e77db7858 100755 --- a/preinst-swig.in +++ b/preinst-swig.in @@ -1,7 +1,5 @@ #!/bin/sh builddir=`dirname $0` -srcdir=`cd "$builddir" && cd '@srcdir@' && pwd` -SWIG_LIB=$srcdir/Lib -#SWIG_LIB=`cygpath -w $srcdir/Lib` # For native Windows version of SWIG +SWIG_LIB=@SWIG_LIB_PREINST@ export SWIG_LIB exec "$builddir/swig" "$@"